在實際項目應用裡,如果需要使用者手動輸入比較複雜的常值內容時可以考慮利用內容助理(Content Assistant)功能減輕使用者負擔,同時減低出錯的機會。Jface的SourceViewer支援內容助理,這篇文章裡介紹一下如 何實現自動完成(Auto Completion)功能,即向使用者提示接下來可能輸入的內容。
//Create a new source viewer
sourceViewer = new SourceViewer(shell, null, SWT.BORDER | SWT.WRAP | SWT.V_SCROLL);
//Set a blank document
sourceViewer.setDocument(new Document(""));
sourceViewer.setEditable(true);
StyledText txtSource = sourceViewer.getTextWidget();
GridData gd = new GridData(GridData.FILL_BOTH);
txtSource.setLayoutData(gd);
自動完成功能一般在以下兩種條件下彈出一個小視窗向使用者提示當前可供選擇的選項,一是使用者按下指定的按鍵組合時,二是使用者輸入了特定的字
符時,SourceViewer支援這兩種觸發方式。在程式裡使用SourceViewer和使用一般控制項沒有很大的分別,只是SourceViewer
是StyledText的封裝,所以一些操作要通過getTextWidget()完成,如下所示:
//Configure source viewer, add content assistant support
sourceViewer.configure(new SourceViewerConfiguration() {
@Override
public IContentAssistant getContentAssistant(ISourceViewer sourceViewer) {
ContentAssistant assistant = new ContentAssistant();
IContentAssistProcessor cap = new MyContentAssistProcessor();
assistant.setContentAssistProcessor(cap, IDocument.DEFAULT_CONTENT_TYPE);
assistant.setInformationControlCreator(getInformationControlCreator(sourceViewer));
assistant.enableAutoActivation(true);
return assistant;
}
});
現在這個SourceViewer還不能彈出任何提示,因為我們還沒有給它一個SourceViewerConfiguration,後者通過getContentAssistant()負責提供一個IContentAssistant的實現。下面的代碼顯示了如何為SourceViewer設定SourceViewerConfiguration,這個例子裡不論當前文字框裡是什麼內容都彈出一樣的提示選項,在實際應用裡可以根據內容改變選項:
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int offset) {
String content = viewer.getTextWidget().getText();
try {
//Demo options
final String[] options = new String[] { "sum()", "count()", "sort()" };
//Dynamically generate proposal
ArrayList result = new ArrayList();
for (int i = 0; i < options.length; i++) {
CompletionProposal proposal = new CompletionProposal(options[i], offset, 0, options[i].length());
result.add(proposal);
}
return (ICompletionProposal[]) result.toArray(new ICompletionProposal[result.size()]);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public char[] getCompletionProposalAutoActivationCharacters() {
return TRIGGER_TOKENS;
}
上面代碼裡,MyContentAssistProcessor是我們對IContentAssistant介面的實現,它裡面與自動完成有關的是computeCompletionProposals()和getCompletionProposalAutoActivationCharacters()這兩個方法,前者返回的結果數組將作為彈出提示視窗裡的選項,後者返回的字元數組包含了可以觸發快顯視窗的特殊字元。
最後,我們還要支援使用者觸發內容助理,這要求為SourceViewer添加一個監聽器:
sourceViewer.appendVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent event) {
// Check for Alt+/
if (event.stateMask == SWT.ALT && event.character == '/') {
// Check if source viewer is able to perform operation
if (sourceViewer.canDoOperation(SourceViewer.CONTENTASSIST_PROPOSALS))
// Perform operation
sourceViewer.doOperation(SourceViewer.CONTENTASSIST_PROPOSALS);
// Veto this key press to avoid further processing
event.doit = false;
}
}
});
實現後的結果如所示,(範例程式碼下載):
相關參考連結:
為 SWT 應用程式配備內容助理
FAQ How do I add Content Assist to my language editor?
Eclipse Help - Content Assist