/* This is a simple JCombo Box GUI * */ import javax.swing.*; import java.awt.event.*; public class JCombo_Box extends JFrame { // Sets to private so only the same class can access these members private JComboBox jcombo; private JPanel panel; private JButton ok; public JCombo_Box() { // Sets the title of the window setTitle("JCombo Box Window"); // Sets the size of the window setSize(300, 200); // Sets the appearance location of the window to the middle of the screen setLocationRelativeTo(null); // Sets the action when a window is close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Creates a JComob Box jcombo = new JComboBox(); // Adds the item to the JCombo Box jcombo.addItem("Jan."); jcombo.addItem("Feb."); jcombo.addItem("March"); jcombo.addItem("April"); jcombo.addItem("May"); jcombo.addItem("June"); jcombo.addItem("July"); jcombo.addItem("Aug."); jcombo.addItem("Sept."); jcombo.addItem("Oct."); jcombo.addItem("Nov."); jcombo.addItem("Dec."); // Create a panel panel = new JPanel(); // Creates a OK button ok = new JButton("OK"); // Creates a event listener to handle the event ok.addActionListener(new okButtonListener()); // Adds the JCombo Box and ok button to the panel panel.add(jcombo); panel.add(ok); // Adds the window to the content pane add(panel); // Sets the window to be true setVisible(true); } /* JCombo Box returns an object, so when we get the selection We must specify what is the type of the object In this case the type is a String * */ private class okButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==ok) { String select = (String)jcombo.getSelectedItem(); JOptionPane.showMessageDialog(null, "You have selected " + select); } } } public static void main(String[] args) { new JCombo_Box(); } }