简体   繁体   中英

How do I refresh a JList?

I am making a GUI that adds a name to a list and then I have a JList on the home frame. When I hit the button on the other frame, I want it to update the JList to display the recently added string to the arraylist

ArrayList:

private static ArrayList<String> name = new ArrayList<String>();

JList:

JList lisName = new JList(name.toArray());

JButton I want to update the list:

JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {

    @Override
    public void actionPerformed(ActionEvent e) {
        if(txtName.getText() == null) {
            JOptionPane.showMessageDialog(pnlName, "Error: Please enter name!");
        }else{
            name.add(txtName.getText());
            nameFrame.setVisible(false);
        }
        
    }
    
});

I would suggest you using a ListModel/TreeModel to handle JList, JTree etc.

There you can make something like this:

DefaultListModel listModel = new DefaultListModel(name);
JList jList = new JList(listModel); //or setListModel(listModel)

And when you want to update it, you can just use reload() , validate() or refresh() . So you can refresh the model of the list and everything's gonna be ok. Or you could just create new listModel and set the new values that you would like to show.

Since the question is similar to some others on Stackoverflow, you could check on this links and that should help you:

Also check related questions to yours. I hope I was helpful.

I have been scouring dozens of answers on SO trying to solve this for the past two days. Others here have suggested to call yourJList.ensureIndexIsVisible(yourModel.getSize()); , however this didn't work for me.

What worked for me was calling yourJList.requestFocus(); after addElement(String); . Hopefully, this helps some folks, as I was pretty frustrated over this one.

Edit: Changed naming convention.

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