Section 3 of IntelliJ IDEA plug-in development: develop toolbar and Tab page to display stock market and K-line

Continue to adhere to the original output, click the blue word to pay attention to me Author: Xiao Fu GeBlog: https://b...
1, Foreword
2, Demand purpose
3, Case development
4, Test verification
5, Summary
6, Series recommendation

Continue to adhere to the original output, click the blue word to pay attention to me

Author: Xiao Fu Ge
Blog: https://bugstack.cn

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

❞ catalogue


  • 1, Foreword

  • 2, Demand purpose

  • 3, Case development

    • 1. Engineering structure

    • 2. tab page form

    • 3. Stock box setting

    • 4. Fill the main panel to the IDEA toolbar

    • 5. Data persistence configuration

    • 6. Stock interface

  • 4, Test verification

    • 1. Allocation of shares

    • 2. Optional stock index

    • 3. K line

  • 5, Summary

  • 6, Series recommendation


1, Foreword

No move, don't write something exciting, you're always not good-looking!

Before, I didn't understand. The technology written is the technical content, and the scene written is the scene analysis. But from the readers' reading, I find that we prefer the combination of technology and scene, especially the shy scenes with technology, although we don't say it.

This chapter is mainly about how to use the toolbar and Tab page to fill the form at the bottom of the IDEA, just like the console in the IDEA. But it seems that it's hard for someone to read it, because it's difficult to find any application scenarios in it only from the technical point of view. Even if you read it, you don't seem to know what this technology can do.

What about it? It's exciting. Don't you like losing money in stocks? Then combine the stock market and K-line display into the IDEA plug-in development. You can let the partners learning plug-ins take a look at the stock when they are tired of writing code, and maybe remind you to throw it out at a critical time!

2, Demand purpose

To be safe, you need to develop stock plug-ins in a more secret corner of the IDEA, so that stock speculators can not forget to buy and sell the stocks they pay attention to when they are nervous about coding CRUD.

In order to solve this problem, we need several technical points, including stock data interface, query object encapsulation, development of form and toolbar at the bottom of IDEA, scheduled task scanning, Swing UI, stock code configuration and saving, form button event monitoring, etc.

Next, we will combine these technical points to solve the actual scenario problems and see how to develop a stock plug-in in IDEA.

3, Case development

1. Engineering structure

guide-idea-plugin-tab
├── .gradle
└── src
├── main
│ └── java
│ └── cn.bugstack.guide.idea.plugin
│ ├── domain
│ │ ├── model
│ │ │ ├── aggregates
│ │ │ │ └── StockResult.java
│ │ │ └── vo
│ │ │ ├── Data.java
│ │ │ ├── GoPicture.java
│ │ │ └── Stock.java
│ │ └── service
│ │ ├── impl
│ │ │ └── StockImpl.java
│ │ └── IStock
│ ├── factory
│ │ └── TabFactory.java
│ ├── infrastructure
│ │ ├── DataSetting.java
│ │ └── DataState.java
│ ├── module
│ │ ├── RefreshBar.java
│ │ ├── SettingBar.java
│ │ └── ViewBars.java
│ └── ui
│ │ ├── ConsoleUI.java
│ │ ├── ConsoleUI.form
│ │ ├── GidConfig.java
│ │ └── GidConfig.form
│ └── Config
├── resources
│ └── META-INF
│ └── plugin.xml
├── build.gradle
└── gradle.properties

Source code: the official account: bugstack wormhole stack reply: idea can download all the IDEA plug-in development source code.

In this IDEA plug-in project, it is mainly divided into five areas:

  • Domain: the domain layer provides data services for querying the stock interface. If you are doing some other tool functions, you can also implement the content of business classes in domain.
  • factory: factory layer, which mainly provides an entry object generated by a tool form to create the form content we add ourselves.
  • infrastructure: the basic layer provides a data storage object. This data object is an operation that can drop the disk. The created class is configured to plugin.xml   Just in. In this way, after we configure the stock code, we can also read the configuration by shutting down and restarting IDEA
  • Module: a module that provides some tool page operations for UI forms. For example, the ViewBars here will be instantiated in TabFactory to display the form you added.
  • ui: this part uses the form generated by automatic dragging in the IDEA, which eliminates the complexity of handwriting. Some simple pages can be dragged directly. This is also a low code!

Next, let's take a look at the implementation process of each core function node. In this process, you can download the code in advance, which will be easier to understand compared with learning.

  1. Implement ToolWindowFactory and develop a form at the bottom to carry the required content
  2. On the left is the side toolbar, which is used to configure self selection and refresh stock index
  3. On the right are two tab pages, which are used to display stock data and K-line chart respectively. The data here needs to be provided through the stock interface

2. tab page form

