Binding an enum's toString() to a Label
binding, enums, javafx, label
Solution
Instead of adding a property to the enum class, why not use a `ObjectProperty` for the application state? Have a look at this MCVE:
import javafx.application.Application;
import javafx.beans.property.ObjectProperty;
import javafx.beans.property.SimpleObjectProperty;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.layout.FlowPane;
import javafx.stage.Stage;
public class Example extends Application {
private ObjectProperty<Mode> appState = new SimpleObjectProperty<>(Mode.DEFAULT);
public static void main(String[] args) {
launch(args);
}
@Override
public void start(Stage primaryStage) throws Exception {
Button btn = new Button("Toggle mode");
btn.setOnMouseClicked((event) -> appState.setValue(appState.get() == Mode.DEFAULT ? Mode.ALTERNATIVE : Mode.DEFAULT));
Label lbl = new Label();
lbl.textProperty().bind(appState.asString());
FlowPane pane = new FlowPane();
pane.getChildren().addAll(btn, lbl);
primaryStage.setScene(new Scene(pane));
primaryStage.show();
}
public enum Mode {
DEFAULT("Default mode"),
ALTERNATIVE("Alternative mode");
private String description;
private Mode(String description) {
this.description = description;
}
@Override
public String toString() {
return description;
}
}
}
Problem
I have set up my application to change its function based on an enum. The value of a variable linked to this enum will determine how the program interprets certain actions like mouse clicks and so on. I would like a Label (perhaps in the status area in the bottom left) to reflect what the current "mode" the application is in, and display a readable message for the user to see. Here's my enum: ``` enum Mode { defaultMode, // Example states that will determine alternativeMode; // how the program interprets mouse clicks // My attempt at making a property that a label could bind to private SimpleStringProperty property = new SimpleStringProperty(this, "myEnumProp", "Initial Text"); public SimpleStringProperty getProperty() {return property;} // Override of the toString() method to display prettier text @Override public String toString() { switch(this) { case defaultMode: return "Default mode"; default: return "Alternative mode"; } } } ``` From what I've gathered, what I'm looking for is a way to bind an enum's toString() property (which I overrode into more digestable form) to this label. The binding would be so that whenever I set something like ``` applicationState = Mode.alternativeMode; ``` the label will display the `toString()` results automatically, without me needing to place a `leftStatus.setText(applicationState.toString())` every time I do that. Here's what I've tried: (in my main controller class): ``` leftStatus.textProperty().bind(applicationState.getProperty()); ``` That sets the label to the initial text, but won't update when I update the `applicationState` enum. What am I doing wrong?