i一直在尝试从ScrollPane获取值getVisibleAmount(),该ScrollPane具有子AnchorPane和ScrollBar。在这种情况下,我想从ScrollPane获取ScrollBar子级,以获取getVisibleAmount()函数。仅在ScrollBar组件上具有此功能。
我想将ScrollPane子项(ScrollBar)的getVisibleAmount()分别应用于其他ScrollBar。
NewMain.java
import javafx.application.Application;
import static javafx.application.Application.launch;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Orientation;
import javafx.scene.Group;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollBar;
import javafx.scene.control.ScrollPane;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
public class NewMain extends Application {
final ScrollPane sp = new ScrollPane();
final VBox vb = new VBox();
final ScrollBar sc = new ScrollBar();
final Button bt = new Button("add");
final AnchorPane ap = new AnchorPane();
Label lb = new Label();
@Override
public void start(Stage stage) {
Group root = new Group();
Scene scene = new Scene(root, 300, 300);
scene.setFill(Color.BLACK);
stage.setScene(scene);
stage.setTitle("Scrollbar");
sp.setPrefSize(280, 280);
ap.getChildren().add(vb);
sp.setContent(ap);
root.getChildren().addAll(sp, sc, bt);
bt.setLayoutY(280);
sc.setLayoutX(scene.getWidth() - sc.getWidth() + 8);
sc.setMin(0);
sc.setOrientation(Orientation.VERTICAL);
sc.setPrefHeight(280);
bt.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent t) {
for (int i = 1; i < 11; i++) {
lb = new Label("ok " + i);
lb.setPrefSize(30, 30);
vb.getChildren().add(lb);
}
int a = vb.getChildren().size();
vb.setPrefSize(200, (lb.getPrefHeight() * a));
vb.setMinSize(200, (lb.getPrefHeight() * a));
ap.setPrefSize(200, (lb.getPrefHeight() * a));
sc.setMax(lb.getPrefHeight() * a - 280);
vb.translateYProperty().bind(sc.valueProperty().negate());
//i want change this value same as scrollpane's scrollbar
sc.setVisibleAmount(sc.getMax() * sc.getPrefHeight() / sc.getPrefHeight() / 2);//330, 1300, 2900... 1.5 170
System.out.println(lb.getPrefHeight() * a - 280);
}
});
stage.show();
}
public static void main(String[] args) {
launch(args);
}
}
任何解决方案将不胜感激。谢谢。
这里是一种从ScrollPane
的ScrollBar
中获取可见量的方法:
static double getScrollBarVisibleAmount(ScrollPane scrollPane, Orientation orientation) {
for (Node node : scrollPane.lookupAll(".scroll-bar")) {
if (node instanceof ScrollBar) {
ScrollBar scrollBar = (ScrollBar) node;
if (scrollBar.getOrientation() == orientation) {
return scrollBar.getVisibleAmount();
}
}
}
return -1.0;
}
您可以这样使用它:
double amount = getScrollBarVisibleAmount(myScrollPane, Orientation.VERTICAL);
您需要确切知道何时调用此方法,因为在调用时可能未显示ScrollPane
。如果分配ChangeListener<Number>
,也会更容易跟踪更改:
scrollBar.visibleAmountProperty().addListener((observable, oldValue, newValue) -> System.out.println("New visible amount: " + newValue));