First, we use the Swing UI function in the IDEA plug-in development to drag out two simple forms. With such a basic structure, we should have pictures in our minds.

2.1 self selected stock configuration window
public class GidConfig implements Configurable {

private JPanel mainPanel;
private JPanel settingPanel;
private JLabel gidLabel;
private JTextField gidTextField;

private ConsoleUI consoleUI;

public GidConfig(ConsoleUI consoleUI){
this.consoleUI = consoleUI;
}

public JTextField getGidTextField() {
return gidTextField;
}

@Override
public void apply() throws ConfigurationException {
List<String> gidList = DataSetting.getInstance().getGids();
gidList.clear();
String[] gids = gidTextField.getText().trim().split(",");
for (String gid : gids) {
gidList.add(gid.trim());
}
//  refresh data
consoleUI.addRows(gidList);
}

}
  • In the java class corresponding to GidConfig, you can get the properties that appear in some forms. When the user clicks the confirm button on this window, we can get the user configured stock code in apply, read it and set the stock data.
2.2 stock display form
public class ConsoleUI {

private JTabbedPane tabbedPane1;
private JPanel one;
private JPanel two;
private JLabel picMin;
private JTable table;
private JLabel picDay;

//  Query data service
private IStock stock = new StockImpl();

private DefaultTableModel defaultTableModel = new DefaultTableModel(new Object[][]{}, new String[]{"shares", "code", "newest", "Rise and fall", "Increase"});

public ConsoleUI() {
//  Initial data
table.setModel(defaultTableModel);
addRows(DataSetting.getInstance().getGids());

//  Add event
table.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
int row = table.getSelectedRow();
Object value = table.getValueAt(row, 1);
GoPicture goPicture = stock.queryGidGoPicture(value.toString());
try {
//  Minute K line
picMin.setSize(545, 300);
picMin.setIcon(new ImageIcon(new URL(goPicture.getMinurl())));

//  Current day K line
picDay.setSize(545, 300);
picDay.setIcon(new ImageIcon(new URL(goPicture.getDayurl())));
} catch (MalformedURLException m) {
m.printStackTrace();
}
}
});
}

public JTabbedPane getPanel() {
return tabbedPane1;
}

public void addRows(List<String> gids) {
//  query
List<Data> dataList = stock.queryPresetStockData(gids);

//  empty
int rowCount = defaultTableModel.getRowCount();
for (int i = 0; i < rowCount; i++) {
defaultTableModel.removeRow(0);
}

//  add to
for (Data data : dataList) {
defaultTableModel.addRow(new String[]);
table.setModel(defaultTableModel);
}
}

}
  • The console UI class corresponding to the window displaying stocks is mainly responsible for rendering and updating data and event operations on each data. When users click a piece of data, they can go to the See the corresponding stock index on the K-line page.

3. Stock box setting

After developing the UI form, we also need to use an inherited implementation class of simpletorwindowpanel to host the settings of toolbars and pages.

3.1 settings - toolbar

cn.bugstack.guide.idea.plugin.module.SettingBar

public class SettingBar extends DumbAwareAction {

private ViewBars panel;

public SettingBar(ViewBars panel) {
super("Allocation stock", "Click to setting", IconLoader.getIcon("/icons/config.svg"));
this.panel = panel;
}

@Override
public void actionPerformed(@NotNull AnActionEvent e) {
ShowSettingsUtil.getInstance().editConfigurable(panel.getProject(), new GidConfig(panel.getConsoleUI()));
}

}
  • The settings toolbar is located at the leftmost position in the custom plug-in panel and is used to set the optional stock code.
  • Through in method Used in actionPerformed The ShowSettingsUtil utility class launches the UI form.
3.2 refresh - toolbar

cn.bugstack.guide.idea.plugin.module.RefreshBar

public class RefreshBar extends DumbAwareAction {

private ViewBars panel;

public RefreshBar(ViewBars panel) {
super("Refresh index", "Click to refresh", IconLoader.getIcon("/icons/refresh.svg"));
this.panel = panel;
}

@Override
public void actionPerformed(@NotNull AnActionEvent e) {
panel.getConsoleUI().addRows(DataSetting.getInstance().getGids());
}

}
  • The refresh toolbar is mainly used to manually trigger the refresh of the latest stock results. The reason for using manual refresh is that this interface has a query number limit. If a scheduled task keeps running, the query limit of 100 times will be used up. However, we are here to reflect the use of technology in the column. By adding multiple setting buttons, it is easier to know how to add
3.3 form filling panel

cn.bugstack.guide.idea.plugin.module.ViewBars

