2015-12-31 71 views
0

我有我想用來顯示不同狀態的JavaFX Label。基於int值的顯示字符串

int status; 

Label finalFieldAgentStatus = new Label(); 

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

有沒有什麼聰明的方式自動設置基於statusfinalFieldAgentStatus字符串?

回答

1

您應該更改狀態字段的類型並使用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

我看到很多示例。你能給最好的嗎? –