8
头图

Author: Xiao Fu Ge
Blog: https://bugstack.cn
Original: https://mp.weixin.qq.com/s/R8qvoSNyedVM95Ty8sbhgg

Precipitate, share, and grow, so that you and others can gain something! 😄

1. Description

is in the wrong direction, efforts were in vain!

There are always people who get the demand for the product and start to work in a hurry. Anyway, they are too lazy to think about what will happen in the development, how many people will use it after it goes online, let it be three or seventy-one, first stack up the code and take a look, anyway, it can run. No matter the code or you!

In fact, many times before writing code, you need to do technical research, architecture design, module layering, data structure, detailed analysis, program review, etc., compared with the guy 3721, it seems to be a bit slow. But this seemingly slow process can solve many common and troublesome problems in the future, such as product requirement iteration, business process changes, code logic changes, and online exception troubleshooting. Although it seems slow, the process of building up a tree is like laying a foundation. There must be a stable foundation to build the entire building. high-rise building rises on the ground, do not build a high platform on the floating sand

2. Purpose of demand

If you need to develop a plug-in with a custom function, whether it is processing code, auxiliary ORM generation, log information recording, etc., you will need to configure the function of a plug-in to initialize and display the corresponding function in the right column of the entire IDEA form. Or the bottom bar, so as to meet the basic needs of a plug-in.

Then you need File -> Settings , and develop your own ToolWindow and embed it in IDEA (left, right, bottom). The development of the form here needs to use Swing, but it is currently in Developing such a function in IDEA only needs to drag and drop the form, which is quite easy.

So next, we take a scene of fishing and reading in IDEA as a case to learn how to configure the window and read the window.

Three, case development

1. Engineering structure

guide-idea-plugin-tool-window
├── .gradle
└── src
    ├── main
    │   └── java
    │       └── cn.bugstack.guide.idea.plugin 
    │           └── factory
    │           │    ├── ReadFactory.java 
    │           │    └── SettingFactory.java
    │           └── ui
    │           │    ├── ReadUI.java 
    │           │    ├── ReadUI.form
    │           │    ├── SettingUI.java  
    │           │    └── SettingUI.form
    │           └── Config    
    ├── resources
    │   └── META-INF
    │       └── plugin.xml 
    ├── build.gradle  
    └── gradle.properties
  • source code acquisition : #public number: bugstack wormhole stack reply: idea can download all IDEA plug-in development source code

This project mainly involves two parts, one is the configuration form and the other is the reading form in the factory, and the two sets of UI implementations are corresponding to it. Finally, the implementation of the factory class is configured to be used in plugin.xml, and at the same time, the position and icon of the form are controlled in plugin.xml.

2. Create a UI form

2.1 How to create

New -> Swing UI Designer -> GUI Form

  • The main ways to create forms in Java are AWT, Swing, and JavaFx. Since IDEA uses Swing for development, the compatibility of creating Swing forms here will be better.
  • Then the creation of the Swing form here can be your own handwritten form structure, or you can use the visual drag-and-drop GUI Form. If your form is not complicated, in fact, the drag-and-drop method can satisfy the use.

2.2 Configuration page form

public class SettingUI {

    private JPanel mainPanel;
    private JPanel settingPanel;
    private JLabel urlLabel;
    private JTextField urlTextField;
    private JButton urlBtn;

    public SettingUI() {
        // 给按钮添加一个选择文件的事件
        urlBtn.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            fileChooser.setFileSelectionMode(JFileChooser.FILES_ONLY);
            fileChooser.showOpenDialog(settingPanel);
            File file = fileChooser.getSelectedFile();
            urlTextField.setText(file.getPath());
        });
    }

    public JComponent getComponent() {
        return mainPanel;
    }

    public JTextField getUrlTextField() {
        return urlTextField;
    }
}

  • The configuration page form mainly provides the choice of article path, the labels that need to be used here include: JLabel, JTextField, JButton
  • After the GUI Form is used to create the form, such a visual page will appear. You can drag various labels to the middle panel on the right, and set the display name and attribute name on the left.
  • In the end, the code label code here will be displayed in SettingUI.java , and the rendered content will be hidden. This method is also more convenient to control the addition of some custom content, such as events and new forms, etc.
  • In addition, in SettingUI.java , we need to add a button event in the constructor to open the file selector, and set the file we need to open to urlTextField .

2.3 Read page form

public class ReadUI {

    private JPanel mainPanel;
    private JTextPane textContent;

    public JComponent getComponent() {
        return mainPanel;
    }

    public JTextPane getTextContent() {
        return textContent;
    }

}

  • The creation of the form is the same as the form of the configuration page, which is also used to display the contents of the path file by dragging and dropping it into the panel.
  • You can add some other buttons as appropriate, such as page turning, scroll bar, word count display, etc.

