Search code examples
javaswingresizejframemaximize-window

Java Swing JFrame minimize/maximize resize bug


The problem is that when I try to maximize the JFrame the frame does get maximized, but the content size is preserved.

https://i.sstatic.net/QKSKF.png

My main frame class:

private CardLayout layout;

private SettingsFrame settingsFrame;

private Container contentPane;
Frame frame = this;

private ApplicationFrame() {       
    contentPane = getContentPane();
    layout = new CardLayout();
    contentPane.setLayout(layout);
    initializeFrame();
    settingsFrame = new SettingsFrame(model);
    initializeMenuBar();
    initializePanels();                
    showPage(FIRST_PAGE);
    this.addWindowStateListener(listener);
}

public SettingsFrame getSettingsFrame() {
    return settingsFrame;
}

private void initializeFrame() {
    this.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    this.setTitle(APPLICATION_TITLE);
    this.settingsFrame = new SettingsFrame(model);
    this.setSize(1400, 900);
    this.setLocationRelativeTo(null);
}    

private void initializePanels() {
    add(new Panel(), FIRST_PAGE);
    add(new Panel(), SECOND_PAGE);
    add(new Panel(), THIRD_PAGE);
}      

I tried to make a listener, catch the maximize event and there i tried:

revalidate();
repaint();

also

invalidate();
validate();

but with no succes.

I found out that:

frame.setExtendedState(JFrame.MAXIMIZED_BOTH);

is corectly maximizing the Frame, but i cannot use that is the listener because the maximize event already happened.


Solution

  • You're using a CardLayout which unfortunately won't allow you to resize the JComponent. Because the CardLayout can hold/manage one or more components that share the same display space.
    You should add a JPanel and set that panel's layout to the CardLayout if you wish to use it.

    I strongly recommend reading the following documentation: A Visual Guide to Layout Managers