Question

I'm trying to create a global Robot variable in a Java class without throwing an AWTException. The only way that I can come up with it is by throwing the exception. The reason I need it to be global is because I need to use the same Robot variable in other methods in the class.

public class Robo{
    Robot r;

    public Robo() throws AWTException{
        r = new Robot();
    }

    public void useRobot(){       
        r.mouseMove(5, 5);
        r.toString();
    }

    public void useRobot2(){
        //r....some other things
    }
}

If I don't throw the exception, I need to declare a new Robot in every method.

public class Robo{

    public Robo() {

    }

    public void useRobot(){
        try{
            Robot r = new Robot();
            r.mouseMove(5, 5);
            r.toString();
        }
        catch (AWTException e){}
    }

    public void useRobot2(){
        try{
            Robot r = new Robot();
            r...... //some other things
        }
        catch (AWTException e){}
    }
}

Can somebody help me?

Was it helpful?

Solution

Just use the throws AWTException version, as java.awt.Robot only throws this exception when GraphicsEnvironment.isHeadless() is true.

Which means you can't run your app with Robot anyway.

OTHER TIPS

Is there a reason you can't catch the AWTException in the constructor and throw it wrapped inside a RuntimeException?

public Robo() {
    try {
        r = new Robot();
    } catch(AWTException e) {
        throw new RuntimeException("Failed to create java.awt.Robot for Robo instance", e);
    }
}

use a static initializer block in your Robo class like this:

public static Robot r;

static
{
    try {
        r = new Robot();
    } catch(AWTException e){e.printStrackTrace();}
}

This makes sure the Robot class is initialized as soon as the JVM loads the Robo class file

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top