打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
SWT 中 texteditor 的一些操作
userphoto

2012.06.01

关注
SWT 中 texteditor 的一些操作
2008-04-11 9:34

下边部分是转别人的 来自Allen Young

_part是action中的IEidtorPart。

如何获得一个未被TextEditor打开的文件的内容:

这个在做“选中文件并对其中内容进行操作”这种功能时很有用,

代码如下:

IFile file = ((FileEditorInput) Workbench.getInstance().getActiveWorkbenchWindow().getActivePage().getActiveEditor().getEditorInput()).getFile();

try {

InputStream contents = file.getContents();

byte[] data = new byte[contents.available()];

contents.read(data);

String textContent = new String(data);

} catch (Exception e)

{

e.printStackTrace();

}

如何获得被TextEditor打开的文件的内容:

只有这个方法才能获得未保存的信息,代码如下:

1.IDocument document = ((TextEditor) _part).getDocumentProvider().getDocument(_part.getEditorInput());

2 String textContent = document.get();

可以看到,每个TextEditor都有一个DocumentProvider,我们通过它来获得IDocument,而IDocument中存储的就有一些字符信息,就是我们想要的内容。

注意getDocument方法的参数其实Object类型,也就是说可以传入任何东东,然后DocumentProvider会尝试把它转换成Document。

这里我们传入的是TextEditor的EditorInput,是正确的。

之后我们再用IDocument的get方法就可以得到TextEditor的内容啦!

如何获得在TextEditor中选中的内容:

代码如下:

String content = ((TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection()).getText();

虽然phiobos说SelectionProvider不是这样用的,有点儿旁门左到,但是貌似正解的getSourceViewer().getSelectedRange()中getSourceViewer()却是个protected方法,所以没办法啦,还好能用就成~

如何把内容写回TextEditor:

知道了IDocument这个东东就简单了~

1 document.set(content);

如何替换TextEditor中内容的一部分:

对TextEditor的操作,最重要的就是这个IDocument类,很多功能的实现都是通过它来完成的。

IDocument包含了TextEditor中内容的完整信息,可以想到,如果要替换TextEditor中的一部分内容,要知道的信息有两个:被替换代码的位置和范围,替换代码。

下面的例子中展示了一个简单的替换:

1 // get the selection object.

2 TextSelection selection = (TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection();

3 // get the content of the selection object as a string.

4 String source = ((TextSelection) ((TextEditor) _part).getSelectionProvider().getSelection()).getText(); 5 // get the document of the TextEditor's content.

6 IDocument doc = ((TextEditor) _part).getDocumentProvider().getDocument(_part.getEditorInput());

7 try {

8 // replace selection with the result of format.

9 doc.replace(selection.getOffset(), selection.getLength(),"hello");

10 } catch (BadLocationException e) {

11 e.printStackTrace();

12 }

可以看到核心方法是IDocument的replace,它的三个参数分别是被替换代码的offset,被替换代码的length和替换代码。我在例子中实现的是替换选中部分的代码,所以offset和length可以从TextSelection对象中得到。

如何在TextEditor中插入内容: 感觉上应该有insert之类的方法,但是很遗憾的是并没有。变通的做法是使用上面所提到的replace方法,把被替换代码长度这个参数设置为0就可以了。那么如果要实现在光标处插入内容,如何得到光标的位置呢?同样遗憾的是,并没有专门的方法,而是使用上面提到的getSelection.getOffset()。这样返回的就是光标的位置,而getSelection.getLength()返回为0。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
SharpDevelop浅析_4_TextEditor_自动完成、代码折叠…… Parser及其应用: Code Completion, Method Insight, Class Scout ...
Jigloo 开发 Swing 的入门教程
JAVA浏览器实现方式
Swt常用控件中文教程
Eclipse RCP application - custom splash screen
Safari 浏览器 一键翻译网页
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服