Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make JavaFX Property Listener to fire an event even if the oldVaule and newValue are the same?

Tags:

java

javafx

Lets consider a sample code:

SimpleIntegerProperty simpleIntegerProperty = new SimpleIntegerProperty(0);
simpleIntegerProperty.addListener((observable, oldValue, newValue) -> {
  // execution code when the event is fired.
});

When I set a new value using a setValue() method, if the oldValue and newValue are the same, the event is not fired. Only when they differ.

An example:

  • I have a ListView<Element> binded with an ObservableList<Element> containing some "elements".
  • I can add more elements in a different place of my application.
  • There's a button "Start" which launches a procedure - it iterates throught the list and does some actions with every element.
  • A Procedure is a different class. It does some stuff with elements and also it contains SimpleIntegerPorperty - currentlyChosenElementIndex to indicate an index of the currently chosen element.

When the current element is being proceeded, I'd like the ListView to show that. Now, during the procedure, the GUI is blocked and the current element is selected on the ListView, while being proceeded. After the end of the procedure the application resets currentlyChosenElementIndex to zero and this is an index with I have my problem. When the procedure starts, the first element is not selected because the application setValue() to the same one that was previously.

Is there any way to change that?

like image 860
Przemysław Długoszewski-Tamoń Avatar asked Oct 23 '25 15:10

Przemysław Długoszewski-Tamoń


1 Answers

You cannot do this by simply using SimpleIntegerProperty class. But you can extend class and add the required functionality. Create a class like this

public class NotifySetIntegerProperty extends SimpleIntegerProperty {
    private OnSetValueListener valueListener;

    public NotifySetIntegerProperty(int initialValue) {
        super(initialValue);
    }

    @Override
    public void set(int newValue) {
        super.set(newValue);
        if(valueListener!= null) {
            valueListener.onValueSet(newValue);
        }
    }

    public void setValueListener(OnSetValueListener valueListener) {
        this.valueListener = valueListener;
    }

    public interface OnSetValueListener {
        void onValueSet(int value);
    }
}

Then you can use it and be notified when setValue or set method is called

NotifySetIntegerProperty property = new NotifySetIntegerProperty(0);
property.setValueListener(new NotifySetIntegerProperty.OnSetValueListener() {
    @Override
    public void onValueSet(int value) {
        System.out.println(value);
    }
});
property.setValue(1);
property.setValue(0);

Will output

1
0
like image 176
Flood2d Avatar answered Oct 25 '25 04:10

Flood2d



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!