基于int值的显示字符串

问题描述:

我有我想用来显示不同状态的JavaFX Label。基于int值的显示字符串

int status; 

Label finalFieldAgentStatus = new Label(); 

当我有status = 0我想打印finalFieldAgentStatus = "Innactive"; 当我有status = 1我想打印finalFieldAgentStatus = "Active";

有没有什么聪明的方式自动设置基于statusfinalFieldAgentStatus字符串?

您应该更改状态字段的类型并使用IntegerProperty

通过这样做,您可以在此属性和label.textProperty()之间添加绑定,以在状态更改时自动更改值。

你可以阅读更多有关绑定的位置:https://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm

编辑:

例如,你可以这样做:

IntegerProperty status = new SimpleIntegerProperty(); 
Label label = new Label(); 
status.addListener((observable, oldValue, newValue) -> { 
    label.setText(newValue.intValue() == 1 ? "Active" : "Inactive"); 
}); 

,或者你可以这样做:

IntegerProperty status = new SimpleIntegerProperty(); 
Label label = new Label(); 
label.textProperty().bind(Bindings.createStringBinding(
     () -> status.intValue() == 1 ? "Active" : "Inactive", status)); 
+0

你能告诉我工作的例子吗? –

+0

@PeterPenzov我刚刚编辑了我的答案,添加了很多绑定示例的链接:https://docs.oracle.com/javafx/2/binding/jfxpub-binding.htm – Prim

+0

我看到很多示例。你能给最好的吗? –