From 3cfcf1e772c4a88ddd574e7fd722ba3a331edded Mon Sep 17 00:00:00 2001 From: yushijinhun Date: Sun, 18 Feb 2018 16:47:00 +0800 Subject: [PATCH] =?UTF-8?q?=E7=94=A8=E5=AE=9A=E4=B9=89=E7=9A=84=E7=B1=BB?= =?UTF-8?q?=E5=9E=8B=E4=BB=A3=E6=9B=BFFXUtils.addListener=E4=B8=AD?= =?UTF-8?q?=E7=9A=84Pair?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../java/org/jackhuang/hmcl/ui/FXUtils.java | 43 +++++++++++++------ 1 file changed, 30 insertions(+), 13 deletions(-) diff --git a/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java b/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java index e7861c399..d58db81c9 100644 --- a/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java +++ b/HMCL/src/main/java/org/jackhuang/hmcl/ui/FXUtils.java @@ -94,20 +94,37 @@ public final class FXUtils { }); } - public static void addListener(Node node, String key, ObservableValue value, Consumer callback) { - ChangeListener listener = (a, b, newValue) -> callback.accept(newValue); - node.getProperties().put(key, new Pair<>(callback, listener)); - value.addListener(listener); - } + private static class ListenerPair { + ObservableValue value; + ChangeListener listener; - public static void removeListener(Node node, String key) { - if (node.getProperties().get(key) instanceof Pair) { - Pair pair = (Pair) node.getProperties().get(key); - if (pair.getValue() instanceof ObservableValue && pair.getKey() instanceof ChangeListener) { - ((ObservableValue) pair.getValue()).removeListener((ChangeListener) pair.getKey()); - } - } - } + ListenerPair(ObservableValue value, ChangeListener listener) { + this.value = value; + this.listener = listener; + } + + void bind() { + value.addListener(listener); + } + + void unbind() { + value.removeListener(listener); + } + } + + public static void addListener(Node node, String key, ObservableValue value, Consumer callback) { + ListenerPair pair = new ListenerPair<>(value, (a, b, newValue) -> callback.accept(newValue)); + node.getProperties().put(key, pair); + pair.bind(); + } + + public static void removeListener(Node node, String key) { + Lang.convert(node.getProperties().get(key), ListenerPair.class) + .ifPresent(info -> { + info.unbind(); + node.getProperties().remove(key); + }); + } public static void setValidateWhileTextChanged(Node field, boolean validate) { if (field instanceof JFXTextField) {