设置JFrame剧中显示

本文介绍了两种实现界面居中显示的方法。一种是通过计算屏幕尺寸和窗口尺寸来定位,另一种是使用JFreeChart中的RefineryUtilities类提供的方法。这两种方法均可确保窗口在不同屏幕尺寸下居中显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

网上查到的一种方法:

    /**
* 设置整个界面居中显示
*/
private void setCenterDisplay() {
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
Dimension frameSize = this.getSize();
if (frameSize.height > screenSize.height) {
frameSize.height = screenSize.height;
}
if (frameSize.width > screenSize.width) {
frameSize.width = screenSize.width;
}

this.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2);
}

JfreeChart中实现的一种方法,位于jcommon.jar中的org.jfree.ui.RefineryUtilities中:

   /**
* Positions the specified frame in the middle of the screen.
*
*
@param frame the frame to be centered on the screen.
*/
public static void centerFrameOnScreen(final Window frame) {
positionFrameOnScreen(frame, 0.5, 0.5);
}

/**
* Positions the specified frame at a relative position in the screen, where 50% is considered
* to be the center of the screen.
*
*
@param frame the frame.
*
@param horizontalPercent the relative horizontal position of the frame (0.0 to 1.0,
* where 0.5 is the center of the screen).
*
@param verticalPercent the relative vertical position of the frame (0.0 to 1.0, where
* 0.5 is the center of the screen).
*/
public static void positionFrameOnScreen(final Window frame,
final double horizontalPercent,
final double verticalPercent) {

final Rectangle s = frame.getGraphicsConfiguration().getBounds();
final Dimension f = frame.getSize();
final int w = Math.max(s.width - f.width, 0);
final int h = Math.max(s.height - f.height, 0);
final int x = (int) (horizontalPercent * w) + s.x;
final int y = (int) (verticalPercent * h) + s.y;
frame.setBounds(x, y, f.width, f.height);

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值