
java中如何让界面窗口居中
用户关注问题
怎样在Java中获取屏幕尺寸以实现窗口居中?
我想在Java程序中让窗口居中显示,但不清楚如何获取当前屏幕的宽高。
使用Toolkit获取屏幕尺寸
可以使用Toolkit类的getScreenSize()方法获取屏幕的宽度和高度,从而计算窗口需要设置的位置,实现窗口居中。示例代码:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
int x = (screenSize.width - frame.getWidth()) / 2;
int y = (screenSize.height - frame.getHeight()) / 2;
frame.setLocation(x, y);
Java Swing中有没有简便方法让JFrame窗口居中?
我使用Swing开发应用,有没有内置方法可以快速让窗口居中,而不用自己计算坐标?
使用setLocationRelativeTo方法快速居中
Swing中JFrame类提供了setLocationRelativeTo(null)方法,调用该方法会自动将窗口居中显示。例如:
frame.setSize(400, 300);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
这段代码会把窗口显示在屏幕正中央。
如何确保Java界面窗口在多显示器环境下居中?
当使用多显示器时,窗口居中是指在主屏幕还是所有屏幕的中间?如何处理?
多显示器环境下的窗口居中处理
多显示器环境下,Toolkit.getScreenSize()返回的是主显示器尺寸。若想让窗口相对于特定显示器居中,可以使用GraphicsEnvironment或GraphicsDevice类获取对应屏幕的边界,再计算居中位置。
示例:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice gd = ge.getDefaultScreenDevice();
Rectangle bounds = gd.getDefaultConfiguration().getBounds();
int x = bounds.x + (bounds.width - frame.getWidth()) / 2;
int y = bounds.y + (bounds.height - frame.getHeight()) / 2;
frame.setLocation(x, y);
这样窗口就会相对于主显示器居中。