简体   繁体   中英

JavaFX pannable GridPane

For my current project, I need a large even grid with a transparent background that one can zoom and pan across. I initially tried to use a ScrollPane with its setPannable(true) , but soon discovered that a scrollpane background will remain opague even when you call setStyle("-fx-background-color: transparent") or setStyle("-fx-background: transparent") . So with that easy option eliminated, I need to make the GridPane in question directly pannable.

I've tried several things already, including trying to bind the mouse position to the GridPane 's Translate property(which quite simply didn't work), and I failed to get the more promising alternative to work properly:

    GridPane gridView = new GridPane();
    int x;
    int y;
    gridView.setOnDragEntered( (event) -> {
        x = event.getX();
        y = event.getY();
    });
    gridView.setOnDragDetected( (event) -> {
        gridView.setTranslateX(X - event.getX());
        gridView.setTranslateY(Y - event.getY());
    });

However, this only makes the map jump up and to the left, rather than to make it slowly pan with the mouse as intended.

Managed to mostly figure it out. The one remaining problem is that the GridPane is rather jittery when it is panned, but it's at an acceptable level for now.

    int x = 0;
    int y = 0;
    gridView.setOnMouseDragged((event) -> {
        if(x != 0){ //prevent from panning before values are initialized
            gridView.setTranslateX( gridView.getTranslateX() + limit(event.getX() - x, 25));
            gridView.setTranslateY( gridView.getTranslateY() + limit(event.getY() - y, 25));
        }
        x = (int)event.getX();
        y = (int)event.getY();
    });

Where the Limit(double num, double limit) method limits the input num to the range [-limit, limit]. Reducing the limit decreases the jitter, but it does so at the expense of decreasing responsiveness as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM