Java Program using JComboBox with ActionListener


In this program, You will learn how to implement JComboBox with ActionListener in java.


JComboBox cb;

public void actionPerformed(ActionEvent e) { 
      //statement
}

Example: How to implement JComboBox with ActionListener in java.

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

class Test implements ActionListener {

    JButton jb1;
    JComboBox cb;
    JLabel jt;
    JFrame f;

    Test() {

        String country[] = {"India", "Aus", "China", "England"};
        f = new JFrame("ComboBox Example");

        cb = new JComboBox(country);
        cb.setBounds(50, 30, 150, 30);
        f.add(cb);

        jt = new JLabel();
        jt.setBounds(220, 30, 180, 30);
        f.add(jt);

        jb1 = new JButton("Test it Now");
        jb1.setBounds(50, 200, 100, 30);
        f.add(jb1);

        jb1.addActionListener(this);

        f.setLayout(null);
        f.setSize(600, 400);
        f.setVisible(true);
    }

    public void actionPerformed(ActionEvent e) {
        jt.setText("Selected is :" + cb.getSelectedItem());
    }

    public static void main(String args[]) {
        Test t = new Test();
    }
}

Output:

JComboBox