import javax.swing.*; import java.awt.*; import java.awt.event.*; /* ListDemo illustrates the use of JLabels, JTextFields, * JScrollPanes and JLists. * * Written by: Stuart Hansen * September 8, 2008 */ public class ListDemo extends JFrame { // These elements form the GUI of the application private JLabel enterLabel; private JTextField enterField; private JScrollPane listPane; private JList list; // The constructor public ListDemo () { super ("List Demo"); enterLabel = new JLabel(); enterField = new JTextField(); // The DefaultListModel on the next line gives us the // ability to add to the list list = new JList(new DefaultListModel()); // The list is added to a JScrollPane, so that we may // view lists larger than the display listPane = new JScrollPane(list); // setup the contentPane to use absolute coordinates Container contentPane = getContentPane(); contentPane.setLayout(null); // initialize and add the components to the GUI enterLabel.setText("Enter some text"); enterLabel.setSize(100, 30); enterLabel.setLocation(20, 20); contentPane.add(enterLabel); enterField.setSize(100, 20); enterField.setLocation(120 ,25); contentPane.add(enterField); enterField.addActionListener(new InputListener()); listPane.setSize(100, 200); listPane.setLocation(20, 60); contentPane.add(listPane); // Set the windows size and close operation setSize(300, 300); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // display the application window setVisible(true); } // The ActionListener for the JTextField // The event if fired when enter is pressed // The text is added to the list private class InputListener implements ActionListener { public void actionPerformed(ActionEvent e) { String text = enterField.getText(); DefaultListModel model = ((DefaultListModel)(list.getModel())); if (!text.equals("")) { model.addElement(text) ; enterField.setText(""); } } } // a very simple main program public static void main (String args[]) { new ListDemo(); } }