Ard*_*han 6 java layout swing jpanel jframe
我想在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);
}
}
Run Code Online (Sandbox Code Playgroud)
有人能帮我吗 ?非常感谢
不要使用 AbsoluteLayout
改变validate();在actionPerformed对contain.validate();与如下contain.repaint();
将类名(保留的Java字或方法名)Frame(java.awt.Frame)重命名为MyFrame(例如)
使用CardLayout而不是删除然后JPanel在运行时添加新的
执行删除和添加操作后,您必须在包含面板上调用validate()和 then 。repaint()
contain.validate();
contain.repaint();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18043 次 |
| 最近记录: |