Search code examples
javaclassobjectstaticscreen-size

Getting Screen Size in Java as a Statric Variable


I am fairly new to Java so this probably has a simple solution but I just can't find the error. I want to get the screen size with a separate class (called Screen) and want it to be accessed as a static variable, like so:

import java.awt.Dimension;
import java.awt.Toolkit;

public class Screen{

public static int width(){

    Dimension size = new Toolkit().getScreenSize();
    return size.width;

}

}

However, I am getting a "Toolkit is abstract; cannot be instantiated" error. Dimension works fine. What am I doing wrong?

Thanks!


Solution

  • To use a Toolkit, you first have to get one by calling the Toolkit static method getDefaultToolkit() and then use the object returned.

    Toolkit toolkit = Toolkit.getDefaultToolkit();
    Dimension size = toolkit.getScreenSize();