IntelliJ Kotlin SDK:基础EditorMouseMotionListener为何无法生效?
修正步骤
问题根源
- 直接在
applicationListeners中注册EditorMouseMotionListener错误:该监听器需要绑定到具体Editor实例,框架无法自动将Editor注入你的类构造函数,导致监听器未被正确初始化。 - 构造函数内的
editor.addEditorMouseMotionListener(this)无法执行,因为Editor实例未被正确传入。 println在插件运行环境中无法输出到可见控制台,需使用IntelliJ官方日志工具。
1. 重构监听器类
创建独立的鼠标监听器实现,同时通过EditorFactoryListener监听所有Editor的创建事件,动态为每个Editor绑定鼠标监听器:
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.event.EditorMouseEvent import com.intellij.openapi.editor.event.EditorMouseMotionListener import com.intellij.openapi.editor.event.EditorFactoryEvent import com.intellij.openapi.editor.event.EditorFactoryListener import com.intellij.openapi.diagnostic.Logger class MyEditorMouseListener : EditorMouseMotionListener { private val logger = Logger.getInstance(javaClass) override fun mouseMoved(e: EditorMouseEvent) { val editor = e.editor val line = editor.xyToLogicalPosition(e.mouseEvent.point).line logger.info("鼠标移动到行号: $line") // 后续可在此添加HintManager弹窗逻辑 } // 监听Editor创建事件的内部类 class MyEditorFactoryListener : EditorFactoryListener { override fun editorCreated(event: EditorFactoryEvent) { val editor = event.editor editor.addEditorMouseMotionListener(MyEditorMouseListener()) } } }
2. 修改plugin.xml配置
替换原有的applicationListeners配置,改为注册EditorFactoryListener以监听Editor创建事件:
<applicationListeners> <listener class="com.github.baristageek.watermelonintellij.listeners.MyEditorMouseListener$MyEditorFactoryListener" topic="com.intellij.openapi.editor.event.EditorFactoryListener"/> </applicationListeners>
3. 验证日志输出
运行插件后,通过以下步骤查看日志:
- 打开IntelliJ的
Help > Diagnostic Tools > Debug Log Settings - 添加你的日志类路径(如
com.github.baristageek.watermelonintellij.listeners.MyEditorMouseListener) - 前往
Help > Show Log in Explorer/Finder查看日志文件,即可看到鼠标移动的日志信息
后续实现Hint弹窗示例
当鼠标事件正常触发后,可使用HintManager显示悬浮弹窗:
import com.intellij.openapi.editor.HintManager import com.intellij.ui.components.JBLabel import java.awt.Point // 在mouseMoved方法内添加: val hintText = "行号$line的提示内容" val hintComponent = JBLabel(hintText) val mousePoint = e.mouseEvent.point HintManager.getInstance().showHint( hintComponent, mousePoint.x, mousePoint.y + 20, // 偏移位置避免遮挡鼠标 editor.component, HintManager.HIDE_BY_ANY_KEY or HintManager.HIDE_BY_TEXT_CHANGE, 0 // 0表示手动关闭弹窗,可设置毫秒数自动隐藏 )
内容的提问来源于stack exchange,提问作者Esteban Vargas
相关产品推荐
相关产品推荐

