Switching to another display mode

From JDK1.4, you can use the class DisplayMode. Either instantiate a DisplayMode object by specifying width, height, bitdepth and refreshrate, or get a list of available DisplayModes by calling the method getDisplayModes on the current GraphicsDevice.

When you’ve made up your mind about the display mode, call the method setFullScreenWindow to get the device into “full-screen exclusive mode” (necessary) and the method setDisplayMode to perform the display change.

Main.java:

import javax.swing.*;
import java.awt.event.*;
import java.util.*;
import java.awt.*;
 
public class Main extends JFrame {
   DisplayMode oldDm;
 
   public Main() {
      addWindowListener(new WindowAdapter() {
         public void windowClosing(WindowEvent we) {
            System.exit(1);
         }
      });
 
      GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment (); 
      final GraphicsDevice gd = ge.getDefaultScreenDevice ();
 
      oldDm = gd.getDisplayMode();
      final DisplayMode dm[] = gd.getDisplayModes();
 
      Vector v = getDisplayModesAsStrings(dm);
      final JComboBox cb = new JComboBox(v);
      cb.addActionListener(new ActionListener() {
         public void actionPerformed(ActionEvent ae) {
            int selectedIndex = cb.getSelectedIndex();
            gd.setFullScreenWindow(Main.this);
        
            if (gd.isDisplayChangeSupported()) {
               try {
                  gd.setDisplayMode(dm[selectedIndex]); 
               } catch(Exception e) {
                  gd.setDisplayMode(oldDm);
               }
            }
            else {
               System.out.println("Display change not supported!");
            }            
         }
      });
 
      getContentPane().setLayout(new FlowLayout(FlowLayout.LEFT, 10, 10));
      getContentPane().add(new JLabel("Change to display mode:"));
      getContentPane().add(cb);
      pack();  
   }
 
   public Vector getDisplayModesAsStrings(DisplayMode dm[]) {
      Vector v = new Vector();
 
      for (int i=0; i<dm.length; i++) {
         int width = dm[i].getWidth();
         int height = dm[i].getHeight();
         int bitDepth = dm[i].getBitDepth();
         int refreshRate = dm[i].getRefreshRate();
         v.add("" + width + "x" + height + " " + bitDepth + "bit " + 
                              (refreshRate == 0 ? "unknown" : ""+refreshRate + "hz"));
      }
 
      return v;
   }
 
   public static void main(String[] args) {
      Main main = new Main();
      main.setVisible(true);
   } 
}