Javafx 简明教程
JavaFX - TextField
text field 是一个图形用户界面组件,用于接受用户的文本形式输入。它是系统和用户之间最简单的交互方式。我们可以在表单或对话框窗口中找到文本字段,如下图所示:
The text field is a graphical user interface component used to accept user input in the form of text. It is the most easiest way of interaction between system and user. We can find a textfield inside a form or dialog window as shown in the below figure −
TextField in JavaFX
在 JavaFX 中, TextField 类表示文本字段,它是名为 javafx.scene.control 的包的一部分。使用此类,我们可以从用户那里接受输入并将其读入我们的应用程序。此类继承了 TextInputControl ,它是所有文本控件类的基类。要创建文本字段,请使用以下任一构造函数实例化 TextField 类:
In JavaFX, the TextField class represents the text field which is a part of the package named javafx.scene.control. Using this we can accept input from the user and read it to our application. This class inherits the TextInputControl which is the base class of all the text controls class. To create a text field, instantiate the TextField class using any of the below constructors −
-
TextField() − This constructor will create an empty textfield.
-
TextField(String str) − It is the parameterized constructor which constructs a textfield with the specified text.
请注意,在最新版本的 JavaFX 中,TextField 类仅接受单行。
Note that in the latest versions of JavaFX, the TextField class accepts only a single line.
Example
以下 JavaFX 程序中,我们将文本创建为超链接。将此代码保存在名 _ JavafxTextfield.java _ 的文件中。
In the following JavaFX program, we will create a hyperlink as a text. Save this code in a file with the name JavafxTextfield.java.
import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class JavafxTextfield extends Application {
public void start(Stage stage) {
//Creating nodes
TextField textField1 = new TextField("Enter your name");
TextField textField2 = new TextField("Enter your e-mail");
//Creating labels
Label label1 = new Label("Name: ");
Label label2 = new Label("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);
//Setting the stage
Scene scene = new Scene(box, 595, 150, Color.BEIGE);
stage.setTitle("Text Field Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}
要从命令提示符编译并执行已保存的 Java 文件,请使用以下命令−
To compile and execute the saved Java file from the command prompt, use the following commands −
javac --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTextfield.java
java --module-path %PATH_TO_FX% --add-modules javafx.controls JavafxTextfield
执行时,以上程序将生成以下输出。
When we execute, the above program will generate the following output.