I am trying to open a JFrame on the second screen and to center it. I can open JFrame on the second screen but how to center it. Here is a sample code I made:
import javax.swing.*;
import java.awt.*;
public class Question {
public Question() {
JFrame f = new JFrame();
JPanel panel = new JPanel();
f.getContentPane().add(panel);
f.pack();
f.setTitle("Hello");
f.setSize(200,200);
showOnScreen(1,f);
f.setVisible(true);
}
public static void main(String[] args) {
Runnable r = new Runnable() {
@Override
public void run() {
new Question();
}
};
SwingUtilities.invokeLater(r);
}
public static void showOnScreen( int screen, JFrame frame ) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
if( screen > -1 && screen < gd.length ) {
frame.setLocation(gd[screen].getDefaultConfiguration().getBounds().x, frame.getY());
} else if( gd.length > 0 ) {
frame.setLocation(gd[0].getDefaultConfiguration().getBounds().x, frame.getY());
} else {
throw new RuntimeException( "No Screens Found" );
}
}
}
I tried something like this to center it in second screen:
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().x*3/2)-200, ((gd[screen].getDefaultConfiguration().getBounds().height)/2)-200);
It works but i don't want to hard code because later in the actual program, the frame size change.
Also i tried this:
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().width)/2-frame.getSize().width/2, (gd[screen].getDefaultConfiguration().getBounds().height)/2-frame.getSize().height/2);
But then it opens it on the first screen. Makes sense.
Please someone can help to apply the right fix. Appreciate your help. Thanks.