笔记记录

编写人:老王
时间:2023-04-10
地点:广州


HBox水平布局

Hbox就是水平布局,例子如下:

  1. package com.example.demo2;
  2. import javafx.application.Application;
  3. import javafx.scene.Scene;
  4. import javafx.scene.control.Button;
  5. import javafx.scene.layout.AnchorPane;
  6. import javafx.scene.layout.HBox;
  7. import javafx.stage.Stage;
  8. public class Main2 extends Application {
  9. public static void main(String[] args) {
  10. launch(args);
  11. }
  12. @Override
  13. public void start(Stage stage) {
  14. stage.setTitle("这是JavaFX的HBox布局类");
  15. stage.setWidth(800);
  16. stage.setHeight(500);
  17. Button button1 = new Button("我是按钮1");
  18. Button button2 = new Button("我是按钮2");
  19. Button button3 = new Button("我是按钮3");
  20. AnchorPane ap = new AnchorPane();
  21. HBox box = new HBox();
  22. box.setPrefHeight(250);
  23. box.setPrefWidth(400);
  24. //给个黄色,便于区分
  25. box.setStyle("-fx-background-color: #ffd700;");
  26. ap.getChildren().add(box);
  27. box.getChildren().addAll(button1,button2,button3);
  28. Scene scene = new Scene(ap);
  29. stage.setScene(scene);
  30. stage.show();
  31. }
  32. }

图片.png
可以看到上图中的按钮依次排列,和以往不同。以前的按钮都是挤在一起,堆叠在一起,哪个最后添加就在最上面。但是用了HBox水平布局之后,按钮就自动的依次排列了。

VBox就是竖着排的,HBox是横着排的。举个例子(只需要把上面的代码改成VBox就行):

  1. package com.example.demo2;
  2. import javafx.application.Application;
  3. import javafx.scene.Scene;
  4. import javafx.scene.control.Button;
  5. import javafx.scene.layout.AnchorPane;
  6. import javafx.scene.layout.HBox;
  7. import javafx.stage.Stage;
  8. public class Main2 extends Application {
  9. public static void main(String[] args) {
  10. launch(args);
  11. }
  12. @Override
  13. public void start(Stage stage) {
  14. stage.setTitle("这是JavaFX的HBox布局类");
  15. stage.setWidth(800);
  16. stage.setHeight(500);
  17. Button button1 = new Button("我是按钮1");
  18. Button button2 = new Button("我是按钮2");
  19. Button button3 = new Button("我是按钮3");
  20. AnchorPane ap = new AnchorPane();
  21. VBox box = new VBox();
  22. box.setPrefHeight(250);
  23. box.setPrefWidth(400);
  24. //给个黄色,便于区分
  25. box.setStyle("-fx-background-color: #ffd700;");
  26. ap.getChildren().add(box);
  27. box.getChildren().addAll(button1,button2,button3);
  28. Scene scene = new Scene(ap);
  29. stage.setScene(scene);
  30. stage.show();
  31. }
  32. }

图片.png如何设置布局内的各种组件的间隔呢?
就要用到以下的方法:

  1. //各组件之间的间隔
  2. box.setSpacing(10);
  3. //组件的内边距
  4. box.setPadding(new Insets(10));
  5. //组件的外边距
  6. box.setMargin(button1,new Insets(20));
  7. //组件的对其方式,向下对齐
  8. box.setAlignment(Pos.BOTTOM_CENTER);

图片.png图片.png
对齐方式有很多种,如下:
图片.png
任选一个举例:
图片.png