简体   繁体   English

如何在 JavaFX Scene Builder 文本字段中获取用户输入?

[英]How to get user input in JavaFX Scene Builder Text field?

I'm new with JavaFX and made a Textfield in the Scene Builder.我是 JavaFX 的新手,并在 Scene Builder 中创建了一个文本字段。 But I don't find a tutorial where someone explains how to get the input from the Textfield.但是我没有找到有人解释如何从 Textfield 获取输入的教程。 My code I called my Textfield Texfield(fx:id) and left the On Action empty can you tell me what I have to fill in those two boxes and than in my code?我的代码我调用了我的 Textfield Texfield(fx:id) 并将 On Action 留空,你能告诉我我必须在这两个框中填写什么而不是在我的代码中填写什么吗?

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception {
        Parent root = FXMLLoader.load(getClass().getResource("sample.fxml"));
        primaryStage.setTitle("Hello World");
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}



package sample;

import com.sun.javafx.scene.control.IntegerField;
import javafx.fxml.FXML;

import java.awt.*;
import java.awt.event.ActionEvent;

public class Controller {

}



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

<?import javafx.scene.control.Label?>
<?import javafx.scene.control.TextField?>
<?import javafx.scene.layout.AnchorPane?>
<?import javafx.scene.text.Font?>

<AnchorPane maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" xmlns="http://javafx.com/javafx/11.0.1" xmlns:fx="http://javafx.com/fxml/1">
   <children>
      <Label layoutX="72.0" prefHeight="20.0" prefWidth="457.0" text="GUESSING GAME">
         <font>
            <Font name="Arial Black" size="48.0" />
         </font>
      </Label>
      <Label layoutX="72.0" layoutY="187.0" text="Your guess:">
         <font>
            <Font name="Arial" size="22.0" />
         </font>
      </Label>
      <Label layoutX="395.0" layoutY="187.0" text="Attempts:">
         <font>
            <Font name="Arial" size="22.0" />
         </font>
      </Label>
      <TextField fx:id="Textfield" layoutX="197.0" layoutY="188.0" prefHeight="25.0" prefWidth="66.0" />
      <Label layoutX="496.0" layoutY="188.0" text="0">
         <font>
            <Font name="Arial" size="22.0" />
         </font>
      </Label>
   </children>
</AnchorPane>

you need to add an id to the element in your fxml and then link it in the controller using @FXML the variable name must be the same name you set as the id.您需要向fxml的元素添加一个 id,然后使用@FXML将其链接到控制器中,变量名称必须与您设置的 id 名称相同。

And then you can access the text field or any UI element然后您可以访问文本字段或任何 UI 元素

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM