Java使用全屏独占模式(FSEM)时如何去除JFrame标题栏?
问题根因
setUndecorated(true)必须在窗口首次显示、或者被设置为全屏窗口之前调用,你当前代码里调用时机太晚,且和setExtendedState的顺序错误,导致装饰属性未生效。- 不需要手动设置内边距,只要
undecorated属性正确生效,Swing会自动移除标题栏和默认边框的内边距。
修正步骤
- 调整
GameWindow构造函数里的属性设置顺序,把setUndecorated(true)移到所有窗口状态设置、全屏设置的最前面 - 移除冗余的
setExtendedState(JFrame.MAXIMIZED_BOTH)调用,graphicsDevice.setFullScreenWindow会自动处理窗口大小和状态,不需要额外设置最大化 - 窗口尺寸相关的设置(setSize、setPreferredSize等)在全屏独占模式下是冗余的,仅需要在不支持全屏模式的降级逻辑中保留
- 你代码里实现了WindowListener但没有重写对应方法,建议补全或者移除接口实现避免编译警告
修正后的核心代码片段
public GameWindow( ) { super("Window"); // 必须在所有窗口状态操作之前设置无装饰 setUndecorated(true); setResizable(false); DisplayMode origDisplayMode = null; GraphicsDevice graphicsDevice= null ; GraphicsEnvironment graphicsEnvironment = GraphicsEnvironment.getLocalGraphicsEnvironment(); GraphicsDevice[] devices = graphicsEnvironment.getScreenDevices(); for(int cnt = 0;cnt < 1;cnt++){ System.out.println(devices[cnt]); } graphicsDevice= devices[0]; if (graphicsDevice.isFullScreenSupported()){ setTitle("FRAME MAX"); graphicsDevice.setFullScreenWindow(this); revalidate(); repaint(); Toolkit.getDefaultToolkit().sync(); System.out.println("OK Full-screen mode is supported"); } else { System.out.println("XX Full-screen mode is not supported"); // 仅非全屏模式下手动设置窗口大小 origDisplayMode = graphicsDevice.getDisplayMode(); Dimension dim=new Dimension(origDisplayMode.getWidth(),origDisplayMode.getHeight()); setSize(dim); setPreferredSize(dim); setMinimumSize(dim); setLocationRelativeTo(null); } }
额外注意事项
- 如果是在Java 9+版本运行,建议添加VM参数
-Dsun.java2d.uiScale=1避免高DPI缩放带来的额外边距 - 不要在
setFullScreenWindow调用之后再修改窗口的装饰属性,会导致属性失效
内容的提问来源于stack exchange,提问作者user13887828
相关产品推荐
相关产品推荐

