[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 240
  • Last Modified:

Unique Selections in ComboBoxes

I inherented this issue and asked to fix it.  I am having a problem trying to figure out how to do it.

I have 3 comboBoxes on my dialog

keyUserModel = new MyListModelkeyUserModel = new MyListModel(info.keyUserIds);
      keyUserComboBox = new JComboBox(keyUserModel);
      keyUserComboBox.setPreferredSize(keyUserComboBox.getPreferredSize());
      keyUserModel.setSelectedItem(keyUserModel.id2Name(session.getCredentials().getUserName()));
     
      amePmeModel = new MyListModel(info.amePmeIds);
      amePmeComboBox = new JComboBox(amePmeModel);
      
      amePmeAltModel = new MyListModel(info.amePmeIds);
      amePmeAltComboBox = new JComboBox(amePmeAltModel););
     

Open in new window


info.keyUserIds in the KeyUser ComboBox is a List of usernames
info.amePmeIds in the amePme ComboBox is a List of usernames
amePmeAlt ComboBox is using the same list as amePme

So there are 3 boxes and 2 list

Heres the problem each box has to have a unique name and can not be able to be selected in the other boxes.

example

Combobox        user selection from the list

KeyUser        -> jkteater
amePme       -> for_yan
amePmeAlt   -> jkteater

The above it not allowed

KeyUser        -> jkteater
amePme       -> for_yan
amePmeAlt   -> CEHj

The above is the way it should be

Here is what I am thinking but not sure how to do it.

When the Keyuser is selected - we stored the value
go to the amepme list find the value and remove it from the list
when the amepme is selected - we store it and remove from the list

That way they can not select the value from the list - any ideas??

 
0
jkteater
Asked:
jkteater
  • 18
  • 17
1 Solution
 
for_yanCommented:
You may be better off with JCheckBox group - which allows to slect only one of the group of the checkboxes - how may item would you have in the list?
0
 
for_yanCommented:
More complex issue is to associate the combobox with the ItemListener and in the itemStateChanged() method modify the underlying list ofr other comboboxes
0
 
jkteaterAuthor Commented:
I am afraid that I have to use the combo boxes.  I have no clue even how to start this one.
0
Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

 
for_yanCommented:
>I have no clue even how to start this one

what you mean by that?

You need to do something like that:

Declare in your class "implements ItemListener"

then .addItemListener(this);

to your comboboxes

and define method:

