Assign a function to JComboBox

4

I have the following doubt, I have a combobox, and I want it when clicking on one of the combo options, it does something. I would like to know how I put a variable or method "bound" to combo options, for example if I clicked on option 1, it lists me something, if it is in 2, it only issued a JOption pane (just an example).

package teste;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class Exemplo extends JFrame
{
    private String t;
    public Exemplo()
    {
        setTitle("Exemplo combo");
        setSize(500, 500);     
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);          


        JPanel jp = new JPanel();
        jp.setLayout(null);
        add(jp);        
        JComboBox combo = new JComboBox();
        combo.addItem("Opção 1");        
        combo.addItem("Opção 2");
        jp.add(combo);
        combo.setBounds(180, 200, 125, 30);       
    }

    public static void main(String[] args) 
    {
        Exemplo ex = new Exemplo();
        ex.setVisible(true);
    }   

}
    
asked by anonymous 10.03.2017 / 18:17

1 answer

1

You must create and bind% change% of Listener :

class ItemChangeListener implements ItemListener{
    @Override
    public void itemStateChanged(ItemEvent event) {
       if (event.getStateChange() == ItemEvent.SELECTED) {
          String value = event.getItem().toString();
          // faz algo conforme a opção selecionada
          if (value.equals("Opção 1")) {
             // faz algo se selecionou a opção 1
          }
       }
    }       
}

To add JComboBox to Listener , do:

addItemListener(new ItemChangeListener());
    
10.03.2017 / 18:33