AnyLogic:Train对象内修改RailCar中Rectangle颜色报错求助
AnyLogic中动态修改Train的RailCar内部Rectangle填充颜色的解决方案
问题原因
RailCar组件内部的Rectangle属于私有成员变量,外部代码无法直接通过.rectangle访问,因此触发"rectangle cannot be resolved or is not a field"错误。
解决方案一:给RailCar添加自定义公共方法
- 双击打开RailCar组件的编辑界面
- 切换到Functions标签页,新增一个公共方法:
public void setCarFillColor(Color color) { rectangle.setFillColor(color); } - 返回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
相关产品推荐
相关产品推荐

