简体   繁体   中英

javafx mouse events in transparent image

JavaFx ImageView doesn't trigger Mouse Events such as press or drag if you click or drag on a transparent pixel, is there anyway to work around this and detect mouse events from transparent areas?

I have this image在此处输入图像描述

that i added into this very simple JavaFX scene在此处输入图像描述

using an ImageView named view and i want to move it with Mouse Drag events so i wrote this code

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class Main extends Application{

    double initMx, initMy,initX, initY;

    @Override
    public void start(Stage ps) throws Exception {
        StackPane pane = new StackPane();
        Image im = new Image("0.png");
        ImageView view = new ImageView(im);
        double fact = im.getWidth() / im.getHeight();

        view.setFitHeight(300);
        view.setFitWidth(300 * fact);

        view.setOnMousePressed(e->{
            initX = view.getTranslateX();
            initY = view.getTranslateY();
            initMx = e.getSceneX();
            initMy = e.getSceneY();
        });

        view.setOnMouseDragged(e->{
            double dx = initMx - e.getSceneX();
            double dy = initMy - e.getSceneY();

            double nx = initX - dx;
            double ny = initY - dy;

            view.setTranslateX(nx);
            view.setTranslateY(ny);

        });

        pane.getChildren().add(view);

        Scene scene = new Scene(pane, 500, 500);

        ps.setScene(scene);
        ps.show();

    }

    public static void main(String[] args) {
        launch(args);
    }
}

this code works fine so far, but if you press or drag somewhere like under his ears ( or anywhere transparent ) nothing will happen how to fix this

The more natural and easiest solution would have been to just set pick on bounds to true.

view.setPickOnBounds(true);

You can do so by setting this image as a graphic in a Button like so

button.setGraphics(new ImageView(im));

Note: You will need to remove style from the button after adding the ImageView by setting the button background with a transparent background color

Try this, if you didn't yet:

   view.setOnMouseDragged(e->{
        double dx = initMx - e.getX();
        double dy = initMy - e.getY();

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