Assign a function to JComboBox

Posted on

Question :

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

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

    public static void main(String[] args) 
        Exemplo ex = new Exemplo();



Answer :

You must create and bind% change% of Listener :

class ItemChangeListener implements ItemListener{
    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());


Leave a Reply

Your email address will not be published. Required fields are marked *