如何创建全局 Robot 变量而不引发 AWTException?
我试图在 Java 类中创建一个全局 Robot
变量,而不抛出 AWTException
。我能想到的唯一方法是抛出异常。我需要它是全局的原因是因为我需要在类中的其他方法中使用相同的 Robot
变量。
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
}
}
如果我不抛出异常,我需要在每个方法中声明一个新的机器人。
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){}
}
}
有人可以帮助我吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
只需使用
throws AWTException
版本,如java.awt.Robot
仅在GraphicsEnvironment.isHeadless()
为 true。这意味着您无论如何都无法使用 Robot 运行您的应用程序。
Just use the
throws AWTException
version, asjava.awt.Robot
only throws this exception whenGraphicsEnvironment.isHeadless()
is true.Which means you can't run your app with Robot anyway.
是否有原因无法在构造函数中捕获 AWTException 并将其包装在 RuntimeException 中?
Is there a reason you can't catch the AWTException in the constructor and throw it wrapped inside a RuntimeException?
在 Robo 类中使用静态初始化块
像这样:
这确保了 JVM 加载 Robo 类文件后立即初始化 Robot 类
use a static initializer block in your Robo class
like this:
This makes sure the Robot class is initialized as soon as the JVM loads the Robo class file