public void itemStateChanged(ItemEvent ie) {
if(ie.getSource().equals(combobox1) {
String selecetdString = combobox.getSelectedItem();

// and then change the list for other comboboxes here


}


}


It ois not much differet than with other events
0
 
jkteaterAuthor Commented:
Let me paste what the class looks like and you can give me some pointers


public class RequestTransmittalDialog extends JDialog  {
   private TCSession session = null;
   private Registry appReg = null;
   boolean cancelled = false;
   private EdiProject project = null;
   MyListModel keyUserModel;
   MyListModel amePmeModel;
   MyListModel amePmeAltModel;
   protected JTextArea textArea;
   JComboBox  keyUserComboBox;
   JComboBox  amePmeComboBox;
   JComboBox  amePmeAltComboBox;
   JLabel keyUserLabel = null;
   JLabel amePmeLabel = null;
   JLabel commentLabel = null;
   JLabel amePmeAltLabel = null;
   SingletonSelectTable myModel;

   //ItemRevisionCommentsWidget ircw;

   private class MyListModel extends AbstractListModel implements ComboBoxModel {
      private TreeMap names2Ids;
      private Object  selKey;

      public MyListModel(List loginIds) {
         super();

         names2Ids = new TreeMap();
         for (int i = 0; i < loginIds.size(); ++i) {
            String id = (String) loginIds.get(i);
            names2Ids.put(id2Name(id), id);
         }

         selKey = null;
      } // end constructor

      public int getSize() {
         return names2Ids.size();
      } // end getSize()

      public Object getElementAt(int idx) {
         Iterator iter = names2Ids.entrySet().iterator();
         int i = 0;
         while (iter.hasNext()) {
            Map.Entry e = (Map.Entry) iter.next();
            if (i == idx) {
               return e.getKey();
            }
            ++i;
         }
         return null;
      } // end getElementAt()


      public Object getSelectedItem() {
         if ((selKey == null) || (!names2Ids.containsKey(selKey))) {
            return null;
         }
         return selKey;
      } // end getSelectedItem()

      public Object getSelectedId() {
         if ((selKey == null) || (!names2Ids.containsKey(selKey))) {
            return null;
         }
         return names2Ids.get(selKey);
      } // end getSelectedId()


      public void setSelectedItem(Object item) {
         if (names2Ids.containsKey(item)) {
            selKey = item;
         }
         else {
            selKey = null;
         }
      } // end setSelectedItem()


      public String id2Name(String id) {
         StringBuffer sb = new StringBuffer();
         Login l = EdiSystemData.getLoginFromId(id);
         if (l != null) {
            sb.append(l.getDisplayName());
            sb.append(" (" + id + ")");
         }
         else {
            sb.append(id);
         }
         return sb.toString();
      } // end addName()
   } // end MyListModel

   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                              Constructor                             //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   public RequestTransmittalDialog(EdiGetRequestTransmittalInfoOperation.TransmittalInfo info,
                                   List workItems,
                                   EdiProject currentProject,
                                   Dialog parent,
                                   TCSession theSession,
                                   Registry theRegistry) {
      super(parent, true);
      session = theSession;
      appReg = theRegistry;
      project = currentProject;
      myModel = SingletonSelectTable.getInstance();
      createDialog(info);
      //ircw.setList(workItems);
   } // end constructor



   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                             createDialog()                           //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private void createDialog(EdiGetRequestTransmittalInfoOperation.TransmittalInfo info) {
      JPanel userPanel = createUserPanel(info);
      JPanel buttonPanel = createButtonPanel();
      //ircw = new ItemRevisionCommentsWidget(appReg);
      setTitle(appReg.getString("edi.reqtrans.title"));
      JPanel p = new JPanel();
      p.setPreferredSize(new Dimension(450, 300));
      p.setLayout(new BoxLayout(p, BoxLayout.PAGE_AXIS));
      
      p.add(userPanel);
      //p.add(ircw);
      p.add(Box.createRigidArea(new Dimension(0, 10)));
      p.add(buttonPanel);

      getContentPane().add(p);
      pack();
      setLocation(getParent().getLocation(null));
   } // end createDialog()
  
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                          createButtonPanel()                         //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private JPanel createButtonPanel() {
      JButton sendReqButton = new JButton(appReg.getString("edi.reqtrans.sendReqButton." + AIFConstants.NAME));
      sendReqButton.setMnemonic(appReg.getChar("edi.projects.select." + AIFConstants.MNEMONIC, 'S'));
      sendReqButton.setEnabled(true);
      sendReqButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
        	 myModel.clearList();
        	 myModel.clearcommentToString();
        	 dispose();
         }
      });

      JButton cancelButton = new JButton(appReg.getString("edi.cancel." + AIFConstants.NAME));
      cancelButton.setMnemonic(appReg.getChar("edi.cancel." + AIFConstants.MNEMONIC, 'C'));
      cancelButton.setEnabled(true);
      cancelButton.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent e) {
            cancelled = true;
            
            dispose();
         }
      });

      JPanel p = new JPanel();
      p.setLayout(new BoxLayout(p, BoxLayout.LINE_AXIS));
      p.add(Box.createHorizontalGlue());
      p.add(sendReqButton);
      p.add(cancelButton);
      return p;
   } // end createButtonPanel()

   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                           createUserPanel()                          //
   //                                                                      //
   //////////////////////////////////////////////////////////////////////////
   private JPanel createUserPanel(EdiGetRequestTransmittalInfoOperation.TransmittalInfo info) {
	    
	  textArea = new JTextArea(5, 20);
	  JScrollPane scrollPane = new JScrollPane(textArea);
	  textArea.setEditable(false);
	  textArea.setText(myModel.commentToString());
	  
	  keyUserModel = new MyListModel(info.keyUserIds);
      keyUserComboBox = new JComboBox(keyUserModel);
      keyUserComboBox.setPreferredSize(keyUserComboBox.getPreferredSize());
      keyUserModel.setSelectedItem(keyUserModel.id2Name(session.getCredentials().getUserName()));
     
      amePmeModel = new MyListModel(info.amePmeIds);
      amePmeComboBox = new JComboBox(amePmeModel);
      
      amePmeAltModel = new MyListModel(info.amePmeIds);
      amePmeAltComboBox = new JComboBox(amePmeAltModel);
      
      JPanel p = new JPanel();
      GridBagLayout gridbag = new GridBagLayout();
      p.setLayout(gridbag);
      gbc.insets = new Insets(5,10,10,5); 
      
      set_gbc(1, 0, 1, 1,GridBagConstraints.HORIZONTAL );
      keyUserLabel = new JLabel(appReg.getString("edi.reqtrans.keyUser"));
      gridbag.setConstraints(keyUserLabel, gbc);
      p.add(keyUserLabel);
      
      set_gbc(1, 1, 1, 1,GridBagConstraints.HORIZONTAL);
      gridbag.setConstraints(keyUserComboBox, gbc);
      p.add(keyUserComboBox);
      
      set_gbc(2, 0, 1, 1,GridBagConstraints.HORIZONTAL );
      amePmeLabel = new JLabel(appReg.getString("edi.reqtrans.amePmes"));
      gridbag.setConstraints(amePmeLabel, gbc);
      p.add(amePmeLabel);
      
      set_gbc(2, 1, 1, 1,GridBagConstraints.HORIZONTAL);
      gridbag.setConstraints(amePmeComboBox, gbc);
      p.add(amePmeComboBox);
            
      set_gbc(3, 0, 1, 1,GridBagConstraints.HORIZONTAL );
      amePmeAltLabel = new JLabel(appReg.getString("edi.reqtrans.amePmeAlts"));
      gridbag.setConstraints(amePmeAltLabel, gbc);
      p.add(amePmeAltLabel);
     
      set_gbc(3, 1, 1, 1,GridBagConstraints.NONE);
      gridbag.setConstraints(amePmeAltComboBox, gbc);
      p.add(amePmeAltComboBox);
      
      set_gbc(4, 0, 1, 1,GridBagConstraints.HORIZONTAL );
      commentLabel = new JLabel("Comments:");
      gridbag.setConstraints(commentLabel, gbc);
      p.add(commentLabel);
     
      set_gbc(4, 1, 1, 1,GridBagConstraints.HORIZONTAL);
      gridbag.setConstraints(scrollPane, gbc);
      p.add(scrollPane);
     

      return p;
   } // end createUserPanel()
   
   //////////////////////////////////////////////////////////////////////////
   //                                                                      //
   //                           set_gbc()                                  //
   //                       GridBagConstraints                             //
   //                                                                      // 
   //////////////////////////////////////////////////////////////////////////
   GridBagConstraints gbc = new GridBagConstraints();
   protected boolean alreadyEnabled;

   private void set_gbc(int row, int column, int width, int height, int fill) {
      gbc.gridy = row;
      gbc.gridx = column;
      gbc.gridwidth = width;
      gbc.gridheight = height;
      gbc.fill = fill;   // GridBagConstraints.NONE .HORIZONTAL .VERTICAL .BOTH
   }
} // end class RequestTransmittalDialog

