Reputation: 1004
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 ?
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 !
Upvotes: 3
Views: 1826
Reputation: 10650
The more natural and easiest solution would have been to just set pick on bounds to true.
view.setPickOnBounds(true);
Upvotes: 10
Reputation: 600
Try this, if you didn't yet:
view.setOnMouseDragged(e->{
double dx = initMx - e.getX();
double dy = initMy - e.getY();
Upvotes: 0
Reputation: 674
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
Upvotes: 1