简体   繁体   中英

How do I search through my JList?

I have a swing application am working on, my application lets the user enter a first name, last name, and phone number. the the user clicks the add button and it adds the entries into the jlist(so it like a phone book). I have a jTextfield above the JList in which I want to allow the user to search for a specific name or phone number on the Jlist, so its kind like a google search you type a character and it shows names with relevant characters in the JList and such. Am really stuck and lost at this point any help would be appricated??

This is my add button code to add names to my Jlist:

private void btnAddContactActionPerformed(java.awt.event.ActionEvent evt) {

    String firstName = txtFirstName.getText();
    String lastName = txtLastName.getText();
    String phoneNum = (txtPhoneNum.getText());
    NumberFormat number = NumberFormat.getNumberInstance();
    //Phone Number formatted
   StringBuilder sb = new StringBuilder(phoneNum).insert(0, "(")
           .insert(4,")").insert(8,"-");
   String phoneNumFormatted = sb.toString();

    contactsArrayList.add(firstName + "\t    " + lastName + "\t    " + phoneNumFormatted);
    DefaultListModel<String> model = new DefaultListModel<>();
    for(int i = 0; i < contactsArrayList.size(); i++)
    {
        String myArraylst = contactsArrayList.get(i);
        model.addElement(myArraylst + "\t");
    }

    listPhoneBookContacts.setModel(model);
    txtFirstName.setText("");
    txtLastName.setText("");
    txtPhoneNum.setText("");

}

It is possible to implement this kind of stuff in Swing, but it is gnarly and you are unlikely to do a good job of it (because it's hard). You're probably better off leaving it to some other library, like SwingX . They have a bunch of components you can use that might do exactly what you want.

If you don't want to use that, a quick Google search reveals a good tutorial for filtering JLists .

my application lets the user enter a first name, last name, and phone number

I would use a JTable to display all this information.

so its kind like a google search you type a character and it shows names with relevant characters

JTable has built in filtering. See Sorting and Filtering for a working example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM