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

问题描述 投票:0回答:1

我是JavaFX的新手,并在Scene Builder中创建了一个Textfield。但是我找不到一个教程,那里没有人解释如何从文本字段获取输入。我的代码称为Textfield Texfield(fx:id),将“执行中的动作”留为空白,您能告诉我在这两个框中必须填写的内容,而不是我的代码吗?

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>
java user-interface javafx input scenebuilder
1个回答
0
投票

您需要在fxml中的元素上添加一个id,然后使用@FXML在控制器中将其链接,变量名称必须与您设置为id的名称相同。

然后您可以访问文本字段或任何UI元素

© www.soinside.com 2019 - 2024. All rights reserved.