I have an array full of a few buttons and I am trying to go through the array and give each button a color, however I keep getting a null point exception error.
public static Button[] arrayButtons = new Button[33];
@FXML public Button btn1 = new Button();
@FXML public Button btn2 = new Button();
@FXML public Button btn3 = new Button();
@FXML
public void initializeButtonArray() {
arrayButtons[1] = btn1;
arrayButtons[2] = btn2;
arrayButtons[3] = btn3;
arrayButtons[4] = btn4;
}
@FXML
private void test() {
initializeButtonArray();
for(Button btn : arrayButtons) {
btn.setStyle("-fx-background-color: #FF0000"); //error occurs here
}
}
The error occurs when I try to give all the buttons a color inside my for each loop.
Buttonarray to hold 33 objects, but only assigning 4 of them. So the other 29 remainnull. Also worth noting is that Java is a zero-indexed language, so the first element in your array isarrayButtons[0], notarrayButtons[1]. And finally, you're doingarrayButtons[4] = btn4, but you never createdbtn4in the code you've provided, so this code will never compile as-is.