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