如何使用 JavaFX 建立文字欄位?
文字欄位用於接受和顯示文字。在最新版本的 JavaFX 中,它只接受單行輸入。在 JavaFX 中,**javafx.scene.control.TextField** 類表示文字欄位,此類繼承 TextInputControl(所有文字控制元件的基類)類。使用它,你可以接受使用者的輸入,並將其讀取到應用程式中。
要建立一個文字欄位,你需要例項化**TextField** 類,還可以將字串值傳遞給此類的建構函式,該值將作為文字欄位的初始文字。
例如
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 TextFieldExample 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); } }
輸出
廣告