You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java识别指定颜色并执行操作时条件判断失效问题

问题解决:Color对象比较失效的原因及修复方案
  • 核心问题:对象引用 vs 内容比较
    Java里==比的是对象的内存地址,不是实际内容。你代码里的color和iron2是两个独立创建的Color对象,哪怕RGB数值完全一样,它们的内存引用也不同,所以color == iron2永远不会成立。

把判断条件改成用equals()方法,它会直接比较两个Color对象的RGB值:

if (color.equals(iron2)) {
    Robot move = new Robot();
    move.mouseMove(x,y);
    System.out.println(iron2);
}
  • 额外优化点
  1. 减少不必要的对象创建:把iron和iron2的实例化移到循环外面,不用每次循环都新建一遍:
// 移到循环外
Color iron = new Color(50,26,17);
Color iron2 = new Color(7,5,16);

for (int i=0; i<image.getWidth()-1; i++){
    int x = i; // 直接用循环变量作为x坐标,避免初始值混乱
    for (int j=0; j<image.getHeight()-1; j++){
        int y = j; // 同理用j作为y坐标
        int c = image.getRGB(x,y);
        int red = (c & 0x00ff0000) >> 16;
        int green = (c & 0x0000ff00) >> 8;
        int blue = c & 0x000000ff;
        Color color = new Color(red,green,blue);
        System.out.println(color);
        
        if (color.equals(iron2)){
            Robot move = new Robot();
            move.mouseMove(x,y);
            System.out.println(iron2);
        }
    }
}
  1. 修正坐标逻辑:原代码中x的初始值未定义,且每次循环x += 1容易导致坐标偏移,直接用循环变量i、j作为x、y坐标更准确。

内容的提问来源于stack exchange,提问作者Daniel Lucas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.24 18:49:11