Java Swing How to - Show JFrame On Additional Screen








Question

We would like to know how to show JFrame On Additional Screen.

Answer

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
/*w  w w  .  j  a va  2s  . c  o m*/
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.KeyStroke;

public class Main {
  void initUI() {
    GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
    int i = 1;
    for (GraphicsDevice gd : ge.getScreenDevices()) {
      JFrame frame = new JFrame();
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.add(createLabel(String.valueOf(i)));
      frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW)
          .put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "exit");
      frame.getRootPane().getActionMap().put("exit", new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
          System.exit(0);
        }
      });
      frame.setLocation(gd.getDefaultConfiguration().getBounds().getLocation());
      frame.setUndecorated(true);
      frame.setExtendedState(frame.getExtendedState() | JFrame.MAXIMIZED_BOTH);
      frame.setVisible(true);
      gd.setFullScreenWindow(frame);
      i++;
    }
  }
  private JLabel createLabel(String label) {
    JLabel jLabel = new JLabel(label);
    jLabel.setHorizontalAlignment(JLabel.CENTER);
    jLabel.setFont(jLabel.getFont().deriveFont(48.0f));
    jLabel.setFocusable(true);
    return jLabel;
  }
  public static void main(String[] args) {
    new Main().initUI();
  }
}