0

我有一种动画正在进行,其中一个矩形的大小正在增加和减少........我在这里要做的是通过 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()
{}
}
4

1 回答 1

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;
        }
    }
}

是的,你可以在任何地方使用机器人并且你可以处理异常,但是它们中的大多数是运行时异常,所以你不必这样做。

于 2014-01-29T14:31:23.163 回答