Open in new window

0
 
for_yanCommented:
Ok I'll look at it when I reach my computer
0
 
for_yanCommented:
Well, that's long code which I anyway cannot execute - that's not very useful to me - i'm not a compiler.

One thing is you probably don't need any ComboBoxModel - that;s way too complicated
just have

Vector<String> v = new Vector<String>();
v.addElement("name1");
v.addElement("name2");
..

JComboBox cb = new JComboBox(v);

and you don't need any combobox model so compilicated
and after that you can removeItem, addItem - all without any complicated models




0
 
for_yanCommented:

You ned to do somthing like that:

public class RequestTransmittalDialog extends JDialog  implements ItemListener {

then below after you create comobobox, say after

keyUserComboBox = new JComboBox(keyUserModel);

keyUserComboBox.addItemListener(this);

and then create a method

public void itemStateChanged(ItemEvent ie) {
if(ie.getSource().equals(keyUserComboBox)){
String s = keyUserComboBox.getSelectedItem();

// then modify your  model for another combobox, contents of which depend ion this selection
// and setModel to that combobox, 

}

if(ie.getSource().equals(anotherComboBox)){

// similar operation here

}



}

Open in new window



0
 
jkteaterAuthor Commented:
@Override
public void itemStateChanged(ItemEvent ie) {
	 if(ie.getSource().equals(keyUserComboBox)){
	   	   String s = (String) keyUserComboBox.getSelectedItem();
	   	   System.out.println("Key : " + s + "\n");
	   	   boolean blnFound = infoList.amePmeIds.contains(s);
	       System.out.println("Does arrayList contain String ? " + blnFound);
     }
}

Open in new window


So now I have the selection and assigned it to S.  Do I see if the amepme list has a matching value (see Above)
then remove the value from that list?
0
 
for_yanCommented:
Yes, you can probably even try to remove it without even checking - I think
if it has, it will remove if not it should not throw the error
0
 
jkteaterAuthor Commented:
I think this is my problem.

keyUserModel = new MyListModel(info.keyUserIds);

Open in new window


I think that info.keyUserIds is a list of shortnames (ex: jkteater )
MyListModel is a class within the RequestTransmittalDialog class.

private class MyListModel extends AbstractListModel implements ComboBoxModel {

Open in new window


I think that MyListModel is taking the list of shortnames and returning  "Jack Teater (jkteater)"

so in the combo box the selection is Jack Teater (jkteater) and not jkteater so there is no match

so I need to figure out how to make
 boolean blnFound = infoList.amePmeIds.contains(s);

Open in new window

be formatted with myListModel
0
 
for_yanCommented:
you can always extract the parentheses from your string

String s1 = s.substring(s.indexOf("("), s.indexof(")")+1);

This should give you "(jkteater)" out of "Jack Teater (jkteater)"
0
 
for_yanCommented:
Or even better
String s1 = s.substring(s.indexOf("("));
becuase the closing parenthese is the end of your string
0
 
jkteaterAuthor Commented:
great idea - let me try it
0
 
jkteaterAuthor Commented:
can we remove the brackets? instead of (jkteater) have jkteater
0
 
for_yanCommented:
This should remove:
String s1 = s.substring(s.indexOf("(")+1, s.indexof(")"));
0
 
jkteaterAuthor Commented:
what would be the best way to remove the element?


Iterator<String> itr = infoList.amePmeIds.iterator();
	       while (itr.hasNext()) {
	           String element = itr.next();
	               if (element == s1){
	                    remove(element);	
	               }
	         
	          }

Open in new window

0
 
for_yanCommented:
No you rather don't remove within iterator.
I think you remove from the list:

