Search code examples
javafxdrawing

JavaFX Drawing Shapes via Mouse


Is there any easy way to draw a some shape by moving mouse?

To be more specific, I'm doing a screenshot program, so I want to select display the area somehow. I see it like holding mouse key on point A and moving it to point B in realtime, drawing the rectangle between point A and current point.

Sorry for bad language, English is not my native.


Solution

  • I am using a Scene object called scene in this case. This or something like it should probably do what you want it, perhaps you have to switch between dragBox.setTranslate and dragBox.setWidth / .setHeight in the cases where you're dragging up or left instead of down and right.

    Rectangle dragBox = new Rectangle(0, 0, 0, 0);
    dragBox.setVisible(false);
    scene.addEventFilter(MouseEvent.ANY, new EventHandler<MouseEvent>() {
        @Override
        public void handle(MouseEvent mouseEvent) {
            if(mouseEvent.getEventType() == MouseEvent.MOUSE_CLICKED){
                dragBox.setVisible(true);
                dragBox.setTranslateX(mouseEvent.getX());
                dragBox.setTranslateY(mouseEvent.getY());
            }
            if(mouseEvent.getEventType() == MouseEvent.MOUSE_MOVED && dragBox.isVisible()){
                dragBox.setWidth(mouseEvent.getX() - dragBox.getTranslateX());
                dragBox.setHeight(mouseEvent.getY() - dragBox.getTranslateY());
            }
            if(mouseEvent.getEventType() == MouseEvent.MOUSE_RELEASED)
                dragBox.setVisible(false);
        }
    });
    

    You also have to make sure to add the dragBox to the Pane that is being showed in the scene, or else the dragBox won't be visible at all.