JavaFX TextField单行文本

Text Field 基本上用于以文本的形式获取用户的输入。javafx.scene.control.TextField表示 TextField。它提供了各种方法来处理 JavaFX 中的文本字段。TextField 可以通过实例化 TextField 类来创建。

让我们看一个示例,其中向用户显示两个文本框并提示填写其用户 ID 和密码。

1 TextField的例子1

package com.yiidian;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TextFieldTest extends Application {

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

    @Override
    public void start(Stage primaryStage) throws Exception {
        Label user_id=new Label("User ID");
        Label password = new Label("Password");
        TextField tf1=new TextField();
        TextField tf2=new TextField();
        Button b = new Button("Submit");
        GridPane root = new GridPane();
        root.addRow(0, user_id, tf1);
        root.addRow(1, password, tf2);
        root.addRow(2, b);
        Scene scene=new Scene(root,800,200);
        primaryStage.setScene(scene);
        primaryStage.setTitle("一点教程网:Text Field Example");
        primaryStage.show();
    }
}  

输出结果为:

2 TextField的例子2:获取文本字段数据

TextField 类提供了一个实例方法getText()来检索文本字段数据。它返回 String 对象,该对象可用于将用户详细信息保存在数据库中。

package com.yiidian;

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.GridPane;
import javafx.stage.Stage;

public class TextFieldExample extends Application {  
    
    public static void main(String[] args) {  
    launch(args);     
    }  
      
    @Override  
    public void start(Stage primaryStage) throws Exception {  
        Label user_id=new Label("User ID");  
        Label password = new Label("Password");  
        TextField tf1=new TextField();  
        TextField tf2=new TextField();  
        Button b = new Button("Submit");  
        b.setOnAction(e->System.out.println("You entered: User_ID: "+tf1.getText()+""+"Password: "+tf2.getText()));  
        GridPane root = new GridPane();  
        root.addRow(0, user_id, tf1);  
        root.addRow(1, password, tf2);  
        root.addRow(2, b);  
        Scene scene=new Scene(root,300,200);  
        primaryStage.setScene(scene);  
        primaryStage.setTitle("一点教程网:Text Field Example");  
        primaryStage.show();  
    }  
}  

输出结果为:

热门文章

优秀文章