SelectingComboSample.java Source code

Java tutorial

Introduction

Here is the source code for SelectingComboSample.java

Source

import java.awt.BorderLayout;
import java.awt.Container;
import java.awt.ItemSelectable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.PrintWriter;
import java.io.StringWriter;

import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;

public class SelectingComboSample {
    static private String selectedString(ItemSelectable is) {
        Object selected[] = is.getSelectedObjects();
        return ((selected.length == 0) ? "null" : (String) selected[0]);
    }

    public static void main(String args[]) {
        String labels[] = { "A", "B", "C", "D", "E", "F", "G", "H", "J", "I" };
        JFrame frame = new JFrame("Selecting JComboBox");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        Container contentPane = frame.getContentPane();

        JComboBox comboBox = new JComboBox(labels);
        contentPane.add(comboBox, BorderLayout.SOUTH);

        final JTextArea textArea = new JTextArea();
        textArea.setEditable(false);
        JScrollPane sp = new JScrollPane(textArea);
        contentPane.add(sp, BorderLayout.CENTER);

        ItemListener itemListener = new ItemListener() {
            public void itemStateChanged(ItemEvent itemEvent) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                int state = itemEvent.getStateChange();
                String stateString = ((state == ItemEvent.SELECTED) ? "Selected" : "Deselected");
                pw.print("Item: " + itemEvent.getItem());
                pw.print(", State: " + stateString);
                ItemSelectable is = itemEvent.getItemSelectable();
                pw.print(", Selected: " + selectedString(is));
                pw.println();
                textArea.append(sw.toString());
            }
        };
        comboBox.addItemListener(itemListener);

        ActionListener actionListener = new ActionListener() {
            public void actionPerformed(ActionEvent actionEvent) {
                StringWriter sw = new StringWriter();
                PrintWriter pw = new PrintWriter(sw);
                pw.print("Command: " + actionEvent.getActionCommand());
                ItemSelectable is = (ItemSelectable) actionEvent.getSource();
                pw.print(", Selected: " + selectedString(is));
                pw.println();
                textArea.append(sw.toString());
            }
        };
        comboBox.addActionListener(actionListener);

        frame.setSize(400, 200);
        frame.setVisible(true);
    }
}