You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.14 19:15:24