What's the code to position a JFrame N pixels (say 300 pixels in x-direction) away from the center of the screen before one calls setVisible(true)?
I typically do something like the following to center a JFrame. You can add the offset to the wdwLeft
variable as shown in the listing to move the frame off center. (The call to setPreferredSize()
is superfluous and only there to make this demo work.)
package testapplication;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Toolkit;
import javax.swing.JFrame;
public class MyJFrame extends JFrame {
MyJFrame() {
super("Test");
Dimension screenSize = new Dimension(Toolkit.getDefaultToolkit().getScreenSize());
setPreferredSize(new Dimension(200, 200));
Dimension windowSize = new Dimension(getPreferredSize());
int wdwLeft = 300 + screenSize.width / 2 - windowSize.width / 2;
int wdwTop = screenSize.height / 2 - windowSize.height / 2;
pack();
setLocation(wdwLeft, wdwTop);
}
public static void main(final String [] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
final MyJFrame jf = new MyJFrame();
jf.setVisible(true);
}
}
);
}
}
You can add additional logic to assure that the offset window is still completely within the screen as determined by getMaximumWindowBounds()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With