从文本字段 java fxml 获取文本

getting text from textfield java fxml

这是我的 fxml 代码和 Java 控制器文件代码。我正在尝试使用 "String s = tf.getText().toString();" 从句柄事件中的 TEXTFIELD tf 获取文本,但它没有被执行。

<?xml version="1.0" encoding="UTF-8"?>

<?import javafx.geometry.*?>
<?import javafx.scene.control.*?>
<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane fx:id = "aPane" prefHeight="268.0" prefWidth="379.0" xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/8" fx:controller="sample.searchController">
  <children>
  <VBox layoutX="20.0" layoutY="36.0" prefHeight="232.0" prefWidth="333.0">
     <children>
        <HBox prefHeight="36.0" prefWidth="333.0">
           <children>
              <Label fx:id= "kw" text="Key Word : ">
                 <padding>
                    <Insets right="10.0" />
                 </padding>
              </Label>
              <TextField fx:id="tf" prefHeight="25.0" prefWidth="120.0" />
              <Button fx:id="srch" mnemonicParsing="false" onAction="#handle" text="Search" >
                 <HBox.margin>
                    <Insets left="10.0" />
                 </HBox.margin>
              </Button>
           </children>
           <padding>
              <Insets left="6.0" top="6.0" />
           </padding>
           <VBox.margin>
              <Insets />
           </VBox.margin>
           <opaqueInsets>
              <Insets />
           </opaqueInsets>
        </HBox>
        <TextArea fx:id="ta" prefHeight="174.0" prefWidth="282.0" />
     </children>
  </VBox>
  </children>
  </AnchorPane>

JAVA 控制器代码:

public class searchController implements Initializable,EventHandler<ActionEvent> {

  AnchorPane aPane = new AnchorPane();
  Label kw = new Label();
  public TextField tf;
  Button srch = new Button();
  TextArea ta = new TextArea();
  //Text t;
  String s = "priyam";

  @Override
  public void initialize(URL location, ResourceBundle resources) {
    // TODO Auto-generated method stub
    tf = new TextField();
  }

  @Override
  public void handle(ActionEvent arg0) {
    // TODO Auto-generated method stub
    s=tf.getText().toString();
    System.out.println(s);
  }
}

问题是你的初始化方法

public void initialize(URL location, ResourceBundle resources) {
    tf = new TextField();
}

在此方法中,您将 tf 设置为一个新的文本字段。这是一个问题,因为当构建 fxml 文档时,文档构建器将自动使用它构建的文本字段填充该字段。但是随后您的初始化方法会用空白方法覆盖它。因此,当您使用 tf.getText() 时,您没有从 UI 中的文本中获取文本,而是从您自己创建的空白文本中获取文本。如果你简单地注释掉 tf = new TextField(); 它工作正常。

方法initialize()实际上覆盖了tf的值。它用新对象初始化您的 TextField 对象 tf

@Override
public void initialize(URL location, ResourceBundle resources) {
  // TODO Auto-generated method stub
  tf = new TextField();
}