我已经设置我的应用程序以基于枚举更改其功能。链接到该枚举的变量的值将确定程序如何解释某些操作,例如单击鼠标等。我希望标签(可能在左下角的状态区域)反映应用程序当前所处的“模式”,并显示一条可读的消息供用户查看。

这是我的枚举:

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


根据我的收集,我正在寻找一种将枚举的toString()属性(我覆盖为更易消化的形式)绑定到此标签的方法。绑定将使每当我设置类似

applicationState = Mode.alternativeMode;


标签将自动显示toString()结果,而无需每次都放置leftStatus.setText(applicationState.toString())

这是我尝试过的:(在主控制器类中):

leftStatus.textProperty().bind(applicationState.getProperty());


这样会将标签设置为初始文本,但是在更新applicationState枚举时不会更新。

我究竟做错了什么?

最佳答案

为何不向枚举类添加属性,为什么不对应用程序状态使用ObjectProperty?看看这个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;
        }
    }

}

10-07 12:51
查看更多