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

JavaFX Layout Stackpane(布局堆栈面板)

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

如果我们使用堆栈窗格,则节点排列在另一个上面,就像在堆栈中一样。首先添加的节点位于堆栈的底部,下一个节点位于堆栈的顶部。

javafx.scene.layout的名为StackPane的类表示StackPane。该类包含一个名为alignment的属性。此属性表示堆栈窗格中节点的对齐方式。

除了这些,这个类还提供了一个名为setMargin()的方法。此方法用于为堆栈窗格中的节点设置边距。

以下程序是StackPane布局的示例。在这里,我们以相同的顺序插入Circle,Sphere和Text。

将此代码保存在名为StackPaneExample.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
55
56
57
58
59
60
61
62
63
64
65
66
67
import javafx.application.Application; 
import javafx.collections.ObservableList;
import javafx.geometry.Insets;

import javafx.scene.Scene;
import javafx.scene.layout.StackPane;
import javafx.scene.paint.Color;
import javafx.scene.shape.Circle;
import javafx.scene.shape.Sphere;

import javafx.scene.text.Font;
import javafx.scene.text.FontWeight;
import javafx.scene.text.Text;
import javafx.stage.Stage;

public class StackPaneExample extends Application {
@Override
public void start(Stage stage) {
//Drawing a Circle
Circle circle = new Circle(300, 135, 100);
circle.setFill(Color.DARKSLATEBLUE);
circle.setStroke(Color.BLACK);

//Drawing Sphere
Sphere sphere = new Sphere(50);

//Creating a text
Text text = new Text("Hello how are you");

//Setting the font of the text
text.setFont(Font.font(null, FontWeight.BOLD, 15));

//Setting the color of the text
text.setFill(Color.CRIMSON);

//setting the position of the text
text.setX(20);
text.setY(50);

//Creating a Stackpane
StackPane stackPane = new StackPane();

//Setting the margin for the circle
stackPane.setMargin(circle, new Insets(50, 50, 50, 50));

//Retrieving the observable list of the Stack Pane
ObservableList list = stackPane.getChildren();

//Adding all the nodes to the pane
list.addAll(circle, sphere, text);

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

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

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

StackPane