idea插件开发(6)-toolWindows
工具窗口指IDEA的子窗口,这些窗口通常沿着主窗口的外边缘有自己的工具栏,包含一个或多个工具窗口按钮,这些按钮激活显示在主 IDE 窗口左侧、底部和右侧的面板。每侧包含两个工具窗口组,主要组和次要组,并且每次只能激活每个组中的一个工具窗口。如图所示:
一、涉及的扩展
-
ToolWindowFactory:工具窗口的扩展类 DumbAware:如果工具窗口的内容需要索引,则要实现此接口; ToolWindowManagerListener:允许监听工具窗口(取消)注册/显示事件
二、plugin.xml配置
<extensions defaultExtensionNs="com.intellij"> <toolWindow id="Sample Calendar" secondary="true" icon="AllIcons.Toolwindows.WebToolWindow" anchor="right" factoryClass="com.zd.ui.CalendarToolWindowFactory"/> </extensions>
-
id:对应于工具窗口按钮上显示的文本,可用绑定资源包; icon:工具窗口按钮上显示的图标,可以使用平台内置的图标,工具类为com.intellij.icons.AllIcons.java,具体的.svg文件存放在app.jar包下的icons文件夹中; secondary:工具窗口显示在主组还是次组; anchor:工具窗口的位置,“左”(默认)、也可以设置“右”或“底”; factoryClass:自定义的实现类
三、示例Java实现
需要注意代码中被注释的内容,也可以通过另一种方式来添加,如果必要的话还可以通过content.dispose()来释放资源。
public class CalendarToolWindowFactory implements ToolWindowFactory, DumbAware { @Override public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { CalendarToolWindowContent toolWindowContent = new CalendarToolWindowContent(toolWindow); Content content = ContentFactory.getInstance().createContent(toolWindowContent.getContentPanel(), "", false); toolWindow.getContentManager().addContent(content); //ToolWindow.getContentManager().addContent(content); //content.dispose(); } @Data private static class CalendarToolWindowContent { private final JPanel contentPanel = new JPanel(); public CalendarToolWindowContent(ToolWindow toolWindow) { contentPanel.setLayout(new FlowLayout()); contentPanel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10)); JLabel currentDate = new JLabel(); final String CALENDAR_ICON_PATH = "/ui/toolWindow/Calendar-icon.png"; currentDate.setIcon(new ImageIcon(Objects.requireNonNull(getClass().getResource(CALENDAR_ICON_PATH)))); contentPanel.add(currentDate); contentPanel.add(createControlsPanel(toolWindow)); } @NotNull private JButton createControlsPanel(ToolWindow toolWindow) { JButton hideToolWindowButton = new JButton("Hide"); hideToolWindowButton.setSize(120, 50); hideToolWindowButton.addActionListener(e -> toolWindow.hide(null)); return hideToolWindowButton; } } }
四、插件效果
可从菜单栏 View-Tool window- Sample Calendar打开插件。