JavaFX要实现滚动可以使用ScrollPane,要实现缩放可以通过调用setScaleX和setScaleY、setScaleZ,如果需要实现滚动 + 缩放联动,那么需要一点点小技巧,这里记录一下。
1. 实现滚动
实现JavaFX的滚动很简单,只需要将UI组件放在ScollPane中即可,下面是一个实现的例子:
public class Sample01 extends Application {
@Override
public void start(Stage stage) {
ScrollPane root = new ScrollPane();
StackPane pane = new StackPane();
pane.setPrefWidth(640);
pane.setPrefHeight(480);
Button btn = new Button("米虫2022");
pane.getChildren().add(btn);
root.setContent(pane);
root.setVvalue(0.5);
root.setHvalue(0.5);
stage.setTitle("滚动 + 缩放");
stage.setWidth(320);
stage.setHeight(240);
stage.setScene(new Scene(root));
stage.getIcons().clear();
stage.getIcons().add(new Image("logo.jpg"));
stage.show();
}
}
这里的stage长宽只有320x240,而内容面板的长宽是640x480,是stage的两倍,这样ScollPane就会出现滚动条了,效果如下:
2. 实现缩放
JavaFX缩放可以通过调用UI组件setScaleX和setScaleY、setScaleZ的API来实现,改造一下上面的例子,给按钮添加一个鼠标处理事件,当按住Ctrl单击时缩小,没有按住Ctrl时单击放大:
btn.setOnMouseClicked(event -> {
if (event.isControlDown()) {
pane.setScaleX(pane.getScaleX() - 0.1);
pane.setScaleY(pane.getScaleY() - 0.1);
} else {
pane.setScaleX(pane.getScaleX() + 0.1);
pane.setScaleY(pane.getScaleY() + 0.1);
}
});
效果如下:
3. 滚动 + 缩放
在上面的例子中,可以看到,缩放时滚动条并不会发生变化,要实现JavaFX的滚动 + 缩放效果,需要给ScrollPane中的UI套一个Group,重新改造一下代码:
root.setContent(new Group(pane));
效果如下:
这样,缩放时,滚动就会跟着变化了。
下面是关于Group的API说明:
A Group node contains an ObservableList of children that are rendered in order whenever this node is rendered.
A Group will take on the collective bounds of its children and is not directly resizable.
Any transform, effect, or state applied to a Group will be applied to all children of that group. Such transforms and effects will NOT be included in this Group's layout bounds, however if transforms and effects are set directly on children of this Group, those will be included in this Group's layout bounds.
标签:Group,缩放,JavaFX,pane,滚动,stage
From: https://www.cnblogs.com/michong2022/p/17034636.html