user11703461
user11703461

Reputation:

Display a ArrayList with in a JList (Swing)

I'm having an issue when I try to display a JList with an ArrayList. I'm using Action Listeners to execute all this:

ContactArray contactObject = new ContactArray();
addContactBtn.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String firstName = firstNameField.getText();
        String lastName = lastNameField.getText();
        contactObject.addName(firstName + " " + lastName);
        // contactObject.getNames().forEach(System.out::println);
    }
});
viewContactButton.addActionListener(new ActionListener() {
    @Override
    public void actionPerformed(ActionEvent e) {
        String[] contacts = contactObject.getNames().toArray(new String[0]);
        contactList = new JList(contacts);
        contactList.setVisibleRowCount(5);
        contactList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        add(new JScrollPane(contactList));
    }
});

ContactArray class:

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class ContactArray {

    private List<String> names;

    public ContactArray() {
        this.names = new ArrayList<>();
    }

    //add a name to list
    public void addName(String name) {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        this.names.add(name);
    }

    //get the name attribute
    public List<String> getNames() {
        if (!Objects.nonNull(names)) {
            this.names = new ArrayList<>();
        }
        return this.names;
    }

}

I have managed to print the full names to the console with contactObject.getNames().forEach(System.out::println);which I put in comments, but can't seem to add them to JList. Normally, when I press on viewContactButton, it should display it.

Also, I'm using the Swing GUI form from IntelliJ IDEA.

Thanks for any help :)

Upvotes: 1

Views: 131

Answers (1)

camickr
camickr

Reputation: 324207

I have managed to print the full names to the console

Well, you placed that code in the wrong place. The code should be placed when you actually use the List to create the JList. (ie. Maybe you have code somewhere that accidentally deletes the List sometime after it is created and before it is used)

I'm having an issue when I try to display a JList with an ArrayList

Well is the problem the ArrayList or did you also try to hardcode data in the JList? In order to solve a problem you need to know what the real problem is. Always first try to display hard coded data instead of dynamic data.

add(new JScrollPane(contactList));

I would guess the real problem is the above statement.

Whenever you add components to a visible frame the basic code should be:

add(...);
revalidate();
repaint();

You need to invoke the layout manager of the panel. Otherwise the component has a size of 0, so there is nothing to paint.

Upvotes: 1

Related Questions