/* The program demonstrate the use of a list In addition we are able to select more than one from the list * */ import javax.swing.*; import java.awt.event.*; public class SelectLists extends JFrame { JPanel panel; JScrollPane scroll; JList list; JLabel msg; JButton ok; public SelectLists() { // 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.MULTIPLE_INTERVAL_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) { Object[] select = list.getSelectedValues(); String msg = "You have selected the following months: \n"; // Using a loop to store the selection in the select array for(Object selection : select ) { msg += (String)selection + "\n"; } JOptionPane.showMessageDialog(null, msg); // Clears all the selection list.clearSelection(); } } } public static void main(String[] args) { new SelectLists(); } }