public class ViewBars extends SimpleToolWindowPanel {

private Project project;
private ConsoleUI consoleUI;

public ViewBars(Project project) {
super(false, true);
this.project = project;
consoleUI = new ConsoleUI();

//  Set form sidebar button
DefaultActionGroup group = new DefaultActionGroup();
group.add(new SettingBar(this));
group.add(new RefreshBar(this));

ActionToolbar toolbar = ActionManager.getInstance().createActionToolbar("bar", group, false);
toolbar.setTargetComponent(this);
setToolbar(toolbar.getComponent());

//  add to
JBSplitter splitter = new JBSplitter(false);
splitter.setSplitterProportionKey("main.splitter.key");
splitter.setFirstComponent(consoleUI.getPanel());
splitter.setProportion(0.3f);
setContent(splitter);
}

public Project getProject() {
return project;
}

public ConsoleUI getConsoleUI() {
return consoleUI;
}
}
  • In the filling panel, mainly in our customized plug-ins, add a toolbar on the left and a stock display panel in the rest.
  • You can use this to add settings and refresh buttons in the DefaultActionGroup, and finally populate the Go to the action toolbar and the setting is completed.
  • JBSplitter is a dividing line, and our stock index display panel is filled on the right splitter.setFirstComponent(consoleUI.getPanel())

4. Fill the main panel to the IDEA toolbar

4.1 form factory

cn.bugstack.guide.idea.plugin.factory.TabFactory

public class TabFactory implements ToolWindowFactory {

@Override
public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {
//  forms
ViewBars viewPanel = new ViewBars(project);
//  Gets an instance of the content factory
ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();
//  obtain   ToolWindow   Content displayed
Content content = contentFactory.createContent(viewPanel, "shares", false);
//  set up   ToolWindow   Content displayed
toolWindow.getContentManager().addContent(content, 0);

//  Scheduled tasks, automatically refresh stocks
/* Due to the limitation of daily query times, there are no scheduled tasks here. Users can apply by themselves   https://dashboard.juhe.cn/home
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
viewPanel.getConsoleUI().addRows(DataSetting.getInstance().getGids());
}
}, 3000, 2000);*/
}

}
  • TabFactory mainly includes two parts: one is to fill ViewBars into the whole toolWindow, and the other is the timed task of refreshing stock data that we have commented out.
  • Here, due to the limited query times of the stock interface, the scheduled tasks are commented out, otherwise the available times will be lost.
4.2 configuration form

plugin.xml

<idea-plugin>

<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
<toolWindow id="XUtil"
canCloseContents="true"
anchor="bottom"
factoryClass="cn.bugstack.guide.idea.plugin.factory.TabFactory"
icon="/icons/stock.png"
/>

</extensions>

</idea-plugin>
  • Here we configure the form to the bottom of the entire IDEA interface anchor="bottom" This location is convenient and safe

5. Data persistence configuration

  • When we use IDEA to configure some basic parameters, such as Maven, Gradle, Git, signature information, etc., these configuration information will be saved when closing and restarting IDEA, rather than saying that it will disappear after closing.
  • Then some optional stock code configurations of the plug-in we developed should also be saved, otherwise it cannot be reset every time the IDEA is started. So here we need to use In plugin.xml applicationService is implemented on the configuration The data setting storage class of PersistentStateComponent.
5.1 object data

cn.bugstack.guide.idea.plugin.infrastructure.DataState

public class DataState {

private List<String> gids = new ArrayList<>();

public List<String> getGids() {
return gids;
}

public void setGids(List<String> gids) {
this.gids = gids;
}

}
  • This is the data object class. You can set the properties you need here. Just like gids, it is used to store the user configured stock code collection.
5.2 persistent data

cn.bugstack.guide.idea.plugin.infrastructure.DataSetting

@State(name = "DataSetting",storages = @Storage("plugin.xml"))
public class DataSetting implements PersistentStateComponent<DataState> {

private DataState state = new DataState();

public static DataSetting getInstance() {
return ServiceManager.getService(DataSetting.class);
}

@Nullable
@Override
public DataState getState() {
return state;
}

@Override
public void loadState(@NotNull DataState state) {
this.state = state;
}

public List<String> getGids(){
return state.getGids();
}

}
  • The DataSetting class needs to use the annotation @ State provided by the IDEA plug-in development to configure the persistent object
  • In addition, we need to provide a getInstance method to obtain the data object instance, so we can get the configured object, set it and read the data when we actually use it.
5.3 plugin.xml configuration
<extensions defaultExtensionNs="com.intellij">
<!-- Add your extensions here -->
<applicationService serviceImplementation="cn.bugstack.guide.idea.plugin.infrastructure.DataSetting"/>
</extensions>
  • After creating the data setting class, you need to use the applicationService tag to configure your class into extensions in plugin.xml.

6. Stock interface

