多读书多实践,勤思考善领悟

JavaFX Layout Panes VBox(布局窗格竖直盒子)

本文于1661天之前发表,文中内容可能已经过时。

如果我们在应用程序中使用VBox作为布局,则所有节点都设置在一个垂直列中。

javafx.scene.layout的名为VBox的类表示VBox窗格。该类包含五个属性,它们是 -

  • alignment - 此属性表示VBox边界内节点的对齐方式。您可以使用setter方法setAlignment()为此属性设置值。
  • fillHeight - 此属性是布尔类型,并将此设置为true; VBox中可调整大小的节点的大小调整为VBox的高度。您可以使用setter方法setFillHeight()为此属性设置值。
  • spacing - 此属性是double类型,它表示VBox的子节点之间的空间。您可以使用setter方法setSpacing()为此属性设置值。

除此之外,本课程还提供以下方法 -

  • setVgrow() - 设置VBox包含的子项的垂直增长优先级。此方法接受节点和优先级值。
  • setMargin() - 使用此方法,您可以将边距设置为VBox。此方法接受Insets类的节点和对象(矩形区域的4个边的一组内部偏移)

以下程序是VBox布局的示例。在这里,我们插入一个文本字段和两个按钮,播放和停止。这是以10的间距完成的,每个边距都有尺寸 - (10,10,10,10)。

将此代码保存在名为VBoxExample.java的文件中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import javafx.application.Application; 
import javafx.collections.ObservableList;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import javafx.scene.layout.VBox;

public class VBoxExample extends Application {
@Override
public void start(Stage stage) {
//creating a text field
TextField textField = new TextField();

//Creating the play button
Button playButton = new Button("Play");

//Creating the stop button
Button stopButton = new Button("stop");

//Instantiating the VBox class
VBox vBox = new VBox();

//Setting the space between the nodes of a VBox pane
vBox.setSpacing(10);

//Setting the margin to the nodes
vBox.setMargin(textField, new Insets(20, 20, 20, 20));
vBox.setMargin(playButton, new Insets(20, 20, 20, 20));
vBox.setMargin(stopButton, new Insets(20, 20, 20, 20));

//retrieving the observable list of the VBox
ObservableList list = vBox.getChildren();

//Adding all the nodes to the observable list
list.addAll(textField, playButton, stopButton);

//Creating a scene object
Scene scene = new Scene(vBox);

//Setting title to the Stage
stage.setTitle("Vbox Example");

//Adding scene to the stage
stage.setScene(scene);

//Displaying the contents of the stage
stage.show();
}
public static void main(String args[]){
launch(args);
}
}

使用以下命令从命令提示符编译并执行保存的java文件。

1
2
javac VBoxExample.java 
java VBoxExample.java

执行时,上面的程序生成一个JavaFX窗口,如下所示。

垂直框