I have extended a JavaFX Button like so:
public class ExtendedButton extends Button {
private ObjectProperty<Enum> x;
public final void setX(Enum value) {
x.set(value);
}
public final String getX() {
return x.get()
}
}
public enum MyEnum{
A,
B
}
Now i want to be able to use this in my FXML. Something like this:
<ExtendedButton fx:id="xButton" x=MyEnum.A />
How do i achieve this.
You can do this using property elements, instead of attributes, along with the fx:constant
attribute :
<ExtendedButton fx:id="xButton" >
<x><MyEnum fx:constant="A" /></x>
</ExtendedButton>
Here's an SSCCE:
ExtendedButton.java
package application;
import javafx.beans.binding.Bindings;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.control.Button;
public class ExtendedButton extends Button {
public final ObjectProperty<Enum<?>> buttonState = new SimpleObjectProperty<>(ButtonState.NORMAL);
public final ObjectProperty<Enum<?>> buttonStateProperty() {
return this.buttonState;
}
public final Enum<?> getButtonState() {
return this.buttonStateProperty().get();
}
public final void setButtonState(final Enum<?> buttonState) {
this.buttonStateProperty().set(buttonState);
}
public ExtendedButton() {
super();
styleProperty().bind(Bindings.
when(buttonState.isEqualTo(ButtonState.CRITICAL)).
then("-fx-base: red;").
otherwise(""));
}
}
ButtonState.java:
package application;
public enum ButtonState { NORMAL, CRITICAL }
ExtendedButtonTest.fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import javafx.scene.layout.StackPane?>
<?import application.ExtendedButton?>
<?import application.ButtonState?>
<?import javafx.geometry.Insets?>
<StackPane xmlns:fx="http://javafx.com/fxml/1">
<padding>
<Insets top="20" right="20" bottom="20" left="20"/>
</padding>
<ExtendedButton text="Test" >
<buttonState>
<ButtonState fx:constant="CRITICAL"/>
</buttonState>
</ExtendedButton>
</StackPane>
ExtendedButtonTest.java:
package application;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
public class ExtendedButtonTest extends Application {
@Override
public void start(Stage primaryStage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("ExtendedButtonTest.fxml"));
primaryStage.setScene(new Scene(root));
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.