如何使用 JavaFX 建立一個 HBox?


建立完所需的應用程式節點後,你可以使用佈局來排列它們。其中一個佈局是計算出在給定空間中物件位置的過程。JavaFX 在 javafx.scene.layout 包中提供了各種佈局。

hbox

在此佈局中,節點被佈置在單一的水平行中。你可以在應用程式中透過例項化 javafx.scene.layout.HBox 類來建立一個 hbox。你可以使用 setPadding() 方法來設定 hbox 周圍的內邊距。

要將節點新增到此窗格,你可以將它們作為建構函式的引數傳遞,也可以將它們新增到如下所示的窗格的可觀察列表中:

getChildren().addAll();

示例

import javafx.application.Application;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class HBoxExample extends Application {
   public void start(Stage stage) {
      //Creating labels
      Label label1 = new Label("User Name: ");
      Label label2 = new Label("Password: ");
      //Creating text and password fields
      TextField textField = new TextField();
      PasswordField pwdField = new PasswordField();
      //Adding labels for nodes
      HBox box = new HBox(5);
      box.setPadding(new Insets(50, 5 , 5, 50));
      box.getChildren().addAll(label1, textField, label2, pwdField);
      //Setting the stage
      Scene scene = new Scene(box, 595, 150, Color.BEIGE);
      stage.setTitle("HBox Example");
      stage.setScene(scene);
      stage.show();
   }
   public static void main(String args[]){
      launch(args);
   }
}

輸出

更新於:19-5-2020

265 瀏覽量

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告
© . All rights reserved.