Issue
I want to have a reusable button in JavaFX and give a function to it.
I currently have this:
BackButtonController
public class BackButtonController {
@FXML
private Button btnBack;
private final Method method;
public BackButtonController(Method method) {
this.method = method;
}
@FXML
protected void initialize() {
this.btnBack.setOnMouseClick(() -> buttonClick());
}
public void btnClick() {
// do the received function
}
}
BackButton.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.AnchorPane?>
<AnchorPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
<Button fx:id="btnBack" mnemonicParsing="false" text="Back" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0"
AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0"/>
</AnchorPane>
Controller
protected void initialize() {
try {
var loader = new FXMLLoader(getClass().getResource("/views/backButton.fxml"));
loader.setController(new BackButtonController(this.test()));
this.vbPanel.getChildren().add(0, loader.load());
} catch (IOException e) {
e.printStackTrace();
}
// some other code
}
I want to be able to load the button with a function that I send to the controller so when the button is pressed it runs that function.
I have been looking online but I can't get this to work.
I hope someone can help me with this.
Solution
I would replace the Method with a Runnable object. Then, on button clicked, execute that Runnable.
Like so:
public class BackButtonController {
@FXML
private Button btnBack;
private final Runnable runnable;
public BackButtonController(Runnable r) {
this.runnable= r;
}
@FXML
protected void initialize() {
this.btnBack.setOnMouseClick(() -> buttonClick());
}
public void btnClick() {
runnable.run();
//Alternatively, if you want to run it in a separate Thread, use
new Thread(runnable).start();
}
}
Answered By - AdminOfThis