-1

I am making a GUI that adds a name to a list and then i have a JList on the home frame and 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);
            }

        }

    });

Thanks for any help in advance

Strahinja
  • 422
  • 8
  • 23
Bravecity
  • 21
  • 1
  • 6
  • 1) See [The Use of Multiple JFrames, Good/Bad Practice?](http://stackoverflow.com/q/9554636/418556) 2) For better help sooner, post a [MCVE] or [Short, Self Contained, Correct Example](http://www.sscce.org/). – Andrew Thompson Sep 15 '17 at 00:29

1 Answers1

1

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.

Strahinja
  • 422
  • 8
  • 23
  • 1
    @Bravecity `And when you want to update it, you can just use reload(), validate() or refresh().` - No, there is no need for any of those methods. All you need to do is update the ListModel and the model will tell the JList to repaint itself. Changes should always be made to a model, not an external data source (ie your ArrayList). – camickr Sep 14 '17 at 14:48