JavaFX (with FXML) Adding Action events for buttons

倾然丶 夕夏残阳落幕 提交于 2020-06-29 04:36:05

问题


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.


回答1:


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.




回答2:


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"


来源:https://stackoverflow.com/questions/54035976/javafx-with-fxml-adding-action-events-for-buttons

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!