如何使用 JavaFX 创建锚窗格?
一旦你为应用程序创建所有必需的节点,就可以使用布局对其进行排列。其中布局是计算给定空间中的对象位置的过程。JavaFX 在 javafx.scene.layout 包中提供了各种布局。
锚窗格
在此布局中,节点被附加/锚定到窗格边缘的点(偏移量)。
可以通过实例化 javafx.scene.layout.AnchorPane 类来创建锚窗格。有四个锚约束来指定从窗格边缘到节点边缘的距离,即 topAnchor、leftAnchor、bottomAnchor、rightAnchor。
可以使用 setPrefSize() 方法设置锚窗格的大小。要向此窗格添加节点,可以将它们作为构造函数的参数传递,或将它们添加到窗格的可观察列表中,如下所示 −
getChildren().addAll();
示例
import javafx.application.Application;
import javafx.collections.ObservableList;
import javafx.geometry.HPos;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.Separator;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;
import javafx.scene.text.FontPosture;
import javafx.scene.text.FontWeight;
import javafx.stage.Stage;
public class AnchorPaneExample extends Application {
public void start(Stage stage) {
//Creating the check boxes
CheckBox checkBox1 = new CheckBox("Hindi");
CheckBox checkBox2 = new CheckBox("Gujarathi");
CheckBox checkBox3 = new CheckBox("Punjabi");
CheckBox checkBox4 = new CheckBox("Telugu");
CheckBox checkBox5 = new CheckBox("Tamil");
CheckBox checkBox6= new CheckBox("Malayalam");
//Creating a label
Label label = new Label("Select known languages:");
Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12);
label.setFont(font);
//Creating a separator
Separator sep = new Separator();
sep.setMaxWidth(80);
sep.setHalignment(HPos.CENTER);
//Adding the check boxes and separator to the pane
VBox vBox = new VBox(5);
vBox.setPadding(new Insets(5, 5, 5, 210));
vBox.getChildren().addAll(label, checkBox1, checkBox2, checkBox3, checkBox4, checkBox5, checkBox6);
//Adding the separator after the 3rd check box
vBox.getChildren().add(4, sep);
//Creating the buttons
Button next = new Button("Next");
Button previous = new Button("previous");
//Creating an Anchor Pane
AnchorPane anchorPane = new AnchorPane();
//Setting the anchor to the next and previous buttons
AnchorPane.setRightAnchor(next, 5.0);
AnchorPane.setLeftAnchor(previous, 5.0);
//Retrieving the observable list of the Anchor Pane
ObservableList list = anchorPane.getChildren();
//Adding vBox and buttons to the anchor pane
list.addAll(vBox, next, previous);
//Setting the stage
Scene scene = new Scene(anchorPane, 595, 200, Color.BEIGE);
stage.setTitle("Anchor Pane Example");
stage.setScene(scene);
stage.show();
}
public static void main(String args[]){
launch(args);
}
}输出

广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP