Java‎ > ‎

Displaying GUI on Multiple Screens

Top level GUI components, like JFrame, can be displayed on a specific screen in a multi-screen environment. Top level windows Frame, JFrame, Window, JWindow, Dialog and JDialog have constructors containing parameter of type GraphicsConfiguration which identifies the target screen device. If the environment has one or more screen devices, one of them is the default screen device.
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import javax.swing.JFrame;
import javax.swing.JLabel;
 
public class Program {
  public static void main(String[] args) {
    GraphicsEnvironment env = GraphicsEnvironment.getLocalGraphicsEnvironment();
    GraphicsDevice[] screenDevices = env.getScreenDevices();
    GraphicsDevice primaryScreenDevice = env.getDefaultScreenDevice();
    GraphicsDevice secondaryScreenDevice = null;
    for (int i = 0; i < screenDevices.length; i++) {
      if (!primaryScreenDevice.equals(screenDevices[i])) {
        secondaryScreenDevice = screenDevices[i];
        break;
      }
    }
    if (secondaryScreenDevice == null) {
      secondaryScreenDevice = primaryScreenDevice;
    }
 
    JFrame frame1 = new JFrame(primaryScreenDevice.getDefaultConfiguration());
    frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame1.add(new JLabel("primary screen"));
    frame1.pack();
    frame1.setVisible(true);
 
    JFrame frame2 = new JFrame(secondaryScreenDevice.getDefaultConfiguration());
    frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame2.add(new JLabel("secondary screen"));
    frame2.pack();
    frame2.setVisible(true);
  }
}
Comments