user8508195
user8508195

Reputation:

JList using HashMap key (String) as its display?

I've been self studying Java for a couple months and have run into a challenge. I'm making a contact list application. I chose to use HashMap<String, Contact> as my storage for the contacts. The challenge I'm running into is the my unfamiliarity with Swing. I'm trying for the first time to use JList. I have got JList to work with a normal array of strings but now I want to use the Key value from the HashMap for the JList display.

I have read elsewhere that a custom ListModel will do, but I have failed to find anything concrete. The oracle document How to Use Lists uses the DefaultListModel in its examples. I have read using AbstractListModel or ListModel are steps in the right direction. There are three main classes so far:

Class Contact

public class Contact {

    private String name;
    private String phoneNumber;
    private String email;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPhoneNumber() {
        return phoneNumber;
    }

    public void setPhoneNumber(String phoneNumber) {
        this.phoneNumber = phoneNumber;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

Class Book

import java.util.HashMap;
import java.util.Map;

public class Book {

    private Map<String, Contact> addressbook = new HashMap<String, Contact>();

    public Map<String, Contact> getAddressbook() {
        return addressbook;
    }

    public void setAddressbook(Map<String, Contact> addressbook) {
        this.addressbook = addressbook;
    }

}

Class UserInterface This is where I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.

import java.awt.BorderLayout;

public class UserInterface extends JPanel implements ActionListener {

    private static final long serialVersionUID = 2161244209167568887L;

    // Contact list display
    JList contactList;

    // Menu bar and accompanying menu items
    private JMenuBar menuBar;
    private JMenu menu;
    private JMenuItem newContactMenuButton;
    private JMenuItem exitAppMenuButton;

    // Buttons
    private JButton newContactButton;
    private JButton openContactButton; 
    private JButton deleteContactButton; 

    // Panels to place components into
    private JPanel mainPanel;
    private JPanel buttonPanel; 

    // For message dialogs
    private JFrame messageDialog;

    public UserInterface() {

        // Add the JList
        contactList = new JList(new ContactListModel()); // ??

        // Creating the menu bar and its items
        // Adding ActionListeners to the menu buttons
        menuBar = new JMenuBar();
        menu = new JMenu("File");
        newContactMenuButton = new JMenuItem("New Contact");
        exitAppMenuButton= new JMenuItem("Exit");
        newContactMenuButton.addActionListener(this);
        exitAppMenuButton.addActionListener(this);
        menu.add(newContactMenuButton);
        menu.add(exitAppMenuButton);
        menuBar.add(menu);

        // Creating the Buttons
        // Adding ActionListeners to the buttons
        newContactButton = new JButton("New Contact");
        openContactButton = new JButton("Open Contact");
        deleteContactButton = new JButton("Delete Contact");
        newContactButton.addActionListener(this);
        openContactButton.addActionListener(this);
        deleteContactButton.addActionListener(this);

        // Creating the Panels with Grid Layouts
        mainPanel = new JPanel(new GridLayout());
        buttonPanel = new JPanel(new GridLayout(0, 1));

        // Adding components to the Panels
        mainPanel.add(contactList);
        buttonPanel.add(newContactButton);
        buttonPanel.add(openContactButton);
        buttonPanel.add(deleteContactButton);

        // Adding and aligning the Panels
        setBorder(BorderFactory.createEmptyBorder(45, 45, 45, 45));
        add(mainPanel, BorderLayout.CENTER);
        add(buttonPanel, BorderLayout.EAST);

    }

    public void CreateAndShowUI() {
        JFrame frame = new JFrame("Addressbook Application");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.add(new UserInterface());
        frame.setJMenuBar(this.menuBar);
        frame.pack();
        frame.setVisible(true);
    }


    @Override
    public void actionPerformed(ActionEvent e) {

        if(e.getSource() == newContactButton) {
            JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
        }

        if (e.getSource() == openContactButton) {
            JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
        }

        if (e.getSource() == deleteContactButton) {

            if(contactList.isSelectionEmpty()) {
                JOptionPane.showMessageDialog(messageDialog, "No contact selected.");

            } else if(!contactList.isSelectionEmpty()) {

                }
            }

        if (e.getSource() == newContactMenuButton) {
            JOptionPane.showMessageDialog(messageDialog, "yaaaay!");
        }

        if (e.getSource() == exitAppMenuButton) {
            System.exit(0);
        }
    }
}

final class ContactListModel extends AbstractListModel {

    Book book = new Book();
    Map<String, Contact> bookList = book.getAddressbook();

    public Object getElementAt(int keys) {
        keys = // ??
        return keys;
    }

    @Override
    public int getSize() {
        return bookList.size();
    }

}

Any genuine point in the right direction is highly appreciated. In the meantime I'll keep searching.

EDIT: Updated & Answered

Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.

private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;

Then inside the UserInterface constructor:

// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);

Upvotes: 2

Views: 2414

Answers (1)

camickr
camickr

Reputation: 324197

I'm having difficulty creating a custom list model that takes the String keys from my HashMap located in class Book.

You don't need to create a custom model. You can just add each Contact object to the DefaultListModel. The point of using models is that the model holds all the data and you use methods of the model to access the data.

Then the simplest way to get the JList to work is to implement the toString() method in your Contact object to return the property that you want to see in the JList.

EDIT: Updated & Answered

Here are the relevant updated code bits. As user carmickr suggested I used DefaultListModel to handle the data from the address book HashMap.

private DefaultListModel<Set<String>> model;
private JList<Set<String>> contactList;

Then inside the UserInterface constructor:

// Create the DefaultListModel object
// Add the JList
model = new DefaultListModel<Set<String>>();
model.addElement(book.AB.keySet());
contactList = new JList<Set<String>>(model);

Upvotes: 0

Related Questions