0

Lets say I have two buttons in the FXML for instance:

<Button fx:id="button1" onAction="#onClick1" prefHeight="134.0" prefWidth="134.0"></Button>
<Button fx:id="button2" onAction="#onClick2" prefHeight="134.0" prefWidth="134.0"></Button>

and I want to have it as an array of buttons in the controller class. How can I go about and do that? I have tried:

public Button button1, button2;
public Button[] arrayButtons = {button1, button2}

and also tried making a method:

public class controller {
    public Button button1, button2;
    public Button[] arrayButtons;

    public void initializeButtonArray() {
        arrayButtons = new Button[2];
        arrayButtons[1] = button1;
        arrayButtons[2] = button2;
    }
}

none of these work as it gives me a runtime exception when I try to do something with the array (ie. arrayButton[1].setText("Test")):

java.lang.RuntimeException: java.lang.reflect.InvocationTargetException

How can I go about and have an array of Button where the elements are from fx:id?

2
  • 2
    Just rename initializeButtonArray to initialize (or call the initializeButtonArray() method from initialize()). Commented Nov 17, 2016 at 17:56
  • Thank you so much! Commented Nov 17, 2016 at 18:07

1 Answer 1

1

Here you are:

1)@FXML annotation is used cause the Objects are private.In case you make them public there is no need to use @FXML

2)As soon as FXMLLoader has loaded the controller the initialize method is called.Inside it you are sure that every object linked with fxml scene graph has been initialized.

🏁Code(Obviously this is one way and you can do it in various other ways):

public class controller { 


@FXML
private Button button1;

@FXML
private Button button2;

public Button[] arrayButtons;

@FXML
public void initialize(){ 

initializeButtonArray();

}
 public void initializeButtonArray() { 

    arrayButtons = new Button[2];  
    arrayButtons[1] = button1;
    arrayButtons[2] = button2;
 } 

}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.