6.1 technical investigation
  • No matter what function development, we need to deal with these piecemeal things before we start code development. This process is also called technical research to design and review. Just as we need to query stock information now, we need to find an interface that can provide data query to see how this interface applies for use and what fields the returned object has, and whether it meets our expectations.

  • Here, little brother Fu found an interface for aggregating data, but it can only be called 100 times / day for free. If you have a better one, you can replace it.

  • Interface: http://web.juhe.cn:8080/finance/stock/hs?gid=sz000651&key= Apply by yourself - keys here need to apply by themselves

  • Data:

6.2 service encapsulation

With the stock query interface, you can perform a query and object conversion on the data.

cn.bugstack.guide.idea.plugin.domain.service.impl.StockImpl

public class StockImpl implements IStock {

//  Apply by yourself, stock API, and replace the key [you can call it 100 times a day for free]: https://dashboard.juhe.cn/home/
private final String key = "4bc57728***********f0595";

@Override
public List<Data> queryPresetStockData(List<String> gids) {
List<Data> dataList = new ArrayList<>();
for (String gid : gids) {
StockResult stockResult = JSON.parseObject(HttpUtil.get("http://web.juhe.cn:8080/finance/stock/hs?gid=" + gid + "&key=" + key), StockResult.class);
Stock[] stocks = stockResult.getResult();
for (Stock stock : stocks) {
dataList.add(stock.getData());
}
}
return dataList;
}

}
  • Here, we define data vo objects in the domain layer and provide encapsulation of stock query services. In this way, the caller can directly use this data. If you are a stock query interface provided by other manufacturers, you can also encapsulate and replace it as an interface adaptation layer.

4, Test verification

  • If you don't have a Plugin and a green arrow after downloading the project, you can configure it yourself according to the figure : runIde so you can run.

Operation effect - the exciting time has come. You don't have to worry about the impact of writing code on looking at stocks anymore

1. Allocation of shares

  • First of all, you need to configure the stock codes you pay attention to here. I have configured three I'm optimistic about.

2. Optional stock index

  • After configuration, you can see your self selected stock index. After selecting one, click the K line.
  • When you need to see the latest data, you can click the refresh button on the left.

3. K line

  • Now this is the corresponding K line. Isn't it very fragrant. At present, the nearest K-line and daily K-line are added. You can also expand the graphs of other dimensions.

5, Summary

  • In this chapter, we used to add a slightly more complex page structure in the IDEA form, including sidebars and Tab pages, and need to interact and communicate in these page bodies. In addition, data storage settings are used, which are often used in the development of IDEA plug-ins.
  • Technical practices like this can not only be used to display stock data, but also expand the content that belongs to your actual scene according to your needs. For example, develop a data centralized query plug-in, which can query databases, ES, Redis, etc., or all tool collection pages, which will be more technical value.
  • When you start to actively add the functions you want to some of the source code, frameworks, components and projects you have learned, you really start to learn, otherwise you will forget a content before long.

6, Series recommendation

- END -

Scan the code below, pay attention to the bugstack wormhole stack, learn, grow and make common progress with brother Fu, and be the most expensive Coder in a code field!

  • Reply to [design pattern] and obtain "re learning Java design pattern", which is a practical book of real cases of the Internet. It is extracted from the actual business to learn code design in many scenarios such as transaction, marketing, second kill, middleware and source code.
  • Reply to [Spring column], Get "hand rolling Spring", which is a technical material to understand the core principles, design and implementation of Spring IOC, AOP, circular dependency and so on by taking the reader to write a simplified Spring framework.
  • Reply to the [Manual of facial Sutra] to obtain the manual of facial Sutra  •  Take Dachang Offer ", which is a deep core content of Java. It continues to explain in depth from data structure, algorithm, concurrent programming and JVM system 8. If you understand it, you really understand it.

Hello, I'm little brother Fu. First line Internet java Engineer and architect, developed transaction & marketing, wrote operation & activities, designed middleware, and tossed repeaters and IO boards. He has not only written the Java language, but also engaged in C#, PHP. He is a tosser with active technology.
Wrote a PDF in 2020 Revisiting Java design patterns , the download volume of the whole network is 500000 +, which has helped many students grow up and has published books. Two projects of github in the same year, CodeGuide , itstack-demo-design , continue to dominate the list trend and become a global hot project.
A small volume will be on the shelves in 2021 SpringBoot middleware design and development , 16 Internet middleware scenarios and 30 projects are the only time in the whole network to teach you how to build wheels and write middleware, because such technology is closest to P7, architects and high salaries!

This article is shared with WeChat official account bugstack wormhole stack (bugstack).
In case of infringement, please contact [email protected] Delete.
Article participation“ OSC source creation program ”, you who are reading are welcome to join us and share with us.

22 November 2021, 08:22 | Views: 1718

Add new comment

For adding a comment, please log in
or create account

0 comments