java - 如何实现这个功能呢?

标签 java swing

我有一个 JPanel 对象(例如 panel),它保存对 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();
    }
}

关于java - 如何实现这个功能呢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34084199/

相关文章:

java - 如何重置JFrame(重启游戏)?

java - 在 java 中编写 unicode (Sindhi) 的 keyListener 实现问题

java - 跨站点 tomcat 表单发布不起作用

java - 如何动态填充JTree?

java - 使用来自字符串的输入填充二维数组的行

java - Spring Boot jpa 与 javafx 服务集成 null

java - 单击按钮时 JFrame 未打开

java - JMapViewer 是线程安全的吗?

java - 我正在尝试编写一个程序,允许用户输入一系列考试分数作为整数

java - SQLite Android 根据今天是哪一天获取数据库信息