Section Emailsearcher: Jlist, Defaultlistmodel, and Interface Listselectionlistener

Section Emailsearcher: Jlist, Defaultlistmodel, and Interface Listselectionlistener

Section EmailSearcher: JList, DefaultListModel, and interface ListSelectionListener

Prerequisites: You attended class Tuesday, you got the general ideas and/or can ask your SL for help and/or work it out with your partner and/or use the linked code demos for the many details you'll need from the code demo examples at our code demos page that is at

Program Spec: You have probably seen text filters in several situations. This is how you can type part of an email address or a name and see the total email address and name. You are asked to completely implement a system that performs this type of behavior. Two tasks are required (but you get full credit for trying):

  1. Enter some text in a JTextField and have the JList show all email addresses that contain that substring.
  2. Click on an email address and see that full email address (actually just a string) in a dialog box.

1. First make your GUI look like this using method setUpModel() to save a lot of typing (copy and paste setUpModel—add allEmails and guiViewOfList as instance variables). Note: This is case insensitive.

private void setUpModel() {

// Need instance variable allEmails. With Java 7, use DefaultListModel<String>();

allEmails = new DefaultListModel();

allEmails.addElement("Peter Parker <>");

allEmails.addElement("Lester Mccann <>");

allEmails.addElement("Steve Rogers <>");

allEmails.addElement("Saumya Debray <>");

allEmails.addElement("Patrick Homer <>");

allEmails.addElement("Tony Stark <>");

allEmails.addElement("Beichuan Zhang <>");

allEmails.addElement("Rick Schlichting <>");

allEmails.addElement("Pete Downey <>");

allEmails.addElement("John Kececioglu <>");

allEmails.addElement("Natasha Romanoff <>");

allEmails.addElement("Clark Kent <>");

allEmails.addElement("Rick Snodgrass <>");

allEmails.addElement("Logan <>");

allEmails.addElement("Hal Jordan <>");

allEmails.addElement("Rick Mercer <>");

// Need instance variable guiViewOfList. With Java 7, use JList<String>();

guiViewOfList = new JList();

// Let the JList store all elements at first



2. When users click a list element, show the list element with JOptionPane.showMessageDialog(null, String)

Details: To respond to a change in the text field such as adding or removing one character, you will need to listen to the Document object that is part of the JTextField. Here are some details you'll need for this 2nd part:

Document doc = inputField.getDocument(); // Assumes inputField is of type JTextField

interface ListSelectionListener // implement removeUpdate and insertUpdate

doc.addDocumentListener(new DocListener());// Listen to a DocumentListener object

if (guiViewOfList.getValueIsAdjusting()) // Use in a ListSelectionListener to avoid code repeats