anon
anon

Reputation:

How to get a JPanel to show over the others in the same area

So I am writing a little app that needs to have one JPanel be added to the same area as another and have one show up when it's needed - AKA when a button is pressed, one disappears and the other shows up. As soon as I have time, I will clean up the post, but for now I kinda need to rush so I don't miss the bus home.

Also, if this is not possible, please tell me a way I can replicate the effect. Preferably within the same window.

SSCCE ex. imports:

public class Demo implements ActionListener {
    static JButton switch = new JButton("Switch");

    public static void main(String[] args) {
        JFrame disp = new JFrame("Demo");
        disp.setLayout(new BorderLayout());
        disp.add(switch, BorderLayout.NORTH);
        JPanel pan1 = new JPanel();
        pan1.setBackground(Color.RED);
        disp.add(pan1);
        JPanel pan2 = new JPanel();
        pan2.setBackground(Color.GREEN);
        disp.add(pan2);
        disp.setVisible(true);
    }

    void actionPerformed(ActionEvent e) {
        System.out.println(e.paramString());
        //Something to switch the JPanels when "switch" is pressed
    }
}

Upvotes: 1

Views: 155

Answers (2)

matt forsythe
matt forsythe

Reputation: 3912

If I understand your question correctly, I think what you want is to use one JPanel with a CardLayout. This in turn could hold the other two colored JPanels. You can then toggle between the two. The JPanel with the CardLayout could then be added to your BorderLayout.CENTER.

The other option is to manage this yourself. Keep references to both pan1 and pan2 as member variables. Then inside of action performed, you can simply remove pan1 and add pan2.

Upvotes: 4

Adrián
Adrián

Reputation: 6255

This might be what you are looking for JFrame.setContentPane()

I think the method signature is pretty much self-explanatory.

Upvotes: 0

Related Questions