import java.awt.*;
public class ScreenTest {
private int x;
private int y;
private String error;
// The jvm initializes this to null. If it is not
// instantiated then all uses of the "dm" variable
// will cause a NullPointerException because it
// does not point to an object, viz, it is null.
private DisplayMode dm;
public ScreenTest() {
x = 0;
y = 0;
error = null;
}
public int getRefresh(){
// "dm" is null so you cannot use it here without causing
// a NullPointerException. If you instantiate it with
// the new operator, eg,
// dm = new DisplayMode(width, height, bitDepth, refreshRate);
// in which you supply proper values for each of the arguments,
// then the reference/variable "dm" will point to the new
// object and no longet be null.
return dm.getRefreshRate();
}
public int returnX(){
try {
x = dm.getWidth();
} catch (HeadlessException hexc) {
error = "Failed to initialize value for X";
}
return x;
}
public int returnY(){
try {
y = dm.getHeight();
} catch (HeadlessException hexc) {
error = "Failed to initialize value for Y";
}
return y;
}
public void resetResolution() {
x = 0;
y = 0;
}
public String returnError() {
return error;
}
public static void main(String[] args) {
ScreenTest test = new ScreenTest();
// Threw a NullPointerException in the returnX method.
// test.returnX();
// Explore the local environment:
GraphicsDevice gd =
GraphicsEnvironment.getLocalGraphicsEnvironment()
.getDefaultScreenDevice();
DisplayMode[] modes = gd.getDisplayModes();
for(int i = 0; i < modes.length; i++) {
DisplayMode mode = modes[i];
query(modes[i]);
}
}
private static void query(DisplayMode mode) {
int bitDepth = mode.getBitDepth();
int height = mode.getHeight();
int refreshRate = mode.getRefreshRate();
int width = mode.getWidth();
System.out.printf("bitDepth = %2d refreshRate = %2d " +
"width = %4d height = %d%n",
bitDepth, refreshRate, width, height);
}
}