Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
746 views
in Technique[技术] by (71.8m points)

java - Change contentpane of Frame after button clicked

I want to be able to set a JFrame's contentpane after a button inside one of that frame's JPanels has been clicked.

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)

ActionListener inside of the first JPanel:

public void actionPerformed(ActionEvent arg0) {
            controller.setpanel(new CustomPanel(string1, string2));
        }

Controller:

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 :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

Better though if you just want to swap JPanels is to use a CardLayout and have it do the dirty work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...