问题描述
我要在Swing是简单的添加的JComboBox
但我想要分配的值康宝每个项目。我有以下的code
I want to add a JComboBox
in Swing that is simple but I want to assign the values for each items in combo. I have the following code
JComboBox jc1= new JComboBox();
jc1.addItem("a");
jc1.addItem("b");
jc1.addItem("c");
现在我想的是,当点击组合框它应该返回1,2和3相应
代替,B,C。
有什么办法来分配在组合框中每个项目的核心价值观?
Now what I want is that when click on combo box it should return 1, 2 and 3 correspondingly instead of a ,b, c.Is there any way to assign the key values for each items in combo box?
推荐答案
您可以添加一个项目作为一个对象,而不是添加字符串是这样的:
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);
所以要返回键,事件的功能是: jc.getSelectedItem()getKey
这样做的方式已经覆盖的toString()
类itemClass时的函数返回要在组合框中显示的字符串。
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.
顺便说一句,退货数量,你可以尝试: jc.getSelectedIndex()
,它会回报你的字符串索引( 0 1 2
为AbC
)
Btw, for return number, you may try : jc.getSelectedIndex()
, it'll return your index of your string (0 1 2
for "a" "b" "c"
)
这篇关于按键分配在Java组合框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!