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)
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
getScreenSizefunction actually expensive? (I do not know whether or not it is)