import java.awt.BorderLayout; import java.awt.Container; import javax.swing.DefaultListModel; import javax.swing.JFrame; import javax.swing.JList; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.ListSelectionModel; import javax.swing.event.ListSelectionEvent; import javax.swing.event.ListSelectionListener; public class CSciClasses implements ListSelectionListener { private JList terms; private JTextField defn; public CSciClasses() { // The JList's model specifies the items appearing in the JList DefaultListModel model = new DefaultListModel(); model.addElement("CSci 150"); model.addElement("CSci 151"); model.addElement("CSci 230"); model.addElement("CSci 250"); model.addElement("CSci 280"); // Now we create the JList, specifying the model we are using terms = new JList(model); terms.setSelectionMode(ListSelectionModel.SINGLE_SELECTION); terms.addListSelectionListener(this); defn = new JTextField(30); defn.setEditable(false); } public void valueChanged(ListSelectionEvent e) { // As a ListSelectionListener, this method is invoked each time // the user selects something in the list. Object value = terms.getSelectedValue(); if(value != null) { // Removing from the model deletes what appears in the JList DefaultListModel model = (DefaultListModel) terms.getModel(); model.removeElement(value); String result = "???"; if(value.equals("CSci 150")) result = "Foundations I"; else if(value.equals("CSci 151")) result = "Foundations II"; else if(value.equals("CSci 230")) result = "Comp Sys Org"; else if(value.equals("CSci 250")) result = "Practicum"; else if(value.equals("CSci 280")) result = "Algorithms"; defn.setText(value + " - " + result); } } public static void main(String[] args) { JFrame main = new JFrame("CSci classes"); main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); CSciClasses manager = new CSciClasses(); Container contents = main.getContentPane(); contents.add(new JScrollPane(manager.terms), BorderLayout.CENTER); // (Note the use of a JScrollPane, so that scroll bars will // appear if the JList is too large for the window.) contents.add(manager.defn, BorderLayout.SOUTH); main.pack(); main.setVisible(true); } }