3. ToolWindow Tool Box

In order to put our own reading form into the right sidebar of the entire IDEA, we need to create an ToolWindowFactory , and configure the implementation class in plugin.xml

public class ReadFactory implements ToolWindowFactory {

    private ReadUI readUI = new ReadUI();

    @Override
    public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
        // 获取内容工厂的实例
        ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
        // 获取 ToolWindow 显示的内容
        Content content = contentFactory.createContent(readUI.getComponent(), "", false);
        // 设置 ToolWindow 显示的内容
        toolWindow.getContentManager().addContent(content);
        // 全局使用
        Config.readUI = readUI;
    }

}
  • The interface method ToolWindowFactory#createToolWindowContent is a method that needs to be implemented by your own tool box class. In this createToolWindowContent method, instantiate your own form ReadUI and fill it in.
  • The subsidy for adding a form mainly depends on ContentFactory.SERVICE.getInstance() create a ContentFactory and finally use toolWindow to add a form to display the UI.
  • Here we additionally added a global property Config.readUI which is for the subsequent use of this UI in the configuration form to set the file content.

4. Configurable configuration box

public class SettingFactory implements SearchableConfigurable {

    private SettingUI settingUI = new SettingUI();

    @Override
    public @NotNull String getId() {
        return "test.id";
    }

    @Override
    public @Nls(capitalization = Nls.Capitalization.Title) String getDisplayName() {
        return "test-config";
    }

    @Override
    public @Nullable JComponent createComponent() {
        return settingUI.getComponent();
    }

    @Override
    public boolean isModified() {
        return true;
    }

    @Override
    public void apply() throws ConfigurationException {
        String url = settingUI.getUrlTextField().getText();
        // 设置文本信息
        try {
            File file = new File(url);
            RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r");
            randomAccessFile.seek(0);

            byte[] bytes = new byte[1024 * 1024];
            int readSize = randomAccessFile.read(bytes);

            byte[] copy = new byte[readSize];
            System.arraycopy(bytes, 0, copy, 0, readSize);

            String str = new String(copy, StandardCharsets.UTF_8);

            // 设置内容
            Config.readUI.getTextContent().setText(str);

        } catch (Exception ignore) {
        }
    }

}
  • There are many ways to implement the SearchableConfigurable interface, including: getId, getDisplayName, createComponent , isModified, apply which are mainly used to write logic implementations are createComponent and apply
  • The createComponent method is mainly to provide the UI panel created by ourselves to JComponent
  • apply is an event. This method will be triggered when we click OK and Finish to complete the configuration. In this method, we get the URL address of the RandomAccessFile to read and parse the file, and finally display the content of the file in the reading form Config.readUI.getTextContent().setText(str);

5. Configure plugin.xml

<extensions defaultExtensionNs="com.intellij">
    <!-- Add your extensions here -->
    <!-- 配置 File -> Settings -> Tools -->
    <projectConfigurable groupId="tools" displayName="My Test Config" id="test.id"
                         instance="cn.bugstack.guide.idea.plugin.factory.SettingFactory"/>
                         
    <!-- 窗体 (IDEA 界面右侧) -->
    <toolWindow id="Read-Book" secondary="false" anchor="right" icon="/icons/logo.png"
                factoryClass="cn.bugstack.guide.idea.plugin.factory.ReadFactory"/>
</extensions>
  • The main configuration content in plugin.xml this time is projectConfigurable and toolWindow. In addition, an icon logo is added to toolWindow. After the configuration is completed, the form we added can be displayed on the IDEA page.

Fourth, plug-in test

  • Start the plug-in through Plugin, this time will open a new IDEA form, in this new form you can see the functions we added.

Configuration file path

  • Click the select button, select your file location, and click OK after selecting

View display file

  • After confirming the file path, you can see your file display content in the right column. expanding? It is suitable for you to fish! ?

Five, summary

  • Learn to customize the development of the UI, fill the UI into the IDEA form that needs to be placed, and add functions to the form. In fact, it mainly includes three aspects: Swing UI, Factory implementation class, and plugin configuration.
  • In the plugin configuration, it mainly includes the form ID, location, icon icon, and the corresponding implementation class. If you do not add these, the form information cannot be displayed normally.
  • In addition, you can use this case as the basis to add the functions you want to complete, such as making this fish reading function more complete, supporting different types of files, even PDF reading, and books you want to read.

Sixth, series recommendation


小傅哥
4.7k 声望28.4k 粉丝

CodeGuide | 程序员编码指南 - 原创文章、案例源码、资料书籍、简历模版等下载。