Search code examples
cssjavafxstylesstylesheet

javafx: change style dynamically on pane


I am trying to change the style of a pane when my mouse goes over it and change it back to normal when my mouse is outside the pane.

I can do something like that

pane.setStyle("");

However I want my css code to be in a css stylesheet and I was wondering if it's possible to create something like togglebutton

.togglebutton{
     -fx-background-color:red;
}

.togglebutton:selected{
     -fx-background-color:green;
}

Thus, each time I select my togglebutton, the style change automatically.

The question is : is it possible to create a parameter to act like the togglebutton. Something like:

css stylesheet

.mypane{
     //do something
}

.mypane:selected{
     // do something else
}

java code

public void mousedragAction(MouseEvent event){
     mypane.isSelected(true);
}

public void mouseexit(MouseEvent event){
     mypane.isSelected(false);
}

Thank you very much for any help, or any other solutions.


Solution

  • The functionality you're looking for is already implemented with the hover pseudoclass. So you can just do

    .myPane {
        /* do something */
    }
    .myPane:hover {
        /* do something else */
    }
    

    In general, though it's not necessary in this case, you can define arbitrary CSS pseudoclasses (which will work like selected and hover). To reproduce the hover functionality, for example, you can do:

    PseudoClass moveOver = PseudoClass.getPseudoClass("mouse-over");
    Pane myPane = new Pane();
    myPane.getStyleClass().add("my-pane");
    myPane.setOnMouseEntered(e -> myPane.pseudoClassStateChanged(mouseOver, true));
    myPane.setOnMouseExited(e -> myPane.pseudoClassStateChanged(mouseOver, false));
    

    and then you can use the following CSS:

    .my-pane {
        -fx-background-color: white ;
    }
    .my-pane:mouse-over {
        -fx-background-color: yellow ;
    }
    

    Note the pseudoclass name in the CSS (:mouse-over) matches the string passed to the getPseudoClass method (PseudoClass.getPseudoClass("mouse-over")), and can be any string that is valid to use as a CSS identifier.