当我点击jComboBox中的Item时,如何在jTextField中设置值?

时间:2017-03-08 15:47:07

标签: java jtextfield jcombobox itemlistener

当我点击jComboBox中的Item时,如何在jTextField中设置值? 就像我在jComboBox中选择Platinum一样,jTextField将显示其值为15%或Gold并将jTextField设置为10%

membox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {

    if(e.getStateChange() == ItemEvent.SELECTED) {

        jTextField6.setText((String) membox.getSelectedItem());
    }
}

});

我卡在这里它只显示我在jComboBox中点击的任何帮助将非常感谢提前谢谢

1 个答案:

答案 0 :(得分:1)

创建一个类

public class ItemClass {
private String name;
private String value;

public ItemClass(String name1, String value1) {
    name = name1;
    value = value1; 
}

@Override
public String toString()
{
    return name;
}

public String getValue() {
    return value;
}
}

并在您的代码中添加此代码...

    ItemClass oro = new ItemClass("gold","10%");
    ItemClass platino = new ItemClass("platinum","15%");
    JComboBox jc = new JComboBox();
    jc = membox;
    jc.addItem(oro);
    jc.addItem(platino);

membox.addItemListener(new ItemListener() {

@Override
public void itemStateChanged(ItemEvent e) {

    if(e.getStateChange() == ItemEvent.SELECTED) {
        Object obj=(Object) membox.getSelectedItem();
        ItemClass itemclass=(ItemClass)obj;
        String value = itemclass.getValue();
        jTextField6.setText(value);
    }
}

});