Javafx,有没有一种方法可以检查按钮的状态并根据其状态执行if语句?

时间:2019-07-16 16:47:28

标签: java javafx

在Javafx中,有一个选项可以设置按钮的颜色/样式,例如

button.setStyle("-fx-background-color: red");

有没有用于检查按钮样式的语法,以检查按钮具有的颜色?

基本上我想做类似的事情:

if (button.style("-fx-background-color: red")) {
something....
}

2 个答案:

答案 0 :(得分:1)

是的,您可以使用.contains()通过.matches()或正则表达式(getStyle())来实现(例如,您的情况是button.getStyle().contains("-fx-background-color: red")

但是,请记住,setStyle()getStyle()都只引用内联样式。因此,它们不会在附加的CSS文件中包含通过CSS选择器传递的样式。

通常,使用视觉属性确定语义属性不是一个好习惯。如果您有应该表现出特定行为的按钮,请考虑扩展Button类,并将其添加为适当的属性。

答案 1 :(得分:0)

Button button = new Button();
String[] styles = button.getStyle().split(";");
for(String style : styles){
   if(style.contains("-fx-background-color")){
       String color = style.split(": ")[1]; // the color of the button
   }
}