Nicolas
Nicolas

Reputation: 11

Java Removing/Adding JPanel

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.

Upvotes: 0

Views: 103

Answers (1)

camickr
camickr

Reputation: 324197

} 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.

Upvotes: 2

Related Questions