有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

从textfield java fxml获取文本

这是我的fxml代码和Java控制器文件代码。我试图使用“String s=tf.getText().toString();”从句柄事件中的文本字段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);
  }
}

共 (1) 个答案

  1. # 1 楼答案

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

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