AnyLogic
Expand
Font size

Replicated controls

Sometimes you need to create an array of similar controls, which can be useful in changing an array of similar objects at runtime as for instance. AnyLogic replicated controls may save you some drawing time and they may also make your model scalable. In this example we will create a replicated button and use it to change the fill color of a replicated shape. Moreover, the number of copies of the button and the shape color will be dynamically controlled by a slider.

Demo model: Replicated Button Open the model page in AnyLogic Cloud. There you can run the model or download it (by clicking Model source files).

Replicated button controlling a replicated shape

  1. Create the following four objects as shown in the figure: a slider, a variable, a button and a rounded rectangle.
  2. Set the Name of the variable to N, its Type to int, and Initial value to 3.
  3. Link the slider to the variable N and set its Minimum value and Maximum value parameters to 1 and 9 correspondingly.
  4. Set the following dynamic properties of the rounded rectangle:
    Replication: N
    Y: 100 50 * index
  5. Set the following dynamic properties of the button:
    Replication: N
    Y: 100 50 * index
    Label: "Paint shape " index
  6. On the General page of the button properties set the Action to:
    roundRectangle.get( index ).setFillColor( blueViolet );
  7. Run the model. Move the slider and press the buttons.

As you can see, the number of buttons changes as the slider changes the variable N. By using the index of the button copy in the button’s Action field you can do different things with different buttons. In our case it is the action of changing the color of the shape, the number of which equals the number of the button. The label of the button also depends on the index.

Replicated text shape referring to a replicated control

You may want to add replicated text shapes nearby the replicated controls. Assume you have a replicated slider and a replicated text shape with the same number of copies defined in the Replication field.

If you set this replicated text shape to display the text: slider.get( index ).getValue() you will get the “Index out of bounds” error. The reason for this is that the replicated copies of the slider might not have been created yet while the text shape is referring to them.

To solve the problem, you have to add this code into the upper-level agent’s On startup code field: slider.createShapes();.

How can we improve this article?