如何在 Eclipse 中获取选定的代码?

2023-09-25Java开发问题
4

本文介绍了如何在 Eclipse 中获取选定的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

对于我的插件,我正在尝试访问 CompilationUnitEditor 中的选定代码.因此,我向上下文菜单添加了一个贡献并使用以下代码:

For my plugin I'm trying to access the selected code in a CompilationUnitEditor. Therefore I added a contribution to the context menu and use following code:

public class ContextMenuHandler implements IEditorActionDelegate {

    private IEditorPart editorPart;

    @Override
    public void setActiveEditor(IAction action, IEditorPart editorPart) {
        this.editorPart = editorPart;
    }

    @Override
    public void run(IAction action) {
        JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
    }

    @Override
    public void selectionChanged(IAction action, ISelection selection) {
        if (selection instanceof TextSelection) {
            TextSelection text = (TextSelection) selection;
            System.out.println("Text: " + text.getText());
        } else {
            System.out.println(selection);
        }
    }

}

现在的问题是方法 selectionChanged(...) 仅在我真正选择某些内容时才被调用,以便我可以复制/粘贴它.但我想访问像这样突出显示的代码元素(这里我想获取IEditorPart")

Now the problem is that the method selectionChanged(...) is only called when i really select something so that I could copy/paste it. But I want to access the Code elements that are highlighted like this (here I would like to get the "IEditorPart")

不幸的是,我不知道我应该寻找什么.

Unfortunately, I have no idea what I should look for.

推荐答案

使用其他答案的输入,我最终得到了以下解决方案:

Using the inputs from the other answers, I ended up with the following solution:

@Override
public void setActiveEditor(IAction action, IEditorPart editorPart) {
    ((CompilationUnitEditor) editorPart).getViewer().addTextListener(new ITextListener() {

        @Override
        public void textChanged(TextEvent event) {
            selectedText = event.getText();
        }
    });

}

这篇关于如何在 Eclipse 中获取选定的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

如何使用 JAVA 向 COM PORT 发送数据?
How to send data to COM PORT using JAVA?(如何使用 JAVA 向 COM PORT 发送数据?)...
2024-08-25 Java开发问题
21

如何使报表页面方向更改为“rtl"?
How to make a report page direction to change to quot;rtlquot;?(如何使报表页面方向更改为“rtl?)...
2024-08-25 Java开发问题
19

在 Eclipse 项目中使用西里尔文 .properties 文件
Use cyrillic .properties file in eclipse project(在 Eclipse 项目中使用西里尔文 .properties 文件)...
2024-08-25 Java开发问题
18

有没有办法在 Java 中检测 RTL 语言?
Is there any way to detect an RTL language in Java?(有没有办法在 Java 中检测 RTL 语言?)...
2024-08-25 Java开发问题
11

如何在 Java 中从 DB 加载资源包消息?
How to load resource bundle messages from DB in Java?(如何在 Java 中从 DB 加载资源包消息?)...
2024-08-25 Java开发问题
13

如何更改 Java 中的默认语言环境设置以使其保持一致?
How do I change the default locale settings in Java to make them consistent?(如何更改 Java 中的默认语言环境设置以使其保持一致?)...
2024-08-25 Java开发问题
13