我有各种各样的按钮,每个按钮都有自己的背景颜色(-fx-background-color:rgb(xxx,xxx,xxx)。按钮的颜色在.fxml文件中定义。
现在,我想在.css文件中定义每个按钮的背景色,以将鼠标悬停时变亮。
例如:Button1的常规颜色是-fx-background-color:rgb(176,30,0)在鼠标悬停时,它应更改为-fx-background-color:rgba(176,30,0,0.7)
我的第一个问题:fxml文件中定义的-fx-background-color会覆盖.css文件中定义的.button:hover {-fx-background-color:rgba(176,30,0,0.7);} 。
第二个问题:甚至还有一种方法可以通过css来指定鼠标悬停时按钮的颜色应保留其rgb值,并仅添加0.7值?
提前感谢!
我的第一个问题:[...]
仅仅是定义的层次结构,例如G。 FXML文件中使用的一个控件的背景颜色样式命令将始终覆盖CSS文件中使用的相同控件的样式命令。如果您具有带有设置的#id和设置的#class控件的纯CSS,则行为相同。 e。 G。 id语句中定义的背景色将覆盖为该类定义的背景色。因此,这是标准行为,您无法更改。
第二个问题:[...]
[没有像-fx-background-transparency:0.7;这样的CSS命令。您可以使用CSS做到这一点(并且不会在FXML中覆盖):
.my-btn-class {
-fx-background-color: rgb(176, 30, 0);
}
.my-btn-class:hover {
-fx-background-color: rgba(176, 30, 0, 0.7);
}
或者您也可以像这样以编程方式完成它:
package sample;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.input.MouseEvent;
import java.net.URL;
import java.util.ResourceBundle;
public class Controller implements Initializable {
@FXML
Button button;
private int[] myButtonBackgroundColorRGB = new int[]{176, 30, 0};
private float transparency = 0.7f;
@Override
public void initialize(URL location, ResourceBundle resources) {
button.setStyle(String.format("-fx-background-color: rgb(%d, %d, %d);",
myButtonBackgroundColorRGB[0], myButtonBackgroundColorRGB[1], myButtonBackgroundColorRGB[2]));
}
@FXML
public void handleOnMouseEntered(MouseEvent event) {
Button button = (Button) event.getSource();
button.setStyle(String.format("-fx-background-color: rgba(%d, %d, %d, %s);",
myButtonBackgroundColorRGB[0], myButtonBackgroundColorRGB[1], myButtonBackgroundColorRGB[2],
String.format("%.2f", transparency).replace(",", ".")));
}
@FXML
public void handleOnMouseExited(MouseEvent event) {
Button button = (Button) event.getSource();
button.setStyle(String.format("-fx-background-color: rgb(%d, %d, %d);",
myButtonBackgroundColorRGB[0], myButtonBackgroundColorRGB[1], myButtonBackgroundColorRGB[2]));
}
}
或者如果您不想在initialize方法中设置颜色,则可以在FXML文件中设置颜色(就像您已经做过的那样),并在进入和退出鼠标时使用button.getStyle()获得样式命令。一些正则表达式并设置通缉的麦粒肿。 ;-)