单击更改 javafx 按钮颜色?

Changing javafx button color on click?

我知道我可以使用按下的伪选择器设置颜色:

myButton:pressed{}

问题是,我试图通过覆盖我样式表中的 css 背景颜色来在代码中执行此操作:

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

后者虽然改变了颜色但失败了。难道一旦我设置了样式表就无法覆盖它吗?如何在点击时更改按钮颜色?

我不得不做类似的事情(这里简化了,只有部分代码将样式更改为按钮),我做到了,希望对您有所帮助

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;
}

Styling FX Buttons with CSS 显示按钮的一些适用样式选项。

"fx-background-color" 只是一个错字。它需要是“-fx-background-color”。

要使用样式,您需要正确获取样式名称和值,并用分号分隔它们。以下方法系统地执行此操作:

  String bstyle=String.format("-fx-text-fill: %s;-fx-fill: %s;-fx-background-color: %s;",textFill,fill, bgColor);
  button.setStyle(bstyle);