JavaFX 8 数字格式绑定

6

能否有人给我展示一个Bindings.bindBidirectional的例子,其中一个文本字段绑定到Double值并且该文本字段被格式化为零位小数。我有以下绑定:

Bindings.bindBidirectional(xProperty, sp.layoutXProperty(), converter);

其中xProperty是一个StringProperty,sp.layoutXProperty是一个DoubleProperty。

我尝试了许多不同的转换器,最终选择了:

NumberFormat nf = NumberFormat.getInstance();    
StringConverter<Number> converter = new NumberStringConverter(nf);

然后我尝试了:

nf.setParseIntegerOnly(true);

但是没有效果。这只是实现结果的许多尝试之一。这可能很直接,但是关于将不同属性与格式绑定的信息似乎很少或者我错过了明显的东西?

2个回答

6

看一下这段代码,看看它是否解决了你的问题:

public class BindingTest {
    static Property<String> sp;
    static Property<Double> dp;

    public static void main(String[] args) {
        sp = new SimpleStringProperty();
        dp = new SimpleObjectProperty<>();

        StringConverter<Double> sc = new StringConverter<Double>() {
            @Override
            public String toString(Double object) {
                if (object != null)
                    return Integer.toString((int) Math.round(object.doubleValue()));
                else
                    return null;
            }

            @Override
            public Double fromString(String string) {
                Double d = Double.parseDouble(string);
                sp.setValue(Integer.toString((int) Math.round(d)));
                return d;
            }
        };

        Bindings.bindBidirectional(sp, dp, sc);

        print();
        sp.setValue("3.14");
        print();
        dp.setValue(6.18);
        print();
    }

    public static void print() {
        System.out.println("String: " + sp.getValue() + "\t" + "Double: " + dp.getValue());
    }
}

输出:

String: null    Double: null
String: 3   Double: 3.14
String: 6   Double: 6.18

4

将双精度值转换为整数可能会有不同的方法,而这些方法在转换时使用不同的舍入方式。本答案与其他答案类似,但添加了一个额外的过滤器,只允许文本字段中的整数值:

@Override
public void start( Stage stage )
{
    TextField field = new TextField();
    DoubleProperty doubleProperty = new SimpleDoubleProperty();
    Label label = new Label();
    label.textProperty().bind( doubleProperty.asString() );

    DecimalFormat format = new DecimalFormat();
    format.setParseIntegerOnly( true );  // used while parsing the input text of textfield
    format.setMaximumFractionDigits( 0 );  // used while formatting the doubleProperty's bound value as output text of textfield
    format.setGroupingUsed( false );  // disable thousand grouping
    format.setRoundingMode( RoundingMode.UP );  // set rounding mode

    Bindings.bindBidirectional( field.textProperty(), doubleProperty, new StringConverter<Number>()
    {
        @Override
        public String toString( Number object )
        {
            return object == null ? "" : format.format( object );
        }


        @Override
        public Number fromString( String string )
        {
            return (string != null && !string.isEmpty()) ? Double.valueOf( string ) : null;
        }
    } );

    // apply filter to allow only integer values
    field.setTextFormatter( new TextFormatter<>( c ->
    {
        if ( c.getControlNewText().isEmpty() )
        {
            return c;
        }

        ParsePosition parsePosition = new ParsePosition( 0 );
        Object object = format.parse( c.getControlNewText(), parsePosition );

        if ( object == null || parsePosition.getIndex() < c.getControlNewText().length() )
        {
            return null;
        }
        else
        {
            return c;
        }

    } ) );

    Button b = new Button( "+1.6" );
    b.setOnAction( ( e ) ->
    {
        doubleProperty.set( doubleProperty.get() + 1.6 );
    } );

    Scene scene = new Scene( new VBox( 5 ) );
    stage.setWidth( 450 );
    stage.setHeight( 250 );
    (( VBox ) scene.getRoot()).getChildren().addAll( field, label, b );
    stage.setScene( scene );
    stage.show();
}

1
谢谢您提供的这两个答案。我只能投票支持一个,所以我会选择第一个回复进行投票,但是Uluk的示例也给了我一些其他的想法。希望这些示例对其他人也有用。 - Frank

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接