Search code examples
javafxjavafx-2javafx-8

Changing javafx button color on click?


I know I can set a color by using the pressed pseudo selector:

myButton:pressed{}

Problem is, im trying to do this in code by overriding the css background color from my stylesheet by doing:

myButton.setStyle("fx-background-color: #FFF");

The latter fails do change the color though. Could it be that once ive set my stylesheet that I cant override it? How can I change the button color on click?


Solution

  • I had to do a similar thing(here is simplified, there is just the part of code which change the style to the button) and i did this, i hope it will be helpful to you

    button.setOnAction((ActionEvent e) -> {
        button.getStyleClass().removeAll("addBobOk, focus"); 
        //In this way you're sure you have no styles applied to your object button
        button.getStyleClass().add("addBobOk");
        //then you specify the class you would give to the button
    });
    

    CSS:

    .addBobOk{
            -fx-background-color:#90EE90;
            -fx-background-radius: 5,5,4;
            -fx-background-insets: 0 0 -1 0,0,1;
            -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.4) , 5, 0.0 , 0 , 1 );
            -fx-text-alignment: center;
    }
    .addBobOk:hover{
    
            -fx-background-color:#64EE64;
            -fx-effect: dropshadow( three-pass-box , rgba(0,0,0,0.4) , 5, 0.0 , 0 , 1 );
            -fx-text-alignment: center;
    }
    .busy{
    
            -fx-background-color:#B3B3B3; 
            -fx-text-alignment: center;
    }
    .busy:hover{
    
            -fx-background-color:cdcbcb;                       
            -fx-text-alignment: center;
    }