Kevin Swartz
Kevin Swartz

Reputation: 99

How do you add data bars to a chart via Java?

On startup, I'm trying to add a varying quantity of values to a barchart. I have an agent type Component. It has a few variables associated with it, one being hopperLevel. I create multiple Component agents based on an Excel sheet that assigns values to these variables. The number of Component agents created depends on the number of rows filled out on the Excel sheet. As the simulation runs, hopperLevel changes and I'd like to chart components(0).hopperLevel, components(1).hopperLevel, components(2).hopperLevel, etc. for all components.

I've tried the addDataItem method in the On startup field like this:

for ( Component comp : components )
{
    chartHopperLevels.addDataItem(comp.hopperLevel, comp.componentName, blue);
} 

but get the error:

"The method addDataItem(DataItem, String, Color) in the type BarChart is not applicable for the arguments (int, String, Color)"

I understand that an int isn't a DataItem, but I'm not sure what a DataItem is.

How do I use this method? Or is there a better way?

Upvotes: 2

Views: 819

Answers (2)

Florian
Florian

Reputation: 972

You cannot directly refer to an value in the addDataItem() function. This is because Java cannot monitor a value and do something if it changes.

Instead, AnyLogic has defined the DataItem which contains more or less only an update function which gets triggered and then pulls a new version of your value. The trigger can be automatically (setting Update data automatically in your chart) or manually (DataItem.update()). This update function is custom build for every value that you want to monitor.

You can build such a custom DataItem/update function (here: for variable myVariable) in the Additional class code in main:

Custom Update Function

public class MyDataItem extends DataItem{
@Override
    public void update(){
        super.setValue(myVariable);
    }
}

You can the initialise your custom version of the DataItem like this:

DataItem di = new MyDataItem();

And finally you can add it (like you already did) to your barchart:

chart.addDataItem(di, "my value", red);

Upvotes: 3

Benjamin
Benjamin

Reputation: 12785

you need to read and understand the API on creating a DataItem first, see the AnyLogic help.

You can create a DataItem as below:

DataItem myItem = new DataItem();
myItem.setValue(12);
chart.addDataItem(myItem, "cool", Color.blue);

So you create a separate DataItem object first and then set its value to something you like. Then, you can add that to your bar chart (which is called "chart" in my example code above).

cheers

Upvotes: 2

Related Questions