如何在JavaFX Scene Builder中获取TextField的用户输入?
Hey there! Let's walk through how to get user input from your TextField in JavaFX step by step, fixing up your current code along the way.
1. Fix the fx:id Naming & Link to Controller
First off, let's adjust your TextField's fx:id to follow Java's camelCase convention (lowercase first letter). In Scene Builder, select your TextField, go to the "Code" panel on the right, and change the fx:id from Textfield to textField. This keeps things consistent with standard practices and avoids potential bugs.
Next, you need to link your FXML file to your Controller class. Open your sample.fxml and add the fx:controller attribute to the root AnchorPane tag, pointing to your sample.Controller class.
2. Configure the "On Action" in Scene Builder
Still in Scene Builder with the TextField selected, look for the "On Action" field in the "Code" panel. Type in handleGuessInput — this will be the name of the method we'll write in the Controller to handle the input when the user presses Enter or triggers the field's action.
3. Update Your Controller Class
Your current Controller has some incorrect imports and missing code. Let's fix that:
- Remove the unnecessary imports for
com.sun.javafx.scene.control.IntegerFieldandjava.awt.*/java.awt.event.ActionEvent(we need JavaFX'sActionEvent, not AWT's). - Add
@FXMLannotations to link FXML elements to variables in the Controller. - Write the
handleGuessInputmethod to fetch and process the user's input.
Here's the updated Controller code:
package sample; import javafx.fxml.FXML; import javafx.scene.control.TextField; import javafx.scene.control.Label; import javafx.event.ActionEvent; public class Controller { // Link to the TextField in FXML — variable name must match fx:id exactly @FXML private TextField textField; // Link to the Attempts label so we can update it later @FXML private Label attemptsLabel; private int attemptCount = 0; // This method is triggered by the TextField's On Action event @FXML private void handleGuessInput(ActionEvent event) { // Get the text from the TextField, trim whitespace to avoid empty inputs String userInput = textField.getText().trim(); if (!userInput.isEmpty()) { attemptCount++; attemptsLabel.setText(String.valueOf(attemptCount)); // Convert input to integer (since this is a guessing game) try { int userGuess = Integer.parseInt(userInput); System.out.println("User guessed: " + userGuess); // Add your game logic here (e.g., check if guess is correct) } catch (NumberFormatException e) { System.out.println("Oops! Please enter a valid number."); } // Clear the TextField for the next guess textField.clear(); } } }
4. Updated FXML File
Here's your modified sample.fxml with all the fixes:
<?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" fx:controller="sample.Controller"> <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" onAction="#handleGuessInput" /> <Label fx:id="attemptsLabel" layoutX="496.0" layoutY="188.0" text="0"> <font> <Font name="Arial" size="22.0" /> </font> </Label> </children> </AnchorPane>
Key Takeaways
- The
fx:idin FXML must exactly match the variable name annotated with@FXMLin the Controller. - The "On Action" method must take a
javafx.event.ActionEventparameter and be annotated with@FXML. - Always remember to link your FXML to the Controller using the
fx:controllerattribute on the root element. - When processing user input, handle edge cases like empty text or invalid number formats to avoid crashes.
内容的提问来源于stack exchange,提问作者Mindmax

