javafxfxmlonhover

set effect for imageview in javafx


I have created a frame with some pictures in it. I would like to add a glow effect to the button's in my scence, such that the button's foreground gets brighter on 'mouse over'.

Here is my FXML document:

public class FrameController implements Initializable {
@FXML
private GridPane album;
ImageView im;

/**
 * Initializes the controller class.
 */
@Override
public void initialize(URL url, ResourceBundle rb) {
    // TODO
}    

@FXML
private void mouseEntered(MouseEvent event) {
    System.out.println(event.getSource());
    im = (ImageView) event.getSource();
    Glow selectGlow = new Glow(1.7f);
    im.setOnMouseEntered(new EventHandler<MouseEvent>() {
    
    @Override
    public void handle(MouseEvent event) {
    im.setEffect(selectGlow);
    }
    });
}

}

but i have two problem:

1)It is very slow and sometimes it seems that mouse handler is not called when i am on a picture because effect does not change

2)I do not know which effect should i use in order to make picture darker when mouse enters pictures area


Solution

  • The performance depends on the effect. If you really only want to change the brightness, you could e. g. use ColorAdjust like this:

    public class ImageTest extends Application {
    
        public static void main(String[] args) {
            launch(args);
        }
    
        @Override
        public void start(Stage primaryStage) {
    
            primaryStage.setTitle("Hello World!");
    
            Group root = new Group();
    
            Image image = new Image("http://upload.wikimedia.org/wikipedia/commons/thumb/4/41/Siberischer_tiger_de_edit02.jpg/320px-Siberischer_tiger_de_edit02.jpg");
    
    
            GridPane gridPane = new GridPane();
    
            gridPane.add(createImageView( image), 0,0);
            gridPane.add(createImageView( image), 1,0);
            gridPane.add(createImageView( image), 0,1);
            gridPane.add(createImageView( image), 1,1);
    
    
            root.getChildren().add( gridPane);
    
            primaryStage.setScene(new Scene(root, 800, 600));
            primaryStage.show();
        }
    
        private ImageView createImageView( Image image) {
    
            ImageView imageView = new ImageView(image);
    
            ColorAdjust colorAdjust = new ColorAdjust();
            colorAdjust.setBrightness(-0.5);
    
            imageView.addEventFilter(MouseEvent.MOUSE_ENTERED, e -> {
    
                imageView.setEffect(colorAdjust);
    
            });
            imageView.addEventFilter(MouseEvent.MOUSE_EXITED, e -> {
                imageView.setEffect(null);
            });
    
            return imageView;
        }
    }
    

    enter image description here