java - 使用 JMenuBar 制作 JFrame 全屏打开
问题描述
我有一个想要添加菜单栏的 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);
}
}
推荐阅读
- python - 在 Python 中使用 exec() 时如何传递套接字变量?
- javascript - 检查数组中的所有值是否为假
- xcode - Flutter App 安装后崩溃
- rust - Rust 抱怨在执行联合时没有为 HashSet 实现 BitOr,文档声明它应该是
- django - 在一个 VPS 上服务两个网站
- java - 如何将 Deeplearning4j 的 UIServer 端口从 9000 更改为其他端口?
- python - Python 正则表达式将评论拆分为数据框
- reactjs - 使用 orderId 的任何人都可以看到带有订单详细信息的动态路线是否安全?
- java - Postgresql 使用 Java 应用程序发送到后端时发生 I/O 错误
- php - 我想限制复选框的选择。只应检查一项