javafx - 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 文件的东西。
解决方案
通过 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
.
推荐阅读
- c# - 无法在 Visual Studio 2019 社区版 16.7.2 中使用外部应用程序调试 c# dll 项目
- javascript - JS(反应)的问题。按钮不起作用
- android - 无法获取“http://jcenter.bintray.com/com/google/jimfs/jimfs/1.1/jimfs-1.1.pom”。从服务器收到状态码 403:Forbidden
- python - 如何使用 Python 正确编辑 PDF 文件?
- python - list 的列表理解作为 any 函数的输入的原因是什么?
- kdb - 基于 vars 的值构建的解析树
- python - python - 如何使用Python中的字典找到值总和等于或大于k的键的可能组合?
- javascript - 将对象与对象解构和旋转运算符相结合
- php - 在 Directus 中直接访问外部 PHP 脚本的数据
- javascript - NextJS 与 url 名称不同的页面名称