单击按钮后更改Frame的内容窗格 [英] Change contentpane of Frame after button clicked
问题描述
我希望能够在单击该框架的某个JPanels中的按钮后设置JFrame的contentpane。
I want to be able to set a JFrame's contentpane after a button inside one of that frame's JPanels has been clicked.
我的架构由一个控制器组成,该控制器创建了JFrame和它里面的第一个JPanel。从第一个JPanel中我调用一个方法:setcontentpane(JPanel jpanel)在控制器上。但是,不是加载传递的JPanel,它只会移除所有面板(请参阅下面的代码)
My architecture consists of a controller which creates the JFrame and the first JPanel inside of it. From within the first JPanel I'm calling a method: setcontentpane(JPanel jpanel) on the controller. However, instead of loading the passed JPanel it does nothing but removing all Panels (see code below)
第一个JPanel内的ActionListener:
ActionListener inside of the first JPanel:
public void actionPerformed(ActionEvent arg0) {
controller.setpanel(new CustomPanel(string1, string2));
}
控制器:
JFrame frame;
public void setpanel(JPanel panel)
{
frame.getContentPane().removeAll();
frame.getContentPane().add(panel);
frame.repaint();
}
public Controller(JFrame frame)
{
this.frame=frame;
}
谁能告诉我我做错了什么?谢谢:)
Can anyone tell me what I'm doing wrong? Thanks :)
推荐答案
调用revalidate,然后重新绘制。这告诉布局管理器要对其组件进行布局:
Call revalidate, then repaint. This tells the layout managers to do their layouts of their components:
JPanel contentPane = (JPanel) frame.getContentPane();
contentPane.removeAll();
contentPane.add(panel);
contentPane.revalidate();
contentPane.repaint();
更好但是如果你只想交换JPanels就是使用CardLayout并让它做脏工作。
Better though if you just want to swap JPanels is to use a CardLayout and have it do the dirty work.
这篇关于单击按钮后更改Frame的内容窗格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!