Java Swing:居中组件
我正在开发一个 Swing UI,我想在其中集中多个组件(JDialogs 和 JFrames)。我知道以下代码将计算用户的屏幕尺寸,从那里,我可以轻松地将组件居中:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
为了提高效率,我应该只计算一次并将其存储在某种常量中,以便可以在任何部分重用项目的。存储它以供以后重用以便可以跨多个类访问的最佳实践是什么?
(此外,如果有更好的方法来计算居中的屏幕尺寸,我也愿意听到)
I'm working on a Swing UI in which I want to center multiple components (JDialogs and JFrames). I know that the following code will calculate the user's screen size, and from there, I can easily center a component:
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
For efficiency's sake, I should only calculate this once and store it in some kind of constant so it can be reused in any part of the project. What is the best practice for storing this for later reuse so it is accessible across multiple classes?
(Furthermore, if there is a better way of calculating screen size for centering, I'd be open to hearing that as well)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
java .awt.Window.setLocationRelativeTo(null) 会将其在屏幕上居中,而
setLocationRelativeTo(someComponent)
将其相对于 java.awt.Component 居中,someComponent。替代存储中心需要考虑的一件事是,如果用户在程序运行时调整分辨率,则存储的常量将不再有效。调用
getScreenSize
函数真的很昂贵吗? (不知道是不是)java.awt.Window.setLocationRelativeTo(null) will center it on the screen while
setLocationRelativeTo(someComponent)
will center it relative to the java.awt.Component, someComponent.One thing to consider with the alternate of storing the center, is that if a user adjusts their resolution while the program is running than the stored constants will no longer be valid. Is recalling the
getScreenSize
function actually expensive? (I do not know whether or not it is)这意味着对话框/框架的大小是 (0, 0),您的基本代码应该是:
This means the size of the dialog/frame is (0, 0), Your basic code should be:
为了使对象居中,您应该尝试:
X 中的框架位置 = (半框架宽度) - (半屏幕尺寸宽度)
Y = (半帧高度) - (半屏幕尺寸高度) 几乎相同
您可以轻松地将值存储在具有公共访问权限的主类中,因此您不需要多次读取它们
For centering the object you should try:
The frame position in X = (half frame width) - (half screen size width)
Almost the same for Y = (half frame height) - (half screen size height)
You can easily stores the values in the main class with public access, so you don't need to read them several times
此外,如果您自己执行此操作,则需要使用 Toolkit.getScreenInsets 考虑屏幕的插图,以考虑任务栏等内容,该任务栏可能位于任何屏幕边缘并且具有任何大小。
在我瞄准 Java 1.4 之前,我使用了:
Also, if you do it yourself, you need to factor in the screen's insets using
Toolkit.getScreenInsets
to account for things like the task bar, which might be on any screen edge and be of any size.Before I could target Java 1.4, I used: