/* The program demonstrate the use of a list In addition we are able to select from the list * */ import javax.swing.*; import java.awt.event.*; public class SelectList extends JFrame { JPanel panel; JScrollPane scroll; JList list; JLabel msg; JButton ok; public SelectList() { // Sets the title of the window setTitle("JList Window"); // Sets the size of the window setSize(300, 400); // Sets the action when the window close setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Sets the label of the window msg = new JLabel("Here are the months"); // Creates a OK button ok = new JButton("OK"); // Create a String of array String[] months = {"Jan.", "Feb.", "March", "April", "May", "June", "July", "Aug.", "Sept.", "Oct.", "Nov.", "Dec."}; // Adds the array of string into the list list = new JList(months); // Sets the visibility of the list list.setVisibleRowCount(5); // Adds the list to a scroll pane JScrollPane scroll = new JScrollPane(list); // Adds the scroll pane, the label and OK button to a panel panel = new JPanel(); panel.add(msg); panel.add(scroll); panel.add(ok); // Adds the panel to a content pane add(panel); // Creates a single selection mode list.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); // Creates an event listener ok.addActionListener(new okButtonListener()); // Set the window to be visible setVisible(true); } public class okButtonListener implements ActionListener { public void actionPerformed(ActionEvent e) { if(e.getSource()==ok) { String select = (String)list.getSelectedValue(); JOptionPane.showMessageDialog(null, "You have selected " + select ); } } } public static void main(String[] args) { new SelectList(); } }