I am creating a game where each player fills a 3×3 grid and they all have a different state of the grid (a player object has an instance variable as the grid and the grid is made up of many JPanels).
I have a JList of players on the left and on the right the grid is displayed. Is there a way to dynamically change the grid when I click on a player’s name in the list?
(I tried doing a for loop to update the grid every time a player is selected but then if the player updates the grid after he is selected, it gets hacky to update the grid i.e you have to make the list get the focus etc. so I am looking for a clean way)
EDIT: Also, I thought about changing the reference of the object dynamically and update the UI however I have some action events which enforces me to make the variables FINAL. So I am unable to do this way either.
You should not change the grid when the selection changes. You should change the data displayed by the grid (i.e. the data model of the grid). For example, suppose the grid is a panel containing 9 labels, each displaying one element of a
String[][]. YourGridobject should have asetModel(String[][] data)which changes the value of each label in the grid.Each time the player selection changes, you should ask the selected player for its data, and call
setData()on the grid. If the data of a player can change while being delected, you should also call setData() each time it changes. This can be done by having aPropertyChangeEventtriggered by thePlayerwhen its data changes, and a listener which updates the grid with the new data if the player triggering the event is the selected player.