Here is some code I have written to handle in a generic fashion an event handler which should only fire once for any JavaFX event:
public final class OneShotEvent<T extends Event>
implements EventHandler<T>
{
private final AtomicBoolean triggered = new AtomicBoolean(false);
private final EventHandler<T> delegate;
public static <E extends Event> EventHandler<E> of(final EventHandler<E> delegate)
{
return new OneShotEvent<>(delegate);
}
private OneShotEvent(final EventHandler<T> delegate)
{
this.delegate = Objects.requireNonNull(delegate);
}
@Override
public void handle(final T event)
{
if (!triggered.getAndSet(true))
delegate.handle(event);
}
}
For some reason, I made triggered an AtomicBoolean instead of a plain boolean.
After thinking about it, I believe this is overkill, because event handlers will run on the "platform thread" of JavaFX... Or will they not? Because if this is the case, then a simple boolean is enough... Right?
If you know the calls are single threaded or thread safe, a simple boolean would be enough, though your could drop it.
private EventHandler<T> delegate;
public void handle(T event) {
if (delegate != null)
delegate.handle(event);
delegate = null; // don't retain a delegate we don't need
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With