[英]Java : how to get the active editor in a thread?
My problem is the following one : I am working with 2 plugins : let's call them A and B. 我的问题是以下一个:我正在使用2个插件:称它们为A和B。
When I start the application, A starts B and gives him a parameter : the current ActiveEditor. 当我启动应用程序时,A启动B并给他一个参数:当前的ActiveEditor。 B can now perform some actions on the current editor. B现在可以在当前编辑器上执行某些操作。 Everything is fine for this point. 对于这一点,一切都很好。
However, the parameter is given only when A is instantiated, so if the current editor changes, B is not aware of the change. 但是,仅在实例化A时才给出参数,因此,如果当前编辑器发生更改,则B不会知道更改。
I tried to use a Thread, started by A, getting the active editor every two seconds and setting it into B. Problem : NullPointerException every time => 我尝试使用由A启动的线程,每两秒钟获取活动的编辑器并将其设置为B。问题:每次NullPointerException =>
java.lang.NullPointerException: while trying to invoke the method org.eclipse.ui.IWorkbenchWindow.getActivePage() of a null object returned from org.eclipse.ui.IWorkbench.getActiveWorkbenchWindow()
at com.highdeal.tests.cortex.eclipse.RefreshThread.run(RefreshThread.java:14)
Here is the code of the thread started by the plugin A : 这是由插件A启动的线程的代码:
public class RefreshThread extends Thread {
public void run(){
while (true){
try{
Thread.sleep(1000);
IEditorPart iep = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
new SampleAction(iep);
} catch (Exception e){
e.printStackTrace();
}
}
}
} }
When I migrate the following piece of code into the constructor of the Plugin A, it works correctly : 当我将以下代码迁移到插件A的构造函数中时,它可以正常工作:
IEditorPart iep = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
new SampleAction(iep);
Thanks for reading. 谢谢阅读。 Ask me if you need further explanations. 问我是否需要进一步的解释。
PlatformUI.getWorkbench().getActiveWorkbenchWindow()
always returns null
when it is called from a background thread (that is a thread which is not the UI thread). 从后台线程(不是UI线程的线程)调用PlatformUI.getWorkbench().getActiveWorkbenchWindow()
始终返回null
。
A better way to do this is to use IPartListener
to listen for the active part being changed. 一种更好的方法是使用IPartListener
侦听要更改的活动零件。
IWorkbenchWindow window = PlatformUI.getWorkbench().getActiveWorkbenchWindow();
window.getPartService().addPartListener(part listener);
(must be run in the UI thread). (必须在UI线程中运行)。
The part listener will be told about each part being activated and you can check if this is a new editor. 部件侦听器将被告知每个部件已被激活,您可以检查它是否是新的编辑器。
要在其他线程而不是UIThread中运行UI代码,请使用UIThreadSynchronizer或Display.syncExec()\\ asyncExec()调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.