全屏打开带有 JMenuBar 的 JFrame

Making a JFrame with a JMenuBar open in fullscreen

我有一个 JFrame,我想在其中添加一个菜单栏,然后​​让该 JFrame 自动全屏打开。如果我只是制作一个 JFrame 并将其设置为全屏 f.setExtendedState(f.getExtendedState()|JFrame.MAXIMIZED_BOTH ); 效果很好:

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

    }
}

但是,一旦我将 JMenuBar 添加到该 JFrame,它将不再全屏打开:

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

    }
}

这可能是什么原因造成的?

更新:

切换到 JDK11 解决了问题。我之前是15,也试过14,都出现问题

您需要以正确的顺序调用 JFrame 方法。

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

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.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        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.pack();
        f.setExtendedState(f.getExtendedState() | JFrame.MAXIMIZED_BOTH);
        f.setVisible(true);
    }

}

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

为我全屏显示。我在 Windows 10.

中使用 JDK11

但是,菜单不起作用,因为您遇到了编码问题。您需要将 JMenu 添加到 JMenubar。

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

此外,我一直只使用:

 f.setExtendedState( JFrame.MAXIMIZED_BOTH );