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

AnyLogic:Train对象内修改RailCar中Rectangle颜色报错求助

AnyLogic中动态修改Train的RailCar内部Rectangle填充颜色的解决方案

问题原因

RailCar组件内部的Rectangle属于私有成员变量,外部代码无法直接通过.rectangle访问,因此触发"rectangle cannot be resolved or is not a field"错误。


解决方案一:给RailCar添加自定义公共方法

  1. 双击打开RailCar组件的编辑界面
  2. 切换到Functions标签页,新增一个公共方法:
    public void setCarFillColor(Color color) {
        rectangle.setFillColor(color);
    }
    
  3. 返回Train所在的主模型,调用该方法修改颜色:
    this.getCar(0).setCarFillColor(maroon);
    

解决方案二:遍历RailCar的图形元素获取Rectangle

如果不想修改RailCar内部代码,可通过遍历图形元素列表定位目标Rectangle:

RailCar targetCar = this.getCar(0);
for (Shape shape : targetCar.getShapes()) {
    if (shape instanceof Rectangle) {
        // 若有多个Rectangle,可通过shape.getName()匹配自定义名称精准定位
        ((Rectangle) shape).setFillColor(maroon);
        break;
    }
}

注意事项

  • 确保maroon是已定义的Color变量,也可直接使用AnyLogic内置常量Color.MAROON
  • 若RailCar内存在多个Rectangle,建议给目标Rectangle设置唯一名称,再通过shape.getName().equals("自定义矩形名")判断定位

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 18:06:39