Zehke
Zehke

Reputation: 139

JavaFX (with FXML) Adding Action events for buttons

I have a FXML-File build with Scene-Builder with the needed fx:ids and the following controller:

public class LaunchLogin extends Application{

public static void main (String [] args) {
    launch(args);
}

@Override
public void start (Stage primaryStage) throws Exception {
    //ResourceLoader rl = ResourceLoader.getInstance();
    FXMLLoader loader = new FXMLLoader();
    loader.setLocation(getClass().getResource("/gfx/gui/LoginScreenUI.fxml"));
    Parent root = loader.load();
    Scene scene = new Scene(root);
    scene.getStylesheets().add("/gfx/gui/cogfitStyle.css");
    primaryStage.setScene(scene);
    primaryStage.setTitle ("CogFit");
    primaryStage.show();
}
@FXML
Button btn_newUser;


@FXML
Button btn_changePW;

@FXML
Button btn_send;

@FXML
private void test(ActionEvent event)
{
    System.out.println("success");
}
}

Now I want to add action events to the buttons. How do I do that? I cannot really find something that involves FXML-Files.

Upvotes: 1

Views: 21159

Answers (2)

Jannik
Jannik

Reputation: 427

In Scene Builder under "Code" there is a field onAction. You have to put the name of the method in your controller class there. Or add the following code to the button properties in the FXML file:

onAction="#method"

Upvotes: 1

Slaw
Slaw

Reputation: 46170

The syntax for adding event handlers via FXML is described by Introduction to FXML. It uses the # symbol along with the appropriate onXXX attribute. For example, if you have the following controller:

package example;

import javafx.event.ActionEvent;  
import javafx.fxml.FXML;

public class Controller {

    @FXML
    private void printHelloWorld(ActionEvent event) {
        event.consume();
        System.out.println("Hello, World!");
    }

}

Then the FXML file might look something like:

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.scene.control.Button?>
<?import javafx.scene.layout.StackPane?>

<StackPane xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1"
           fx:controller="example.Controller" prefWidth="500" prefHeight="300">

    <Button text="Click me!" onAction="#printHelloWorld"/>

</StackPane>

You can configure this using Scene Builder by clicking on the desired node and going to the "Code" panel on the right side. There will be fields for the various onXXX properties as well as a field for fx:id.

enter image description here

Upvotes: 8

Related Questions