如何使用Eclipse文本编辑器在RCP应用程序中显示/编辑/保存字符串?

时间:2018-12-13 02:27:27

标签: java eclipse rcp

我正在开发Eclipse 4 RCP应用程序。我有一些部分和一个编辑器的观点。编辑器的目的是打开,编辑和保存字符串。

  1. 如何打开将字符串作为输入的编辑器?大多数IDE.openEditor(...)实现都将IFile作为输入,但我不想将文件用作中介。

  2. 编辑编辑器的内容后,如何将其保存为字符串?使用文件时,编辑器会将其内容直接保存到文件中。

1 个答案:

答案 0 :(得分:0)

我知道了。通过Rüdiger Herrmanngreg-449,我可以构建此原型。

class StringEditorInput implements IStorageEditorInput {

    private IStorage storage;

    public StringEditorInput(IStorage storage) {

        this.storage = Objects.requireNonNull(storage, "Storage object cannot be null.");
    }

    @Override
    public boolean exists() {
        return true;
    }

    @Override
    public IStorage getStorage() throws CoreException {
        return storage;
    }

   /* Uninteresting methods left out for brevity */
}

class StringStorage implements IStorage {

    private String content;

    public StringStorage(String content) {

        this.content = Objects.requireNonNull(content, "The new content string cannot be null.");
    }

    @Override
    public InputStream getContents() throws CoreException {
        return new ByteArrayInputStream(content.getBytes(StandardCharsets.UTF_8));
    }

    /* Uninteresting methods left out for brevity */
}

/**
 * Set the text in the PDDL editor.
 *
 * @param text
 *            PDDL code to show in the editor.
 */
public void setEditorText(String text) {

    String editorId = "pl.poznan.put.cs.gui4pddl.PDDLEditor";
    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();

    try {
        editor = IDE.openEditor(page, new StringEditorInput(new StringStorage(text)), editorId);
    } catch (PartInitException e) {
        e.printStackTrace();
    }
}

/**
 * Get the text currently displayed in the PDDL editor.
 *
 * @return PDDL code.
 */
public String getEditorText() {

    IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    page.saveEditor(editor, false);

    String editorText = "";

    if (editor instanceof ITextEditor) {
        ITextEditor textEditor = (ITextEditor) editor;

        IDocumentProvider provider = textEditor.getDocumentProvider();

        IEditorInput input = editor.getEditorInput();

        IDocument document = provider.getDocument(input);

        editorText = document.get();
    }

    return editorText;
}

请注意,setEditorText(String text)getEditorText()以某种方式连接到RCP应用程序中的“打开”和“保存”按钮。