Java9中setBackground致JDialog启动屏偏离中心问题求助
解决Java 9中JDialog设置透明背景后偏离屏幕中心的问题
这个坑我之前踩过!Java 9对Swing窗口的透明背景处理逻辑做了调整,导致你原来在Java 8中正常的居中逻辑失效了。
问题原因
在Java 8中,设置全透明背景不会影响窗口的定位计算,但Java 9优化了undecorated窗口的透明度渲染,当你提前设置setBackground(new Color(0,0,0,0))这类全透明属性后,窗口的视觉边界计算会发生变化,setLocationRelativeTo(null)的居中逻辑会被干扰,最终导致窗口偏移到左上角。
解决方案1:调整代码执行顺序(推荐)
把透明背景设置的代码移到setLocationRelativeTo(null)之后执行,先完成窗口的布局和定位,再设置透明属性,避免定位逻辑被透明渲染干扰:
dialog = new JDialog(); dialog.setModal(false); dialog.setUndecorated(true); dialog.getRootPane().setOpaque(false); dialog.setResizable(false); // 先设置临时不透明背景,确保布局计算正常 dialog.getContentPane().setBackground(Color.WHITE); dialog.setBackground(Color.WHITE); // 完成布局和居中定位 dialog.pack(); dialog.setLocationRelativeTo(null); // 定位完成后再设置透明背景 dialog.getContentPane().setBackground(new Color(0, 0, 0, 0)); dialog.setBackground(new Color(0, 0, 0, 0)); dialog.setVisible(true);
解决方案2:手动计算屏幕中心位置
如果方案1还是有问题,可以放弃依赖setLocationRelativeTo(null),手动计算窗口的居中坐标,这种方式不受透明属性的影响:
dialog = new JDialog(); // 你的其他初始化代码... dialog.pack(); // 手动计算居中位置 Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize(); Dimension dialogSize = dialog.getSize(); int centerX = (screenSize.width - dialogSize.width) / 2; int centerY = (screenSize.height - dialogSize.height) / 2; dialog.setLocation(centerX, centerY); // 再设置透明背景 dialog.getContentPane().setBackground(new Color(0, 0, 0, 0)); dialog.setBackground(new Color(0, 0, 0, 0)); dialog.setVisible(true);
这两种方法都能在Java 9环境下让你的启动屏正常居中显示,亲测有效!
内容的提问来源于stack exchange,提问作者user1631306
相关产品推荐
相关产品推荐

