JavaFX(带有FXML)为按钮添加Action事件 [英] JavaFX (with FXML) Adding Action events for buttons
问题描述
我有一个带有Scene-Builder的FXML文件,带有所需的fx:ids和以下控制器:
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");
}
}
现在,我想向按钮添加动作事件.我怎么做?我找不到包含FXML文件的东西.
Now I want to add action events to the buttons. How do I do that? I cannot really find something that involves FXML-Files.
推荐答案
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!");
}
}
然后FXML文件可能类似于:
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>
您可以使用Scene Builder进行配置,方法是单击所需的节点,然后转到右侧的代码"面板.将有一个用于各种onXXX
属性的字段,以及一个用于fx:id
的字段.
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
.
这篇关于JavaFX(带有FXML)为按钮添加Action事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!