 loginIds.remove(string);
0
 
jkteaterAuthor Commented:
I think it is itr.remove();
0
 
for_yanCommented:
yes, it seesm thes is such method.
I'd rather remove directly form collection -- more understandable
0
 
jkteaterAuthor Commented:
Yea - my way did not work
0
 
jkteaterAuthor Commented:
so do I write a method in the myListModel Class

that will remove the string from loginIds and I can pass the string to the method?
0
 
for_yanCommented:
yes, that would be the most straighforwwrad way to my mind
0
 
jkteaterAuthor Commented:
Let me walk though what I am thinking to make sure I understand everything.

In the class MyListModel

I want to create a method that takes in 2 variables

public List removeFromList (String s1) {

loginIds.remove(s1); <- error

}

Open in new window


loginIds can not be resolved



then is the itemStateChange method (which is in the RequestTransmittalDialog class)

public void itemStateChanged(ItemEvent ie) {
	 if(ie.getSource().equals(keyUserComboBox)){
	   	   String s = (String)keyUserComboBox.getSelectedItem();
	   	   String s1 = s.substring(s.indexOf("(")+1, s.indexOf(")"));
                   myListModel.removeFromList(s1); < - error
         }
       
}

Open in new window


the myListModel is throwing a error - can not be resolved

Does this look like the right way to be doing this?
0
 
for_yanCommented:
You don't have instance variable loginIds
I think you have something called names2Id - you gete elemets from this one - you should
remove from names2Id
0
 
jkteaterAuthor Commented:
good catch
0
 
jkteaterAuthor Commented:
even though myListModel is in the same class as RequestTransmittalDialog, do I still have to make a new instance of myListModel in the constructor?
0
 
jkteaterAuthor Commented:
I think I have it - testing now
0
 
for_yanCommented:
defninitely you don't want new instance - only deal with te same one which is underlying under your checkboxes - we already went through that
0
 
jkteaterAuthor Commented:
At the risk of looking bad once again, I saw where the combo boxes was creating a new instance with each box

keyUserModel = new MyListModel(info.keyUserIds);
amePmeModel = new MyListModel(info.amePmeIds);
amePmeAltModel = new MyListModel(info.amePmeIds);

so I thought I would do something like

public void itemStateChanged(ItemEvent ie) {
       if(ie.getSource().equals(keyUserComboBox)){
                  String s = (String)keyUserComboBox.getSelectedItem();
                  String s1 = s.substring(s.indexOf("(")+1, s.indexOf(")"));
                  myList = new MyListModel(null);
                  myList.removeFromList(s1);
       }
   }

It throws a null pointer
0
 
for_yanCommented:

Look:

myList = new MyListModel(null);
                  myList.removeFromList(s1);

you aalready have Comboboxes and you have instances of objects which serve as their models - manipulate with them
Why are you creating a new instance ? Why ?

If I have a hat and you want to paint my hat in red color, why do you go to the store - buy absolutely different brand new hat, paint it red - and then
look at my hat and wondering why it did not becomer red ? That is exactly what you are doing .

Study simple examples - and understand it once and for all





0
 
jkteaterAuthor Commented:
yea - I am afraid that I figure it out a little after I submitted
0
 
jkteaterAuthor Commented:
testing now
0
 
jkteaterAuthor Commented:
I would like to thank you for your help.  I did get the issue resolved thanks to your suggestions.  As well as learning a little more about the workings of JAVA.
0
 
for_yanCommented:
You are always welcome.
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

  • 18
  • 17
Tackle projects and never again get stuck behind a technical roadblock.
Join Now