在主屏幕上居中框架的最简单方法(如果您有多个屏幕,则有选项)是使用 setLocationRelativeTo(...) 框架方法,并将 null 作为参数:
JFrame frame = new JFrame ();
frame.setSize ( 500, 300 );
frame.setLocationRelativeTo ( null );
frame.setVisible ( true );
如果这不起作用 - 试试这个(直接坐标):
Dimension ss = Toolkit.getDefaultToolkit ().getScreenSize ();
Dimension frameSize = new Dimension ( 500, 300 );
JFrame frame = new JFrame ();
frame.setBounds ( ss.width / 2 - frameSize.width / 2,
ss.height / 2 - frameSize.height / 2,
frameSize.width, frameSize.height );
frame.setVisible ( true );
最后一个也是“终极”的例子——它将在每个可用的系统屏幕上显示居中的框架:
public static void main ( String[] args )
{
Dimension frameSize = new Dimension ( 500, 300 );
for ( GraphicsDevice screen : getGraphicsDevices () )
{
GraphicsConfiguration gc = screen.getDefaultConfiguration ();
Rectangle sb = gc.getBounds ();
JFrame frame = new JFrame ( gc );
frame.setDefaultCloseOperation ( JFrame.EXIT_ON_CLOSE );
frame.setBounds ( sb.x + sb.width / 2 - frameSize.width / 2,
sb.y + sb.height / 2 - frameSize.height / 2, frameSize.width,
frameSize.height );
frame.setVisible ( true );
}
}
public static List<GraphicsDevice> getGraphicsDevices ()
{
List<GraphicsDevice> devices = new ArrayList<GraphicsDevice> ();
for ( GraphicsDevice gd : GraphicsEnvironment.getLocalGraphicsEnvironment ()
.getScreenDevices () )
{
if ( gd.getType () == GraphicsDevice.TYPE_RASTER_SCREEN )
{
if ( gd == GraphicsEnvironment.getLocalGraphicsEnvironment ()
.getDefaultScreenDevice () )
{
devices.add ( 0, gd );
}
else
{
devices.add ( gd );
}
}
}
return devices;
}