Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...