是否可以删除 Java 中的 mouseListener

is it possible to remove a mouseListener in Java

我将 mouseListener 添加到一个按钮,当鼠标移动到它时它会执行一些操作。我向同一个按钮添加了一个 actionListener,它删除了按钮。我的问题是:当我尝试删除按钮时出现运行时错误。我怎样才能删除按钮?

关于:

is it posibble to remove a mouseListener in Java

是的,只需调用 myComponent.removeMouseListener(myMouseListener); 它就消失了。您当然需要对上述 MouseListener 的引用。

另外关于:

I added mouseListener to a button

您通常不想这样做,我很想知道您是如何使用它的。 JButtons 应该添加 ActionListeners 而不是 MouseListeners。

and when mouse moved to it it performs some action.

如果要监听悬停,您最好向 JButton 的模型添加一个 ChangeListener 并查询 isRollover()。 -- 或者 -- 也许您真正需要的是通过 setToolTipText(String text) 方法设置 JButton 的工具提示文本。

I added an actionListener to same button and it removes the button. My question is: when I try to remove the button I get runtime error. How can i remove the button?

这里我们被卡住了,因为我们无法访问相关代码或您的错误消息。如果您需要更多帮助,请通过提供相关代码来改进问题,最好是 Minimal, Complete, and Verifiable Example Program 将代码压缩到仍然可以编译和运行的最小位,没有外部依赖性(例如需要 link 到数据库或图像),没有与您的问题无关的额外代码,但仍能说明您的问题。此外 post 完整的错误消息以及导致错误的行的指示(错误消息会告诉您)。