Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map values of JavaFX observables?

I have a SimpleIntegerProperty and want to derive a SimpleObjectProperty<Color> from it.
For that I imagine some mechanism like with streams and optionals:

SimpleIntegerProperty intProp;
ObjectProperty<Color> colorProp = intProp.map(i -> convertIntToColor(i), c -> convertColorToInt(c));

Is there something built-in already or do I really need to roll this out on my own?
It would seems odd if there is no such thing because looking at all the power of Bindings gives you the strong feeling that this feature should also be there.

Thanks!

like image 567
Chris Avatar asked Sep 02 '16 07:09

Chris


1 Answers

Unsure if this is the best way, but this seems to work using Bindings.createObjectBinding:

@Test
    public void test() {
        SimpleIntegerProperty simpleIntegerProperty = new SimpleIntegerProperty(1);
        ObjectBinding<Color> binding = Bindings
                .createObjectBinding(() -> converToColor(simpleIntegerProperty.get()), simpleIntegerProperty);
        System.out.println(binding.get());
        binding.addListener(new ChangeListener<Color>() {
            @Override
            public void changed(ObservableValue<? extends Color> observable, Color oldValue, Color newValue) {
                System.out.println(newValue);
            }
        });
        simpleIntegerProperty.set(2);
    }

    private Color converToColor(int i) {
        switch (i) {
            case 1:
                return Color.RED;
            case 2:
                return Color.BLUE;
        }
        return null;
    }
like image 155
Wim Deblauwe Avatar answered Oct 09 '22 08:10

Wim Deblauwe