Java Swing How to - Change screen display mode such as resolution








Question

We would like to know how to change screen display mode such as resolution.

Answer

import java.awt.DisplayMode;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
//  w w  w  .j av  a 2  s  .  co  m
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;

public class Main {

  private static boolean programmatic = false;

  public static void main(String[] args) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    GraphicsDevice device = GraphicsEnvironment.getLocalGraphicsEnvironment()
        .getDefaultScreenDevice();
    device.setFullScreenWindow(frame);
    device.setDisplayMode(new DisplayMode(800, 600, 32, 60));

    frame.addWindowListener(new WindowAdapter() {
      @Override
      public void windowIconified(WindowEvent we) {
        if (programmatic) {
          programmatic = false;
          frame.setState(JFrame.NORMAL);
        }
      }
    });

    JButton btn = new JButton();
    btn.setText("Btn");
    final JPanel panel = new JPanel();

    panel.add(btn);
    frame.add(panel);

    btn.addActionListener(e -> {
      programmatic = true;
      JOptionPane.showMessageDialog(panel, "Sample");
    });
    frame.setVisible(true);
  }
}