How to replace JPanel with another JPanel(如何用另一个 JPanel 替换 JPanel)
问题描述
我想用 JFrame 中的另一个 Jpanel 替换一个 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
推荐答案
不要使用
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 而不是 remove 然后在运行时添加一个新的 JPanel
use CardLayout instead of remove and then add a new JPanel on runtime
这篇关于如何用另一个 JPanel 替换 JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何用另一个 JPanel 替换 JPanel
基础教程推荐
- 在springboot中如何给mybatis加拦截器 2023-04-29
- 在java中使用xpath和selenium解析HTML表格数据 2022-01-01
- 如何在相机中应用自定义滤镜 [Surfaceview 预览]. 2022-01-01
- Maven:无效的目标版本:10 2022-01-01
- JPA惰性列表上的流 2022-01-01
- Java ECDSAwithSHA256 签名长度不一致 2022-01-01
- 将 double 转换为 Int,向下舍入 2022-01-01
- 将 Windows 证书导入 Java 2022-01-01
- doFilter()是在servlet的工作完成之前还是之后执行的? 2022-01-01
- 控制台应用程序中的 Java 键盘输入解析 2022-01-01
