Binding Sample

This entry is the translation of 18 Dec. entry of JavaFX Advent Calendar.

The previous entry was Refinement for existing application GUI by JavaFX (halfway...) by @rewtheblow.

The next entry was JavaFX Utilities by @yumix_h.


I'm serializing JavaFX article in Japanese web magazine ITpro. I picked up property and binding on the article of January.

For the article, I made some samples. However, I didn't use all samples because of too much pages.

MOTTAINAI!! (What a waste!!)

So, I'll show the sample here.

The sample is connected balls.

You can drag the balls, and the connection follows up the dragged ball like rubber band. To connect the balls and the connection, edge points of the connection are bound to the center of balls.

At first, I'll explain how to drag the balls.

When starting dragging, MouseEvent is occurred, and the application stores difference between the center location of the ball and the location of mouse cursor. The application update the center location of the ball from the present mouse cursor and the stored difference, while dragging the ball.

class Ball extends Circle {
    private double dragBaseX;
    private double dragBaseY;
 
    public Ball(double centerX, double centerY, double radius) {
        super(centerX, centerY, radius);
 
        setOnMousePressed(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                // store the difference between mouse cursor and the center of the ball.
                dragBaseX = event.getSceneX() - getCenterX();
                dragBaseY = event.getSceneY() - getCenterY();
            }
        });
 
        setOnMouseDragged(new EventHandler<MouseEvent>() {
            @Override
            public void handle(MouseEvent event) {
                // update the center of the ball from the present mouse cursor
                // and the stored difference.
                setCenterX(event.getSceneX() - dragBaseX);
                setCenterY(event.getSceneY() - dragBaseY);
            }
        });
    }
} 

Next is the connection. The only thing to do is that the edge points of the connection bound to the center of the balls.

class Connection extends Line {
    public Connection(Ball startBall, Ball endBall) {
        // bind the edge points to the center of the balls
        startXProperty().bind(startBall.centerXProperty());
        startYProperty().bind(startBall.centerYProperty());        
        endXProperty().bind(endBall.centerXProperty());
        endYProperty().bind(endBall.centerYProperty());        
    }
}

That's all! It is easy, isn't it?