1

I have an issue with firing a button that is located in another class.

I've tried passing button in parameter, but I'm getting null exception error same goes for getter that I've created.

public class ButtonHolder{
    @FXML
    RadioButton radioButton;

    public void radioButtonOnClick(){
        //does something
    }
    public RadioButton getRadioButton(){
        return this.radioButton;
    }
}


public class Example{
    public void fireButton(){
        ButtonHolder buttonHolder = new ButtonHolder();
        buttonHolder.getRadioButton.fire();
    }
}
djm.im
  • 3,295
  • 4
  • 30
  • 45
Wikimmax
  • 59
  • 3
  • 9

1 Answers1

1

The problem

XML (I assume you have XML layout) not connected to your code.

Solution

A better approach in terms of architecture would be to separate"business" logic from UI logic. Let's say you have some code inside radioButtonOnClick.

  • Move the code to a new class to its own merhod
  • Add said class as a dependency to both of your classes;
  • Run new method from both of your classes.

What if I need to use button

You can create it:

//A button with an empty text caption.
Button button1 = new Button();

And then call fire ().

What if control element doesn't have fire method

here's example for RadioMenuItem with EventHandler:

MenuBar menuBar = new MenuBar();

Menu menu = new Menu("Menu 1");

RadioMenuItem choice1Item = new RadioMenuItem("Choice 1");
choice1Item.setOnAction(new EventHandler<ActionEvent>() {
    @Override public void handle(ActionEvent e) {
        System.out.println("radio toggled");
    }
});
RadioMenuItem choice2Item = new RadioMenuItem("Choice 2");
RadioMenuItem choice3Item = new RadioMenuItem("Choice 3");

ToggleGroup toggleGroup = new ToggleGroup();
toggleGroup.getToggles().add(choice1Item);
toggleGroup.getToggles().add(choice2Item);
toggleGroup.getToggles().add(choice3Item);

menu.getItems().add(choice1Item);
menu.getItems().add(choice2Item);
menu.getItems().add(choice3Item);

menuBar.getMenus().add(menu);

VBox vBox = new VBox(menuBar);

Scene scene = new Scene(vBox, 300, 275);
primaryStage.setScene(scene);
primaryStage.show();

What if I want to use button from XML

Take a look at the FXML tutorial: https://riptutorial.com/javafx/example/5125/example-fxml

Andrei Konstantinov
  • 6,971
  • 4
  • 41
  • 57