import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JComboBox; import javax.swing.JFrame; public class JComboBoxExample implements ActionListener { // Create a JFrame private JFrame frame = new JFrame(); // Create and set up a JComboBox String[] comboData = {"cat", "dog", "fish", "ant", "bee", "shark", "zebra", "elephant"}; private JComboBox combo = new JComboBox(comboData); public static void main(String[] args) { new JComboBoxExample(); } public JComboBoxExample() { // Allow objects to be placed anywhere on the JFrame frame.setLayout(null); // Don't let the JFrame be resized frame.setResizable(false); // Allow the JFrame to be closed via the "X" frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Set the size of the JFrame frame.setSize(200, 300); // Set the background color of the JFrame frame.getContentPane().setBackground(Color.BLACK); // Position the JFrame in the center of the screen frame.setLocationRelativeTo(null); // ============================================================ // Set the size of the JComboBox combo.setSize(90, 20); // Position the JComboBox on the JFrame combo.setLocation(55, 50); // Set the index of the JComboBox item that should be initially highlighted; to // start off with NO element highlighted, use the value of -1 combo.setSelectedIndex(0); // Assign an identifier to the JComboBox combo.setActionCommand("YeeCombo"); // Allow the JComboBox to respond to actions combo.addActionListener(this); // Add the JComboBox to the JFrame frame.add(combo); // Make the JFrame visible frame.setVisible(true); } public void actionPerformed(ActionEvent event) { if (event.getActionCommand().equals("YeeCombo")) { System.out.println(combo.getSelectedIndex()); System.out.println(combo.getSelectedItem()); } } }