单击按钮后更改Frame的内容窗格 [英] Change contentpane of Frame after button clicked

查看:85
本文介绍了单击按钮后更改Frame的内容窗格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够在单击该框架的某个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屋!

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