gpt4 book ai didi

java - 使用空赋值控制监听器的添加和移除

转载 作者:行者123 更新时间:2023-11-30 07:29:08 27 4
gpt4 key购买 nike

我有一个 JComponent 需要根据类的其他字段的状态添加或删除监听器的情况。不应多次添加监听器,当然也只能删除一次。使用类字段来存储监听器并使用 null 值来控制向组件注册/注销监听器的操作是否是一个好习惯。

我想到的代码是这样的(修改代码以明确 JComponent 提供给类):

public class MyClass {
private ActionListener fListener = null;
private JComponent fComponent;

public MyClass(JComponent component) {
fComponent = component; // for example, component = new JButton("Test");
}

public void setListener() {
if (fListener == null ) {
fListener = new MyListener();
fComponent.addActionListener(fListener);
}
}

public void removeListener() {
if (fListener != null) {
fComponent.removeActionListener(fListener);
fListener = null;
}
}
}

最佳答案

不要每次都实例化和处理监听器对象。使用 getActionListeners() 方法来验证是否添加了监听器。

public class MyClass {
private ActionListener fListener = new MyListener();
private JButton fComponent = new JButton("Test");

public MyClass() {
fComponent.addActionListener(fListener);
}
public void setListener() {
if (fComponent.getActionListeners().length == 0) {
fComponent.addActionListener(fListener);
}
}

public void removeListener() {
if (fComponent.getActionListeners().length !=0) {
fComponent.removeActionListener(fListener);
}
}
}

方法 ActionListener[] getActionListeners() 返回添加到此 JButton 的所有 ActionListeners 的数组。

关于java - 使用空赋值控制监听器的添加和移除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8721411/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com