首页 > 解决方案 > JavaFX (with FXML) 为按钮添加动作事件

问题描述

我有一个带有所需 fx:ids 和以下控制器的 Scene-Builder 构建的 FXML 文件:

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");
}
}

现在我想向按钮添加动作事件。我怎么做?我真的找不到涉及 FXML 文件的东西。

标签: javafx

解决方案


通过 FXML 添加事件处理程序的语法在 FXML简介中进行了描述。它使用#符号和适当的onXXX属性。例如,如果您有以下控制器:

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!");
    }

}

然后 FXML 文件可能类似于:

<?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>

您可以使用 Scene Builder 进行配置,方法是单击所需节点并转到右侧的“代码”面板。将有各种onXXX属性的字段以及fx:id.

在此处输入图像描述


推荐阅读