[英]Accessing TextField from a separate class
I am currently attempting to make a very basic class MyController, which takes the content of a TextField in an FXML created window and, when the button in the window is pressed, inserts its contents into a string which is printed to the terminal. 我目前正在尝试制作一个非常基本的类MyController,该类在FXML创建的窗口中获取TextField的内容,并在按下窗口中的按钮时将其内容插入到打印到终端的字符串中。 Once this is done, it changes the contents of the TextField to "done!".
完成此操作后,它将TextField的内容更改为“完成!”。
The code for the FXML file is as follows: FXML文件的代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.control.*?>
<?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" fx:controller="practice1.MyController">
<children>
<Button fx:id="HelloWorld" layoutX="30.0" layoutY="34.0" mnemonicParsing="false" onAction="#sayHello" text="Hello World" />
<TextField fx:id="message" layoutX="30.0" layoutY="77.0" />
</children>
</AnchorPane>
The only information of interest in this is that the TextField has the fx:id "message". 对此感兴趣的唯一信息是TextField具有fx:id“ message”。
The code for my class MyController
is as follows: 我的类
MyController
的代码如下:
package practice1;
import javafx.event.*;
import javafx.scene.control.TextField;
public class MyController {
private TextField message;
public void sayHello(ActionEvent event) {
System.out.print("You said \"");
System.out.print(message.getText());
System.out.println("\"");
message.setText("done!");
}
}
Your TextField in the controller is private so the loader cannot access it. 控制器中的TextField是私有的,因此加载程序无法访问它。 Using javafx.fxml.FXML annotation as follows you can mark it as accessible to FXML.
如下使用javafx.fxml.FXML批注,可以将其标记为FXML可访问。
@FXML
private TextField message;
You could alternatively just declare it as public. 您也可以将其声明为公共。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.