Reputation: 101
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.
Upvotes: 3
Views: 1706
Reputation: 3224
To show centered on a secondary screen (last, in this example) I did this:
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
GraphicsConfiguration gc = gd[gd.length - 1].getDefaultConfiguration();
frame.setLocationRelativeTo(new JFrame(gd));
as per setLocationRelativeTo(Component c)
documentation:
If the component is not null, but it is not currently showing, the window is placed in the center of the target screen defined by the GraphicsConfiguration associated with this component.
Upvotes: 1
Reputation: 101
This is how i solved. My application can have max two screens.
public void showOnScreen( int screen, JFrame frame ) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
if( screen > 0 && screen < 2 ) {
int x = frame.getWidth()/2;
int y = frame.getHeight()/2;
frame.setLocation((gd[screen].getDefaultConfiguration().getBounds().width * 3/2) - x, (gd[screen].getDefaultConfiguration().getBounds().height *1/2) - y);
} else if( gd.length > 0 ) {
frame.setLocationRelativeTo(null);
} else {
throw new RuntimeException( "No Screens Found" );
}
}
Upvotes: 2