根据 int 值显示 String
Display String based on int value
我有 JavaFX 标签,我想用它来显示不同的状态。
int status;
Label finalFieldAgentStatus = new Label();
当我有 status = 0
我想打印 finalFieldAgentStatus = "Innactive"
;
当我有 status = 1
我想打印 finalFieldAgentStatus = "Active";
有什么聪明的方法可以根据 status
值自动设置 finalFieldAgentStatus
字符串吗?
您应该更改状态字段的类型并使用 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 ) );
我有 JavaFX 标签,我想用它来显示不同的状态。
int status;
Label finalFieldAgentStatus = new Label();
当我有 status = 0
我想打印 finalFieldAgentStatus = "Innactive"
;
当我有 status = 1
我想打印 finalFieldAgentStatus = "Active";
有什么聪明的方法可以根据 status
值自动设置 finalFieldAgentStatus
字符串吗?
您应该更改状态字段的类型并使用 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 ) );