概述
Anchor意思是锚点布局。可以将创建的根节点改变位置。这里主要是介绍一些方法。
首先设置一个按钮作为根节点:
import javafx.application.Application;
import javafx.scene.control.Button;
import javafx.stage.Stage;
public class AnchorPaneTest extends Application {
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Button button = new Button("Hello,JavaFX!");
}
}
然后不使用AnchorPane,直接将按钮放入场景中:
Scene scene = new Scene(button);
Stage stage = new Stage();
stage.setScene(scene);
stage.setWidth(500);
stage.setHeight(500);
stage.show();
运行结果:
可以看见按钮将场景占满了。当按钮用AnchorPane布局之后:
public void start(Stage primaryStage) throws Exception {
Button button = new Button("Hello,JavaFX!");
AnchorPane pane = new AnchorPane(button);
Scene scene = new Scene(pane);
Stage stage = new Stage();
stage.setScene(scene);
stage.setWidth(500);
stage.setHeight(500);
stage.show();
}
运行结果:
按钮变小了,并且在没有给按钮设置位置的情况下,默认位置为(0,0)。
方法
如果我们为按钮设置了坐标,之后会在相应的坐标显示。用这个方法增加节点时,可以一次增加多个:
Button button = new Button("Hello,JavaFX!");
Button button1 = new Button("Happy!");
AnchorPane pane = new AnchorPane(button,button1);
当然,还有另外的方法,方便随时加节点,add()一次只能加一个,addAll()可以一次增加多个:
pane.getChildren().add(button);
pane.getChildren().addAll(button,button1);
AnchorPane还可以为节点定位,使节点相对于窗口的上下左右的位置不变:
AnchorPane.setTopAnchor(button,100.0);
AnchorPane.setLeftAnchor(button,150.0);
其他两边的方法是类似的,运行结果:
设置之后,无论怎么放大缩小窗口,button相对于窗口的上左的距离是不变的。
既然有set,那么get 也要安排上,就是获取关于设置的相对距离的数值:
System.out.println(AnchorPane.getTopAnchor(button));
结果就是输出设置的100.0。
AnchorPane中有一个方法叫clearConstraints(Node child)作用是清除作用在这个节点上的定位束缚。
AnchorPane.clearConstraints(button);
运行后会发现,这个按钮回到了原来的位置,并且不再有定位的束缚。
总结
如果有时间,看了API,会发现AnchorPane继承了Pane,Region,Parent,Node,Object的好多方法,尤其是Node,压根数不过来。所以像我这样的初学javafx的,建议先看一些超类,不然看这种,继承了很多方法,还不知道其所以然。