ItemTest.java Source code

Java tutorial

Introduction

Here is the source code for ItemTest.java

Source

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

import javax.swing.ButtonGroup;
import javax.swing.JComboBox;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JRadioButton;

public class ItemTest {
    public static void main(String args[]) {
        JFrame frame = new JFrame();
        Container contentPane = frame.getContentPane();

        ItemListener listener = new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                System.out.println("Source: " + name(e.getSource()));
                System.out.println("Item: " + name(e.getItem()));
                int state = e.getStateChange();
                System.out.println("State: " + ((state == ItemEvent.SELECTED) ? "Selected" : "Deselected"));
            }

            private String name(Object o) {
                if (o instanceof JComponent) {
                    JComponent comp = (JComponent) o;
                    return comp.getName();
                } else {
                    return o.toString();
                }
            }
        };

        JPanel panel = new JPanel(new GridLayout(0, 1));
        ButtonGroup group = new ButtonGroup();
        JRadioButton option = new JRadioButton("French Fries", true);
        option.setName(option.getText());
        option.addItemListener(listener);
        group.add(option);
        panel.add(option);
        option = new JRadioButton("Onion Rings", false);
        option.setName(option.getText());
        option.addItemListener(listener);
        group.add(option);
        panel.add(option);
        option = new JRadioButton("Ice Cream", false);
        option.setName(option.getText());
        option.addItemListener(listener);
        group.add(option);
        panel.add(option);
        contentPane.add(panel, BorderLayout.NORTH);

        String flavors[] = { "Item 1", "Item 2", "Item 3" };
        JComboBox jc = new JComboBox(flavors);
        jc.setName("Combo");
        jc.addItemListener(listener);
        jc.setMaximumRowCount(4);
        contentPane.add(jc, BorderLayout.SOUTH);

        frame.pack();
        frame.show();
    }
}