1.創建Plugin工程
如果Module SDK中沒有可選的SDK,那么點擊New新添加一個SDK,目錄就選擇Intellij的安裝位置即可。
創建出的Plugin項目結構很簡單,只是在META-INF下多了一個plugin.xml配置文件,后文會介紹到它的用處。
2.讓插件Say哈嘍
2.1添加Component
在src目錄上Alt+Insert,可以看到New對話框中列出有三種組件,分別對應三種級別:Application、Project、Module Component。
這里我們選擇Application Component作為實例,在彈出框中輸入一個名字例如MyComponent,這樣一個組件就創建出來了。
然后在MyComponent中添加一個SayHello的方法,其他方法暫不實現,源代碼如下所示:
<code>
packagecom.cdai.plugin.rapidg;
importcom.intellij.openapi.components.ApplicationComponent;
importcom.intellij.openapi.ui.Messages;
importorg.jetbrains.annotations.NotNull;
/**
*?My?Component
*?User:?cdai
*?Date:?13-11-4
*?Time:?上午10:08
*/
publicclassMyComponentimplementsApplicationComponent?{
publicMyComponent()?{
}
publicvoidinitComponent()?{
//?TODO:?insert?component?initialization?logic?here
}
publicvoiddisposeComponent()?{
//?TODO:?insert?component?disposal?logic?here
}
@NotNull
publicString?getComponentName()?{
return"MyComponent";
}
publicvoidsayHello()?{
//?Show?dialog?with?message
Messages.showMessageDialog(
"Hello?World!",
"Sample",
Messages.getInformationIcon()
);
}
}
</code>
## 螺絲刀積分iOS大姐夫
2.2添加Action
現在需要添加一個Action讓使用我們插件的用戶可以通過菜單或其他方式點擊到插件。
Action主要工作是創建一個Application和MyComponent對象,代碼如下:
packagecom.cdai.plugin.rapidg;
importcom.intellij.openapi.actionSystem.AnAction;
importcom.intellij.openapi.actionSystem.AnActionEvent;
importcom.intellij.openapi.application.Application;
importcom.intellij.openapi.application.ApplicationManager;
/**
*?Say?Hello?Action
*?User:?cdai
*?Date:?13-11-4
*?Time:?上午10:16
*/
publicclassSayHelloActionextendsAnAction?{
@Override
publicvoidactionPerformed(AnActionEvent?e)?{
Application?application?=?ApplicationManager.getApplication();
MyComponent?myComponent?=?application.getComponent(MyComponent.class);
myComponent.sayHello();
}
}
2.3配置文件
其實前面兩步新建Component和Action的同時,IDEA在幫我們自動將它們注冊到META-INF/plugin.xml中。
我們剛才添加的Application Component和Action會在結點下,plugin.xml最終是下面的樣子:
com.cdai.plugin.rapidg
CDai's?Rapid?Generator?Plugin
1.0
http://www.yourcompany.com">CDai
Enter?short?description?for?your?plugin?here.
most?HTML?tags?may?be?used
]]>
Add?change?notes?here.
most?HTML?tags?may?be?used
]]>
on?how?to?target?different?products?-->
com.intellij.modules.lang
-->
com.cdai.plugin.rapidg.MyComponent
3.運行調試
打開Run/Debug配置對話框,新加一個Plugin類型的,Use classpath of module選擇剛才的示例項目。
運行起來就會發現,原來會啟動一個新的Intellij IDEA實例,重新走一遍啟動配置過程,可以看到插件的名字就是plugin.xml中中的值。
我們可以只選中我們剛開發的插件,忽略掉其他的。現在通過Window->Say Hello!就可以觸發我們的插件了,效果就是會彈出個對話框。