Java Tutorial on Combobox[
^]
Check that Tutorial.
What looks pretty nice:
- create an
Object
with the
String
(id?)to display and the corresponding value in it.
Make sure there is a
toString()
in the Object returning the text that should be displayed.
- add a
List
of these
Objects
to the ComboBox.
It will automatically display the strings and you will easily find the corresponding value (see Richards answer) to the displayed String.
EDIT:
See this demo. The Combobox
oComboBox
is filled with values from the Object
ComboValue
. The
ComboValue
owns a method
toString()
which provides the String for the ComboBox to display.
CustomComboBoxListener
is called as the ActionListener. He checks if the Component is the one with the ActionCommand and then extracts the value (can be done in a one-liner, here more lines to show what happens). The ActionListener just goes for the
getSelectedItem()
and does not even care for index numbers. So there can not be a "false friend" where you get the false value due to false counting.
I hope this is pretty clear - it's simple though.
For those searching for a simple code to copy for homework:
Have fun explaining the code to your teacher ;-)
public class MyFrame extends JFrame {
private JComboBox oComboBox;
private static final String ACTIONCOMMAND = "ComboBox";
public MyFrame(){
this.ignition();
}
private void ignition() {
createCombobox();
getContentPane().add(oComboBox, BorderLayout.NORTH);
}
private void createCombobox() {
oComboBox = new JComboBox(getItems());
oComboBox.setActionCommand(ACTIONCOMMAND);
oComboBox.addActionListener(new CustomComboBoxListener());
}
private ComboValue[] getItems() {
ComboValue[] oItems = new ComboValue[3];
oItems[0] = new ComboValue(123, "randomNumber 1");
oItems[1] = new ComboValue(456, "randomNumber 2");
oItems[2] = new ComboValue(789, "randomNumber 3");
return oItems;
}
private class CustomComboBoxListener implements ActionListener{
@Override
public void actionPerformed(ActionEvent oEvent) {
if(oEvent.getActionCommand().equals(ACTIONCOMMAND)){
JComboBox oBox = (JComboBox)oEvent.getSource();
ComboValue oValue = (ComboValue)oBox.getSelectedItem();
int iID = oValue.getID();
System.out.println("The selected ID is: " + iID);
}
}
}
private class ComboValue {
private int iID;
private String strName;
public ComboValue(int iID, String strName){
setID(iID);
setName(strName);
}
public void setName(String strName) {
this.strName = strName;
}
public String getName() {
return strName;
}
public void setID(int iID) {
this.iID = iID;
}
public int getID() {
return iID;
}
public String toString(){
return getName();
}
}
}