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

JavaFX Layout FlowPane(布局流面板)

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

如果我们在应用程序中使用流窗格,则所有节点都包含在流中。水平流动窗格将窗格的元素包裹在其高度,而垂直流动窗格将元素包裹在其宽度处。

名为类FlowPane包的javafx.scene.layout代表流动窗格。该类包含7个属性,其中包括 -

  • alignment - 此属性表示“流”窗格内容的对齐方式。您可以使用setter方法setAllignment()设置此属性。
  • columnHalignment - 此属性表示垂直流窗格中节点的水平对齐方式。
  • rowValignment - 此属性表示水平流窗格中节点的垂直对齐方式。
  • Hgap - 此属性是double类型,它表示流窗格的行/列之间的水平间距。
  • Orientation - 此属性表示流窗格的方向。
  • Vgap - 此属性为double类型,表示流窗格的行/列之间的垂直间距。

以下程序是FlowPane布局的示例。在此,我们在水平流动窗格中插入四个按钮。

将此代码保存在名为FlowPaneExample.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.collections.ObservableList; 
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.layout.FlowPane;
import javafx.scene.shape.Sphere;
import javafx.stage.Stage;

public class FlowPaneExample extends Application {
@Override
public void start(Stage stage) {
//Creating button1
Button button1 = new Button("Button1");

//Creating button2
Button button2 = new Button("Button2");

//Creating button3
Button button3 = new Button("Button3");

//Creating button4
Button button4 = new Button("Button4");

//Creating a Flow Pane
FlowPane flowPane = new FlowPane();

//Setting the horizontal gap between the nodes
flowPane.setHgap(25);

//Setting the margin of the pane
flowPane.setMargin(button1, new Insets(20, 0, 20, 20));

//Retrieving the observable list of the flow Pane
ObservableList list = flowPane.getChildren();

//Adding all the nodes to the flow pane
list.addAll(button1, button2, button3, button4);

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

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

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

FlowPane