【发布时间】:2018-06-11 05:11:39
【问题描述】:
使用 FXML 创建自定义设计,其中包含两个文件 CustomToggleSwitch.fxml 和 CustomToggleSwitch.java。
CustomToggleSwitch.fxml 有以下代码
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?import javafx.scene.shape.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<fx:root type="Pane" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<Button mnemonicParsing="false" onAction="#click" text="Button" />
</children>
</fx:root>
CustomToggleSwitch.java 有代码
package com.custom;
import java.io.IOException;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.layout.Pane;
public class CustomToggleSwitch extends Pane{
int tick;
public CustomToggleSwitch() {
FXMLLoader loader=new FXMLLoader(getClass().getResource("CustomToggleSwitch.fxml"));
loader.setRoot(this);
loader.setController(this);
try {
loader.load();
} catch (IOException e) {
e.printStackTrace();
}
}
@FXML
public void click(ActionEvent actionEvent){
System.out.println(tick++);
}
}
从这些创建 jar 文件并在应用程序项目中使用此 jar 文件。应用程序有 test.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import com.custom.*?>
<?import com.custom.CustomToggleSwitch?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="- Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/8" xmlns:fx="http://javafx.com/fxml/1">
<children>
<CustomToggleSwitch layoutX="29.0" layoutY="48.0" />
</children>
</AnchorPane>
控制器类(TestController.java)有以下
public class TestController implements Initializable{
@Override
public void initialize(URL arg0, ResourceBundle arg1) {
}
@FXML
public void click(){
System.out.println("Test");
}
}
按钮在 GUI 上成功显示,并且按钮单击也被检测到。按钮在输出控制台上显示 0、1、2、3..等。但是测试没有打印在屏幕上。
如何检测应用程序控制器类中的按钮按下?有人可以帮我解决这个问题。
非常感谢大家。
【问题讨论】:
-
在组件控制器中添加带有 getter 和 setter 的监听器属性。