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

JavaFX Layout Panes HBox(布局窗格水平盒子)

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

如果我们在应用程序的布局中使用HBox,则所有节点都设置在一个水平行中。

javafx.scene.layout名为HBox的类表示HBox窗格。该类包含五个属性,即 -

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

除此之外,这个类还提供了几种方法,它们是 -

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

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

将此代码保存在名为HBoxExample.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.HBox;

public class HBoxExample 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 HBox class
HBox hbox = new HBox();

//Setting the space between the nodes of a HBox pane
hbox.setSpacing(10);

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

//retrieving the observable list of the HBox
ObservableList list = hbox.getChildren();

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

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

//Setting title to the Stage
stage.setTitle("Hbox 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 HBoxExample.java 
java HBoxExample.java

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

HBox中