javajtextfieldjcomboboxitemlistener

How do i set the value in jTextField when i click an Item in jComboBox?


How do i set the value in jTextField when i click an Item in jComboBox? Like when i select Platinum in jComboBox the jTextField will display its value like 15% or Gold and set the jTextField to 10%

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

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

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

});

im stuck here it only displays what i clicked in the jComboBox any help will be so much appreciated thank you in advance


Solution

  • Create a class

    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;
    }
    }
    

    and add this code in yours...

        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);
        }
    }
    
    });