1

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

2 に答える 2

4

あなたの質問を正しく理解できれば、あなたが望むのは CardLayout で 1 つの JPanel を使用することだと思います。これにより、他の 2 つの色付き JPanel を保持できます。その後、2 つを切り替えることができます。次に、CardLayout を含む JPanel を BorderLayout.CENTER に追加できます。

もう 1 つのオプションは、これを自分で管理することです。pan1 と pan2 の両方への参照をメンバー変数として保持します。次に、実行されるアクション内で、pan1 を削除して pan2 を追加するだけです。

于 2013-01-15T20:57:43.303 に答える
0

これはあなたが探しているものかもしれませんJFrame.setContentPane()

メソッドのシグネチャはほとんど一目瞭然だと思います。

于 2013-01-15T20:59:24.100 に答える