Change contentpane of Frame after button clicked

后端 未结 3 1698
不思量自难忘°
不思量自难忘° 2020-12-19 06:41

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

相关标签:
3条回答
  • 2020-12-19 07:18

    Whenever you change a frame's containment hierarchy, you have to call pack().

    From the docs:

    Causes this Window to be sized to fit the preferred size and layouts of its subcomponents. [...] The Window will be validated after the preferredSize is calculated.

    0 讨论(0)
  • 2020-12-19 07:27

    I found a way to do what I outlined above.

    Implementing the setpanel method like this:

    public void setpanel(JPanel panel)
    {
        frame.setContentPane(panel);
        frame.validate();
    }
    

    did the trick in my case.

    I'm sure that I still need to fix something within my code, since pack() still shrinks the window, but at least the method posted above works.

    0 讨论(0)
  • 2020-12-19 07:34

    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.

    0 讨论(0)
提交回复
热议问题