Java 如何实现这一功能?

Java 如何实现这一功能?,java,swing,Java,Swing,我有一个JPanel对象say面板,其中包含对JPanel对象的引用。 假设panel指向panel-1,在单击(操作)时,它应该指向panel-2,panel-2必须替换JFrame对象框架上的panel-1 但是,它不会更新。我尝试了以下方法,但没有成功: frame.repaint(); panel.revalidate(); 我想这段代码就是你想做的。它有一个JPanel,它持有一个绿色JPanel或一个红色JPanel和一个按钮来进行翻转 public class Test{

我有一个JPanel对象say面板,其中包含对JPanel对象的引用。 假设panel指向panel-1,在单击(操作)时,它应该指向panel-2,panel-2必须替换JFrame对象框架上的panel-1

但是,它不会更新。我尝试了以下方法,但没有成功:

frame.repaint();
panel.revalidate();

我想这段代码就是你想做的。它有一个JPanel,它持有一个绿色JPanel或一个红色JPanel和一个按钮来进行翻转

public class Test{
    boolean isGreen;  // flag that indicates the content

    public Test(){      
        JFrame f = new JFrame ("Test"); // the Frame
        f.setLayout (new BorderLayout());

        JPanel p = new JPanel(new BorderLayout()); // the content Panel 
        f.add(p, BorderLayout.CENTER);

        JPanel green = new JPanel(); // the green content
        green.setBackground(Color.GREEN); 

        JPanel red = new JPanel(); // the red content
        red.setBackground(Color.RED); 

        p.add(green); // init with green content
        isGreen = true;

        JButton b = new JButton ("flip"); // the flip button
        b.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                p.removeAll(); // remove all of old content                    
                if(isGreen){
                    p.add(red); // set new red content
                    isGreen = false;
                } else {
                    p.add(green); // set new green content
                    isGreen = true;
                }
                p.revalidate(); // invalidate content panel so component tree will be reconstructed
                f.repaint(); // repaint the frame so the content change will be seen
            }
        });
        f.add (b, BorderLayout.SOUTH);        
        f.pack();
        f.setSize(250,330);
        f.setVisible (true);
    }
    public static void main (String [] args){
       new Test();
    }
}

. 它还应该是
revalidate
repaint
,您只需在更改的面板上执行即可。您需要提供一个可运行的示例来演示您的问题。我猜,放置面板也会涉及到对父类的一些remove()或add()调用。您是否调用了
removeAll()
?不,不是这样的。正如@MadProgrammer指出的,您应该考虑使用
卡片布局
,而不是手动从框架中添加和删除面板。只是一些与答案不相关的东西。p、f、绿色和红色的声明需要在类中声明,如果您不想使它们成为最终的,非常感谢。这正是我想要的。你让我开心。再次感谢。