有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java制作JFrame并全屏打开JMenuBar

我有一个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岁,两人都有问题


共 (2) 个答案

  1. # 1 楼答案

    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 );
    
  2. # 2 楼答案

    您需要按正确的顺序调用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);
        }
    
    }