我有一种动画正在进行,其中矩形正在增加和减小尺寸........我想在这里做的是通过Robot()类检测特定位置的颜色但是它的没发生..........为什么?我还想知道Robot()是否可以在try或没有main()类之外使用。
//<applet code=ctry.java width=500 height=500></applet>
import java.awt.*;
import java.applet.Applet;
import java.awt.AWTException;
public class ctry extends Applet implements Runnable{
Thread d=null;
int l=0,t=0,i=250,j=250;
Color color=null;
public void init(){
setBackground(Color.red);
}
public void start(){
d=new Thread(this);
d.start();
}
public void run(){
System.out.println("in run");
try{
Robot robo=new Robot();
System.out.println("after robo");
while(true){
System.out.println("in while");
repaint();
color=robo.getPixelColor(i,j);
System.out.println("Red = " + color.getRed());
l+=10;
t+=10;
d.sleep(100);
if(t>=225)
{t=0;}
if(l>=225)
{l=0;}
}
}
catch(Exception e)
{}
}
public void paint(Graphics g)
{
System.out.println("in paint");
g.setColor(Color.blue);
g.fill3DRect(225,225,l*2,t*2,true);
}
public void destroy()
{}
}
答案 0 :(得分:0)
您可以尝试捕捉图像并检查其中的颜色。 Robot.getPixelColor()非常慢,每次都返回一个新的Color实例。请尝试使用BufferedImage:
Color color = Color.black;
int screenWidth = 768;
int screenHeight = 1024;
Rectangle rectangle = new Rectangle(screenWidth, screenHeight);
BufferedImage image = robot.createScreenCapture(rectangle);
for (int y = 0 ; y < screenHeight ; y++) {
for (int x = 0 ; x < screenWidth ; x++) {
if(image.getRGB(x, y) == color.getRGB()) {
return true;
}
}
}
是的,你可以在任何地方使用Robot,你可以处理异常,但大多数都是运行时异常,所以你不必这样做。