Search code examples
javatextanylogic

Anylogic change button label dynamically


I am trying to change the text of an already created Button. On the document page there is a reference saying that there is a property setText​(java.lang.Object text) that sets the button label text. However how do I create the text object? At first I thought I should create a ShapeText and pass it as the text argument, but when I tried to do it it changed the label of the button for the name of the ShapeText object reference.

I used this constructor and assigned to the button:

ShapeText new_text = new ShapeText​(true, 190.0, 190.0, 0, black, "My new button label", my_new_font, alignment)

button1.setText(new_text)

However the label of the button doesn't change to "My new button label". What am I missing?


Solution

  • You can simply use a String argument for the setText method of the button element, so you can use button1.setText("My new button label").

    (It is probably defined as an Object in the documentation, because the method also works with integer, boolean, etc. type arguments.)

    If you need to change the appearance too during runtime, a possible solution is using a Rounded rectangle (or any other shape) and a Text element on top of it instead of the standard Button. The shapes have 'On click' properties where you can call the desired action. Text doesn't have a built-in method to make it bold, but you have lots of other options for customization this way even if you only write simpler code.