Я пытаюсь разработать плагин eclipse. Я знаю об этом.Разработка плагина Eclipse: как прослушивать события в редакторе Eclipse
В шаблоне пример плагина, когда мы нажмем пункт меню (или кнопку со значком затмения в изображении ниже в данном случае) в тестировании, например затмения, выполнить метод sampleHandler.java выполняется и поп- показанный на изображении ниже.
Я хочу, чтобы вызвать «выполнить» метод всякий раз, когда я нажимаю некоторые клавиши (позволяет сказать, что забой) в редакторе кода вместо нажатия любой пункт меню (или кнопки).
SampleHandler.java
public class SampleHandler extends AbstractHandler {
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(
window.getShell(),
"Sdfsdfsadf",
"Hello, Eclipse world");
return null;
}
}
Я попытался предложения, приведенные в other posts, но я не в состоянии достичь желаемой функциональности.
Согласно моему пониманию из ссылочного пост в строке выше, я попытался ниже код -
package eventlisten.handlers;
import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.texteditor.ITextEditor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.IDocumentListener;
/**
* Our sample handler extends AbstractHandler, an IHandler base class.
* @see org.eclipse.core.commands.IHandler
* @see org.eclipse.core.commands.AbstractHandler
*/
public class SampleHandler extends AbstractHandler {
/**
* The constructor.
*/
public SampleHandler() {
}
/**
* the command has been executed, so extract extract the needed information
* from the application context.
*/
public Object execute(ExecutionEvent event) throws ExecutionException {
IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
MessageDialog.openInformation(window.getShell(),"EventListen","Trying event listen");
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
IEditorPart editor = page.getActiveEditor();
IEditorInput input = editor.getEditorInput();
IDocument document=(((ITextEditor)editor).getDocumentProvider()).getDocument(IDocument.class);
document.addDocumentListener(new IDocumentListener() //**this is line 45**
{
@Override
public void documentAboutToBeChanged(DocumentEvent event) {
// TODO Auto-generated method stub
System.out.println("Hello");
}
@Override
public void documentChanged(DocumentEvent event) {
// TODO Auto-generated method stub
System.out.println("Hello second");
}
});
return null;
}
}
Но после показа всплывающего окна, он бросает исключение -
java.lang.NullPointerException
at eventlisten.handlers.SampleHandler.execute(SampleHandler.java:45)
at org.eclipse.ui.internal.handlers.HandlerProxy.execute(HandlerProxy.java:290)
at org.eclipse.core.commands.Command.executeWithChecks(Command.java:499)
at org.eclipse.core.commands.ParameterizedCommand.executeWithChecks(ParameterizedCommand.java:508)
at org.eclipse.ui.internal.handlers.HandlerService.executeCommand(HandlerService.java:169)
at org.eclipse.ui.internal.handlers.SlaveHandlerService.executeCommand(SlaveHandlerService.java:241)
at org.eclipse.ui.menus.CommandContributionItem.handleWidgetSelection(CommandContributionItem.java:829)
at org.eclipse.ui.menus.CommandContributionItem.access$19(CommandContributionItem.java:815)
at org.eclipse.ui.menus.CommandContributionItem$5.handleEvent(CommandContributionItem.java:805)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1276)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:3562)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3186)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:353)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:180)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:629)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:584)
at org.eclipse.equinox.launcher.Main.run(Main.java:1438)
at org.eclipse.equinox.launcher.Main.main(Main.java:1414)
Может кто-то руководство меня через процесс? Дайте мне знать, если потребуется дополнительная информация.
Вы ссылаетесь на другой вопрос и ответ, но что конкретно вы пытались и какие результаты вы достигли или не смогли достичь? –
Обновлено сообщение. Я даже не знаю, как продолжить использовать код этого сообщения. – User42
Действительно ли вы хотите запускать выполнение каждый раз, когда пользователь нажимает клавишу или только если содержимое изменяется (или это достаточно даже, когда файл сохраняется)? Является ли 'document == null'? Вы можете проверить это, установив точку останова на linek 43, запустите плагин в режиме отладки и запустите строку 43 (F6 или перейдите на панель инструментов), а затем наведите указатель мыши на 'document'. Или вы можете сказать конкретно, какой экземпляр «null»? – bugybunny