dadadima
dadadima

Reputation: 938

JavaFX Label that dynamically displays a value calculated using some controllers

I have some JavaFX controllers implemented with listeners (eg. a Slider, some RadioButtons in a ToggleGroup). I would like to have a Label or a TextField (I think the former suits better from my request) that displays a number resulting from an operation made with the numbers selected through my controllers. The Label should update the displayed value automatically everytime the controllers are used by the user. How can I achieve this?

A Basic Example

private Slider firstSlider = new Slider(0, 255, 0);
private Slider secondSlider = new Slider (0, 15, 0);
private Label firstSliderValue = new Label("256 bytes (64 words)");
private Label secondSliderValue = new Label("0.413818359375 KHz");

// I would like this Label to display for example 
// double math = secondSlider.getValue() * firstSlider.getValue();
private Label finalValueLabel; 

firstSlider.valueProperty().addListener((ov, old_val, new_val) -> {
    int value = (int) Math.round(new_val.doubleValue());
    firstSlider.setValue(value);
    System.out.println(value);
    firstSliderValue.setText(getDisplayMemory(value));
});

    secondSlider.valueProperty().addListener((ov, old_val, new_val) -> {
    int value = (int) Math.round(new_val.doubleValue());
    secondSlider.setValue(value);
    System.out.println(value);
    secondSliderValue.setText(getDisplayFrequency(value));
});

getDisplayFrequency and getDisplayMemory are just some methods for displaying a certain text on the firstSliderValue and on the secondSliderValue depending on the values selected via the Sliders, but they are not necessary for my question.

EDIT: Added a basic and simple example.

Upvotes: 0

Views: 1252

Answers (1)

Halko Karr-Sajtarevic
Halko Karr-Sajtarevic

Reputation: 2268

You can use Bindings.createStringBinding

e.g.

label.textProperty().bind(
    Bindings.createStringBinding(
        () -> String.format("%.2f", firstSlider.getValue()*secondSlider.getValue()), 
        firstSlider.valueProperty(), secondSlider.valueProperty()
    )
);

And you can improve your other code too if you want.

e.g.

firstSliderValue.textProperty().bind(
    Bindings.createStringBinding(
        () -> getDisplayMemory((int) Math.round(firstSlider.getValue())),
        firstSlider.valueProperty()
    )
);
secondSliderValue.textProperty().bind(
    Bindings.createStringBinding(
        () -> getDisplayFrequency((int) Math.round(secondSlider.getValue())),
        secondSlider.valueProperty()
    )
);

Upvotes: 3

Related Questions