Highlight Gridpane Cell on Mouseover JavaFX

1120
February 17, 2017, at 07:08 AM

Okay so as said above I have gridpane in my javafx application and im trying to get it so that when I mouse over an individual cell the cell that the mouse is over will change color to a yellow (think excell kinda thing). Ive got no idea how to do this and then reset it after the mouse leaves the cell.

  officeHoursGridPane.setOnMouseEntered((MouseEvent t) -> {
        officeHoursGridPane.setStyle("-fx-background- color:#FFFF00;");
  });
  officeHoursGridPane.setOnMouseEntered((MouseEvent t) -> {
       officeHoursGridPane.setStyle("-fx-background-color:#dae7f3;");
  });

This is how I have it right now but it just changes the one color at mouse over and then stays that color. The entire table also changes not each cell. Anyone help?

Answer 1

If you set a style class on the grid pane:

officeHoursGridPane.getStyleClass().add("office-hours-pane");

then you can use CSS to apply styles to the immediate children of the grid pane, and use the built-in hover pseudoclass to only apply them when the node is hovered. Add the following to an external CSS file:

.office-hours-pane > *:hover {
    -fx-background-color: #FFFF00;
}

If you prefer to use listeners (which is much trickier, and not good practice as you should really separate the style into a separate entity, such as CSS) then you would set onMouseEntered and onMouseExited listeners on each of the child nodes of the grid pane (not on the grid pane itself).

READ ALSO
Maven build failure from missing tycho dependency?

Maven build failure from missing tycho dependency?

I'm attempting to build two Maven projects from EclipseOne project constitutes a set of dependencies and libraries to be used for the other project which contains all of my source code

322
Versioned java applications

Versioned java applications

I need to solve a following issue

334
What is an X and Y offset, and why do I need it?

What is an X and Y offset, and why do I need it?

I was looking through some of the source code from a really cool open-source project that was started by Markus Persson called Minicraft, and I saw this in the Screenjava file:

347