Java AWT ItemListener handle item selection event on JComboBox

Description

Java AWT ItemListener handle item selection event on JComboBox


import java.awt.BorderLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

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

public class Main extends JFrame {
   public Main() {
      setSize(450, 350);//w  w  w.j  a  v  a 2s  .  co  m

      this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      JPanel comboPanel = new JPanel();
      String[] langs = { "CSS", "HTML", "Java" , "Javascript", "C", "C++"
            , "Ruby"};

      JComboBox<String> combo = new JComboBox<>(langs);
      combo.setMaximumRowCount(3);
      combo.addItemListener(new ItemListener() {
         public void itemStateChanged(ItemEvent e) {
            System.out.println("Combo: " + combo.getSelectedItem());
         }
      });
      combo.setSelectedIndex(1);
      comboPanel.add(combo);

      getContentPane().add(comboPanel, BorderLayout.SOUTH);
   }
   public static void main(String[] args) {
      Main that = new Main();
      that.setVisible(true);
   }
}



PreviousNext

Related