Reputation: 369
Yes, this probably looks like a duplicate question, but bear with me. Take the code below, that is functional:
private void setMainLayout(Container pane) {
String imagePath = Start.getProperty("IMAGE_DIR");
characters.add(char1); // pseudocode
characters.add(char2);
characters.add(char3);
characters.add(char4);
// "CharacterDisplay.getMainLayout()" returns a Box object:
for (CharacterDisplay character : characters)
character.getMainLayout().setBorder(BorderFactory.createMatteBorder(2, 2, 2, 2, Color.WHITE));
// "mainFrame" is a JFrame:
mainFrame.setLayout(new GridBagLayout());
GridBagConstraints gbc = new GridBagConstraints();
/* do random gridbagconstraints stuff */
pane.add(characters.get(0).getMainLayout(), gbc);
/* do random gridbagconstraints stuff */
// "nonCharacterArea" is a JPanel:
nonCharacterArea.setOpaque(true);
nonCharacterArea.setBackground(Color.BLACK);
nonCharacterArea.setLayout(new GridBagLayout());
GridBagConstraints constCenter = new GridBagConstraints();
/* do random gridbagconstraints stuff */
nonCharacterArea.add(actionPane, constCenter); // actionPane is a kind of JPanel
/* do random gridbagconstraints stuff */
nonCharacterArea.add(menuPane, constCenter); // menuPane is a kind of JPanel
pane.add(nonCharacterArea, gbc);
/* do random gridbagconstraints stuff */
pane.add(characters.get(1).getMainLayout(), gbc);
gbc.gridx = 0;
gbc.gridy = 2;
pane.add(characters.get(2).getMainLayout(), gbc);
gbc.gridx = 2;
gbc.gridy = 2;
pane.add(characters.get(3).getMainLayout(), gbc);
} // setMainLayout
I want to be able to change the actionPane
object dynamically during execution. What is the best way to accomplish this? I wrote this pseudo-code block specifically to show that it's not just as simple as the other examples people have posted in similar questions -- because it is based on a precise placement of the JPanel at a certain spot on the screen, and this setMainLayout() method should not have to be called each time I want to change only the actionPane object.
Sometimes it will be a side-scrolling screen, sometimes it will be a shop interface, it can be many different kinds of things.
Ideas? Thanks.
Upvotes: 0
Views: 134
Reputation: 15729
If the actionPane
is taken from a small set of Panels that are pretty much predefined, with relatively minor live updates and changes, a good option is to use a CardLayout, and switch between the predefined actionPanes as needed.
If the actionPane is very dynamic and you really cannot predict ahead of time what it might be, then @Greg Kopff has a reasonable answer.
Upvotes: 4
Reputation: 16545
Don't add and remove the actionPane
- leave that in place, but add/remove a child component to actionPane
. This task then becomes relatively trivial because actionPane
contains only a single component.
Upvotes: 3