Java Swing How to - Get JFrame from main to make fullscreen








Question

We would like to know how to get JFrame from main to make fullscreen.

Answer

import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
//  w  w w . j a  v  a2 s  .c  om
import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;

public class Main {
  public static void main(String[] args) {
    GameFrame gameFrame = new GameFrame();
    gameFrame.setVisible(true);
  }
}

class GameFrame extends JFrame {
  static final GraphicsDevice gd = (GraphicsEnvironment
      .getLocalGraphicsEnvironment().getScreenDevices())[0];
  static final boolean FULLSCREEN_SUPPORTED = gd.isFullScreenSupported();
  JButton fsButton = new JButton("Make Full Screen");
  boolean isFullscreen = false;

  public GameFrame() {
    setSize(300, 300);
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
    if (FULLSCREEN_SUPPORTED) {
      fsButton.addActionListener(e->toggleFullscreen());
      add(fsButton);
    } else {
      add(new JLabel("Fullscreen mode is not supported on this device"));
    }
  }
  public void toggleFullscreen() {
    isFullscreen = !isFullscreen;
    setVisible(false);
    dispose();
    setUndecorated(isFullscreen);
    if (isFullscreen) {
      fsButton.setText("Make Windowed");
      gd.setFullScreenWindow(this);
      validate();
    } else {
      fsButton.setText("Make Full Screen");
      gd.setFullScreenWindow(null);
      setVisible(true);
    }
  }
}