0

Currently I have a client that contains two panels... one is the main game and the other is a side panel containing tools. The side panel can be shown/hid (thus making the frame only show the game).

            activateSidePanel.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                if (sp) {
                    frame.remove(enhancedPanel);
                    frame.repaint();
                    frame.pack();
                    sp = false;
                } else if (!sp) {
                    frame.add(enhancedPanel);
                    frame.repaint();
                    frame.pack();
                    sp = true;
                }
            }
        });

That is my action listener for the button. The button hides correctly, however it doesn't show. When I click the button again it just makes the frame smaller and does not bring back the side panel. Confused on this one.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Nicolas
  • 11
  • 2
  • 8
  • 2
    For many components in one space, use a [`CardLayout`](http://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html) as seen in this [short example](http://stackoverflow.com/a/5786005/418556). – Andrew Thompson Nov 16 '13 at 21:23
  • Rather than calling `add(...)` and `remove(...)`, I'd change the enhancedPanel's visibility via `setVisible(...)`, and then call `revalidate()` and `repaint()` on its container. Consider creating and posting an [sscce](http://sscce.org) for better and more specific help. – Hovercraft Full Of Eels Nov 16 '13 at 21:26

1 Answers1

2
} else if (!sp) {

Why do test for !sp? A boolean can only have two values, so all you need is an if/else statement (without the test on the else.

Instead of removing/adding the panel I would try invoking the setVisible(false/true) method first.

If that doesn't work then then general code for removing/adding components is:

panel.add(...)
panel.revalidate(); 
panel.repaint();

You should not need to invoke pack() because you don't want the frame to keep resizing, you only want the main panel to become bigger/smaller.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • I actually do want the frame to resize. Your code works perfectly though. Thank you :) – Nicolas Nov 16 '13 at 21:34
  • @Nicolas, please don't forget to "accept" the answer by clicking on the large check-mark next to the answer, if you think the answer satisfied your question. This is how we responds to each other in this site: upvoting, downvoting and accepting ;) – Sage Nov 16 '13 at 21:55