Anika
Anika

Reputation: 103

I need help conceptualizing my GUI implementation

I am trying to make a game where I can have an n number of players.

problem is how can I make a JFrame for each player if I don't know the number?

Originally I planned on making multiple frames, panels and JButton components and their action listener for say 5 players, then limit the users to only have 5 players to play with. But still, that would mean making 5 options buttons for 5 players so 25 buttons and 5 frames and that seems really ridiculous.

I was wondering if there was a way to make this easy? I am really new to java and especially the GUI part. I want to use Swing, not JavaFX.

This is how I want to implement my players:

ArrayList<Players> players = new ArrayList();
gamePanel(players);

Normally I would do

JFrame f = new JFrame(playerName);

but how can I make multiple frames with a number of player objects? Or maybe just one frame that switches back and forth between the player objects based on what buttons they have pressed? Based on some win condition I also want to remove the frames associated with the players, and then get more user input via button clicks, until there is only one user in the ArrayList. I am not sure how to go about all of this, help would be greatly appreciated!

Upvotes: 0

Views: 102

Answers (1)

MDK
MDK

Reputation: 499

The most simple way would be to store your JFrame objects in a HashMap. This way you can add a new JFrame associated with a player:

HashMap<Player, JFrame> frames = new HashMap<>();
for (Player player : players) {
    JFrame frame = new JFrame(player.getName());
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    // additional setup, creating buttons for the frame, ...
    frames.put(player, frame);
}

after that you can easily access each frame by calling frames.get(player);, for example frames.get(players.get(0)).dispose(); to shut down the frame associated with the first player and afterwards frames.remove(players.get(0)) to delete the mapping.

You can also easily iterate over all frames, for example

for (JFrame frame : frames.values()) {
    frame.setVisible(true);
}

For further reading about structuring GUIs I recommend to have a look at the Model-View-Controller pattern. That pattern is very useful to organize how the model (in your case the players) interact with the view (in your case the JFrames).

Upvotes: 2

Related Questions