FoxMaccloud
FoxMaccloud

Reputation: 109

Javafx, Is there a way to check state of buttons and do an if statement depending on its state?

In Javafx there is an option to set colors/styles for buttons e.g.,

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

Is there any syntax for checking a buttons style for witch color the button has?

Basically I want to do something like:

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

Upvotes: 0

Views: 748

Answers (2)

Byaz
Byaz

Reputation: 1

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

Upvotes: 0

Piotr Wilkin
Piotr Wilkin

Reputation: 3491

Yes, you can do it via .contains() or via regular expression (.matches()) by using getStyle() (for example, in your case, it would be button.getStyle().contains("-fx-background-color: red").

However, keep in mind that both setStyle() and getStyle() only refer to inline styles. Therefore, they will not include the styles that are passed via CSS selectors in attached CSS files.

Generally, using visual properties for determining semantic properties is not considered a good practice. If you have buttons that are supposed to exhibit a particular behavior, consider extending the Button class and adding those as proper properties instead.

Upvotes: 1

Related Questions