Handle JComboBox item selection changed event - Java Swing

Java examples for Swing:JComboBox

Description

Handle JComboBox item selection changed event

Demo Code

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

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main extends JFrame implements ItemListener {
  String[] formats = { "(choose format)", "Atom", "RSS 0.92", "RSS 1.0",
      "RSS 2.0" };
  String[] descriptions = { "A","B","C","D" };
  JComboBox formatBox = new JComboBox();
  JLabel descriptionLabel = new JLabel("");

  public Main() {
    super("Syndication Format");
    setSize(420, 150);//from  w  w  w  .j a v  a 2  s .  com
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setLayout(new BorderLayout());
    for (int i = 0; i < formats.length; i++) {
      formatBox.addItem(formats[i]);
    }
    formatBox.addItemListener(this);
    add(BorderLayout.NORTH, formatBox);
    add(BorderLayout.CENTER, descriptionLabel);
    setVisible(true);
  }

  public void itemStateChanged(ItemEvent event) {
    int choice = formatBox.getSelectedIndex();
    if (choice > 0) {
      descriptionLabel.setText(descriptions[choice - 1]);
    }
  }
  public static void main(String[] arguments) {
    Main fc = new Main();
  }
}

Related Tutorials