user3130731
user3130731

Reputation: 695

Java JList Not Updating

Why isn't my JList updating?

I re-instantiate the list object. I repaint and revalidate... What's going wrong?

needmoredetailsneedmore

External class:

                ControlPanel.usernames.add(username);
            ControlPanel.list = new JList(ControlPanel.usernames.toArray());
            ControlPanel.panel.repaint();
            ControlPanel.panel.revalidate();

ControlPanel.java

package main;

import java.awt.BorderLayout;
import java.util.ArrayList;

import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;

@SuppressWarnings("serial")
public class ControlPanel extends JFrame {

public static JPanel panel = new JPanel();
JScrollPane scrollpane;
static JLabel players;
static String s;
public static ArrayList<String> usernames = new ArrayList<String>();
public static JList list;

// public static String categories[] = {};

public ControlPanel() {
    list = new JList(usernames.toArray());
    scrollpane = new JScrollPane(list);

    panel.add(scrollpane, BorderLayout.CENTER);
    add(panel);

    setTitle("RuneShadows CP");
    setSize(400, 400);
    setResizable(false);
    setDefaultCloseOperation(EXIT_ON_CLOSE);
    setVisible(true);
}
}

Upvotes: 0

Views: 4072

Answers (1)

MadProgrammer
MadProgrammer

Reputation: 347334

You've created a new JList which has not been added to the screen

Instead, create a new ListModel and set it as the model for the list that's already on the screen

ControlPanel.usernames.add(username);
ControlPanel.list,setModel(new UserNamesListModel(ControlPanel.usernames));
ControlPanel.panel.repaint();
ControlPanel.panel.revalidate();

See How to use lists for more details

Your access model is, frankly, scaring. It allows complete access to everything form anywhere, so any nasty class might come along and completely dismantle your UI, for example.

The use if static is not a solution for easy access and greatly reduces the flexibility of your application over time.

You should be providing simply getters and setters to allow outside classes access to the information contained within and managed by the class.eapqually, you should provide the class's with management functionality that other class might need to use, such as refresh.

No one should care exactly how refresh works, only that it does...

Start by taking a look at How to use lists

import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractListModel;

public class UserNamesListModel extends AbstractListModel<String> {

    private List<String> userNames;

    public UserNamesListModel(List<String> userNames) {
        this.userNames = new ArrayList<>(userNames);
    }

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

    @Override
    public String getElementAt(int index) {
        return userNames.get(index);
    }

}

Upvotes: 4

Related Questions