Get selected value of JComboBox populated with Enum

1

I have in my window a JComboBox with items from an enum, and a JLabel to show the value of the selected item in the combo.

So far so good, I can do this, but I'm a little unsure if I'm doing it right, because I do not know if there is a more efficient way to do it.

JComboBox event:

form.cmbPizza.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                if(form.cmbPizza.getSelectedItem() != null){
                    if(Pizzas.CALABRESA == (Pizzas) form.cmbPizza.getSelectedItem()){
                        form.lblPrecoPizza.setText("R$ " + Pizzas.CALABRESA.preco);
                    }
                }else{
                    form.lblPrecoPizza.setText("R$ 0,00");
                }
            }
        });

Enum:

        public enum Pizzas {

            CALABRESA("25,99"), MUSSARELA("25,99"), PALMITO("19,99"), PORTUGUESA("19,99"),
 CATUPIRY("25,99"), PROVOLONE("19,99"), LOMBO("29,99");

            public String preco;

            private Pizzas(String s) {
                preco = s; 
            }

        }

The issue is that I have several items in the enum, so my question arises, will I have to do what I just did with all the items or is there a less complicated and more efficient way of doing this?

    
asked by anonymous 02.04.2016 / 16:39

1 answer

2

First add in your Enum a method that returns the price option:

public enum Pizzas {

    CALABRESA("25,99"), MUSSARELA("25,99"), PALMITO("19,99"), PORTUGUESA("19,99"),
    CATUPIRY("25,99"), PROVOLONE("19,99"), LOMBO("29,99");

    public String preco;

    private Pizzas(String s) {
        preco = s;
    }
    public String getValue(){
        return preco;
    }
}

As I already replied in the other question , just adapt the code from there to your Enum . And to monitor selection changes from JComboBox , you must use ItemStateChanged :

form.cmbPizza.addItemListener(new ItemListener() {

            @Override
            public void itemStateChanged(ItemEvent e) {

             if (e.getStateChange() == ItemEvent.SELECTED) {
                Pizzas p = (Pizzas) e.getItem();
                 jLabel1.setText("R$" + p.getValue());
            }
        });

See working:

    
02.04.2016 / 17:20