开发者

How can I create a global Robot variable without throwing an AWTException?

开发者 https://www.devze.com 2022-12-10 12:30 出处:网络
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

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?


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消