0

I am designing a GUI where an user can add a new ship to the system by just adding the name of the ship. The name of new ship will be stored in an ArrayList. Within my GUI design, I have implemented a JList which uses the ship ArrayList as data. The idea behind the implementation was when a new ship is added to the system, the JList would be updated with the name of the new ship in the JList as well. I know for sure that the ship name is being added to the ArrayList, because upon printing it as output, it displays, however, it does show on the JList.

I was maybe thinking, is there a refresh method I can make (if so how) or call which refreshes the frame, because I am assuming the problem is that it needs the frame to refresh in order for the JList to be updated?

BluesSolo
  • 608
  • 9
  • 28
Freddy
  • 683
  • 4
  • 35
  • 114
  • 2
    You need to either set a new model, or make the model fire the appropriate event. `AbstractListModel` has all those `fireXXX` methods. – Ordous Dec 09 '14 at 16:37
  • [This question](http://stackoverflow.com/questions/1851217/java-swing-updating-jlist) might help you out – Chris Sprague Dec 10 '14 at 15:20

1 Answers1

0

Here are a few snippets of code you might be looking for:

Assuming ArrayList already has some data to begin with:

DefaultListModel model = new DefaultListModel();
for(String ship: yourArrayList)
    model.addElement(ship);

list = new JList(model);

Then add a function to add ships to the ArrayList and JList:

public void addShip(String ship) {
    yourArrayList(ship);
    ((DefaultListModel) list.getModel()).addElement(ship);
}

Now when you want to add a ship instead of calling yourArrayList.add(...) you can call addShip(...).

707090
  • 102
  • 6