如何在 JavaFX 中檢索文字欄位的內容?
文字欄位接受並顯示文字。在 JavaFX 的最新版本中,它只接受單行文字。在 JavaFX 中,javafx.scene.control.TextField 類表示文字欄位,此類繼承了 javafx.scene.control.TextInputControl (所有文字控制元件的基礎類)類。使用此類可以接受使用者輸入並將其讀取到應用程式中。
要建立一個文字欄位,您需要例項化此類,指向此類的建構函式。它從其超類 TextInputControl. 繼承了一個名為 text 的屬性。此屬性儲存當前文字欄位的內容。您可以使用 getText() 方法檢索此資料。
示例
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;
public class TextFieldGettingData extends Application {
public void start(Stage stage) {
//Creating nodes
TextField textField1 = new TextField();
TextField textField2 = new TextField();
Button button = new Button("Submit");
button.setTranslateX(250);
button.setTranslateY(75);
//Creating labels
Label label1 = new Label("Name: ");
Label label2 = new Label("Email: ");
//Setting the message with read data
Text text = new Text("");
//Setting font to the label
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 10);
text.setFont(font);
text.setTranslateX(15);
text.setTranslateY(125);
text.setFill(Color.BROWN);
text.maxWidth(580);
text.setWrappingWidth(580);
//Displaying the message
button.setOnAction(e -> {
//Retrieving data
String name = textField1.getText();
String email = textField2.getText();
text.setText("Hello "+name+"Welcome to Tutorialspoint. From now, we will
communicate with you at "+email);
});
//Adding labels for nodes
HBox box = new HBox(5);
box.setPadding(new Insets(25, 5 , 5, 50));
box.getChildren().addAll(label1, textField1, label2, textField2);
Group root = new Group(box, button, text);
//Setting the stage
Scene scene = new Scene(root, 595, 150, Color.BEIGE);
stage.setTitle("Text Field Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}輸出

廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP