assign keys for combo box in java

家住魔仙堡 提交于 2019-12-02 09:26:50

You can add an item as an object instead of adding String like this:

JComboBox<ItemClass> jc = new JComboBox<ItemClass>();
    jc.addItem(item1);
    jc.addItem(item2);
    jc.addItem(item3);

So to return key, the function of the event is : jc.getSelectedItem().getKey Doing this way you have to override the toString() function of class ItemClass to return the string you want to show in combobox.

Btw, for return number, you may try : jc.getSelectedIndex(), it'll return your index of your string (0 1 2 for "a" "b" "c")

mhshams

you can create your own Model and add it to the combo box instead of adding Strings directly.

check Java ComboBoxModel.

you can find more info in this thread

Wrap your data in a simple class:

class MyData {
  int value;
  String text;
  ...
}

Now you can write your own renderer by extending BasicComboBoxRenderer. Cast the "value" to "MyData" and render the text.

public class Bla extends BasicComboBoxRenderer{

@Override
public Component getListCellRendererComponent(JList list, Object value,
        int index, boolean isSelected, boolean cellHasFocus) {
    if(value instanceof MyData) {
        setText(((MyData) value).getText());
    }
    return super.getListCellRendererComponent(list, value, index, isSelected,
            cellHasFocus);
}
}

if you use Java7 it is best practice to use generics like @Taiki has shown. Now you can get the selected object by jc.getSelectedItem(). It is always from type MyData and you can access the text ("a", "b", etc.) and the value (1, 2, 3, etc.)

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!