gpt4 book ai didi

java - 如何用另一个 JPanel 替换 JPanel

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:59:24 24 4
gpt4 key购买 nike

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

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);
}
}

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

最佳答案

  1. 不要使用AbsoluteLayout

  2. actionPerformed 中的 validate(); 更改为 contain.validate(); 并跟随 contain.repaint ();

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

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

关于java - 如何用另一个 JPanel 替换 JPanel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14874613/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com