如何用另一个JPanel替换JPanel [英] How to replace JPanel with another JPanel

查看:324
本文介绍了如何用另一个JPanel替换JPanel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个JFrame中的另一个替换一个Jpanel 我已经搜索并尝试了我的代码,但没有任何反应 这是我的代码:

I want to replace a Jpanel with another one in a JFrame I already search and try my code but nothing's happen this is my code :

public class Frame extends JFrame {

    private Container contain;
    private JPanel reChange,reChange2;
    private JButton reChangeButton;

    public Frame() {
        super("Change a panel");
        setSize(350, 350);
        setLayout(null);
        setLocationRelativeTo(null);
        setResizable(false);

        reChange = new JPanel(null);
        reChange.setBackground(Color.red);
        reChange.setSize(240, 225);
        reChange.setBounds(50, 50, 240, 225);
        add(reChange);

        reChangeButton = new JButton("Change It");
        reChangeButton.setBounds(20, 20, 100, 20);
        add(reChangeButton);

        reChangeButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //System.out.println("in");
                contain = getContentPane();
                contain.removeAll();
                //System.out.println("in2");

                reChange2 = new JPanel(null);
                reChange2.setBackground(Color.white);
                reChange2.setSize(240, 225);
                reChange2.setBounds(50, 50, 240, 225);
                //System.out.println("in3");

                contain.add(reChange2);
                validate();
                //System.out.println("in4");
                setVisible(true);
                //System.out.println("in5");
            }
        });

    }

    public static void main(String[] args) {
        Frame frame = new Frame();
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

有人可以帮助我吗?非常感谢

can someone help me ? Thanks a lot

推荐答案

  1. 不要使用AbsoluteLayout

actionPerformed中的validate();更改为contain.validate();,然后跟随contain.repaint();

change validate(); in actionPerformed to contain.validate(); and follows with contain.repaint();

将类名(保留的Java单词或方法名)重命名为Frame(java.awt.Frame)至MyFrame(例如)

rename class name (reserved Java word, or methods name) Frame (java.awt.Frame) to MyFrame (for example)

使用CardLayout而不是删除,然后在运行时添加新的JPanel

use CardLayout instead of remove and then add a new JPanel on runtime

这篇关于如何用另一个JPanel替换JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