Skip to content
Advertisement

Making a JFrame with a JMenuBar open in fullscreen

I have a JFrame that I want to add a menu bar to and then have that JFrame automatically open in fullscreen. If I just make a JFrame and set it to fullscreen with f.setExtendedState(f.getExtendedState()|JFrame.MAXIMIZED_BOTH ); that works fine:

import javax.swing.*;

public class testframe {
    private static JFrame f;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(testframe::createAndShowGUI);
    }

    private static void createAndShowGUI() {
        f = new JFrame("Test");

        f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
        f.pack();
        f.setVisible(true);

    }
}

However, once I add a JMenuBar to that JFrame it will no longer open in fullscreen:

import javax.swing.*;

public class testframe {
    private static JFrame f;

    public static void main(String[] args) {
        SwingUtilities.invokeLater(testframe::createAndShowGUI);
    }

    private static void createAndShowGUI() {
        f = new JFrame("Test");

    JMenuBar menubar = new JMenuBar();
    JMenu j_menu = new JMenu("Test");
    JMenuItem j_menu_item = new JMenuItem("Test_item");
    j_menu.add(j_menu_item);
    menubar.add(j_menu);
    f.setJMenuBar(menubar);

    f.setExtendedState( f.getExtendedState()|JFrame.MAXIMIZED_BOTH );
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);;
    f.pack();
    f.setVisible(true);

    }
}

What could be the cause for this?

Update:

Switching to JDK11 solved the problem. I was on 15 before and also tried 14, both had the problem.

Advertisement

Answer

once I add a JMenuBar to that JFrame it will no longer open in fullscreen:

Appears in full screen for me. I use JDK11 in Windows 10.

However, the menu doesn’t work because you have a coding problem. You need to add the JMenu to the JMenubar.

//menubar.add(j_menu_item);
menubar.add(j_menu);

Also, I’ve always just used:

 f.setExtendedState( JFrame.MAXIMIZED_BOTH );
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement