Show JFrame in a specific screen in dual monitor configuration
public static void showOnScreen( int screen, JFrame frame )
{
GraphicsEnvironment ge = GraphicsEnvironment
.getLocalGraphicsEnvironment();
GraphicsDevice[] gs = ge.getScreenDevices();
if( screen > -1 && screen < gs.length )
{
gs[screen].setFullScreenWindow( frame );
}
else if( gs.length > 0 )
{
gs[0].setFullScreenWindow( frame );
}
else
{
throw new RuntimeException( "No Screens Found" );
}
}
I have modified @Joseph-gordon's answer to allow for a way to achieve this without forcing full-screen:
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" );
}
}
In this code I am assuming getDefaultConfiguration()
will never return null. If that is not the case then someone please correct me. But, this code works to move your JFrame
to the desired screen.
A much cleaner solution after reading the docs for JFrame.setLocationRelativeTo Display on screen 2
public void moveToScreen() {
setVisible(false);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screens = ge.getScreenDevices();
int n = screens.length;
for (int i = 0; i < n; i++) {
if (screens[i].getIDstring().contentEquals(settings.getScreen())) {
JFrame dummy = new JFrame(screens[i].getDefaultConfiguration());
setLocationRelativeTo(dummy);
dummy.dispose();
}
}
setVisible(true);
}
This function can be used to switch application window between screens
I have modified @Joseph-gordon and @ryvantage answer to allow for a way to achieve this without forcing full-screen, fixed screen configuration position and center it on select screen:
public void showOnScreen(int screen, JFrame frame ) {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] gd = ge.getScreenDevices();
int width = 0, height = 0;
if( screen > -1 && screen < gd.length ) {
width = gd[screen].getDefaultConfiguration().getBounds().width;
height = gd[screen].getDefaultConfiguration().getBounds().height;
frame.setLocation(
((width / 2) - (frame.getSize().width / 2)) + gd[screen].getDefaultConfiguration().getBounds().x,
((height / 2) - (frame.getSize().height / 2)) + gd[screen].getDefaultConfiguration().getBounds().y
);
frame.setVisible(true);
} else {
throw new RuntimeException( "No Screens Found" );
}
}
Please Refer to GraphicsDevice API, you have a good example there.