0

I want to know if there is a way to set the hover style of a JavaFX ManuItem without add a stylesheet.

for Node I normally use: this.setOnMouseEntered(e -> this.setStyle(initialStateCss + hoverStateCss));and this.setOnMouseExited(e -> this.setStyle(initialStateCss));

But for MenuItem this events are not available. Someone have an idea of how to do it?

Thanks in advance!

Ikaro
  • 165
  • 1
  • 12
  • if you insist on not using stylesheets (concurring with 0009laH: you should _do_ use them :) - you need access to the node representing the MenuItem: afair, that can be done by using its Styleable api (after the skin has been attached, and maybe after it was showing at least once, forgot the details) – kleopatra Nov 27 '20 at 13:51

1 Answers1

0

I suggest you to use CSS stylesheets then use the .menu-item:focused selector event. In your CSS file, the markup would look like this:

.menu .menu-item:focused {
    -fx-background-color: #FFF6;
    -fx-background-radius: 5.0;
    -fx-font-weight: bold;
}

I would recommend you to use as little Java style as possible and use CSS stylesheets instead. It would enhance your code as it will be more maintainable.

For more details, this SO request gives useful information about MenuItem's CSS style.

0009laH
  • 1,960
  • 13
  • 27
  • Thanks for the answer. I'm doing it in that way right now. But I'm trying to build something like Material for reactjs. With small isolated components that depend as less as possible on external classes. I'll end up using stylsheets, but for this particular case I'd like to test it the other way. – Ikaro Nov 27 '20 at 13:33
  • really `:focused`? I would have expected `:hover` – kleopatra Nov 27 '20 at 13:52
  • @kleopatra I've tried that selector event but it has no effect; I think it doesn't exist – 0009laH Nov 27 '20 at 13:55
  • @Ikaro I've searched on the internet but I cannot find the exact solution to your problem. – 0009laH Nov 27 '20 at 13:56
  • Having just tried it, the `:hover` pseudo-class definitely exists for `.menu-item`. I expected that to be the case for all `Node`s seeing as how said pseudo-class is linked to the `Node#hover` property (the visuals of `MenuItem` are implemented with `Node`s, regardless of the fact that `MenuItem` is not itself a `Node`). That being said, it appears simply by having the mouse enter the menu item it focuses the menu item, which is probably why `:focused` works here ( @kleopatra ). – Slaw Nov 27 '20 at 21:21