Idea包含UI内容的插件开发
- 前言
- 插件效果
- 项目结构
- 配置功能的实现
- 找一个股票接口
- 完成最终的页面
- 配置Plugin.xml
- 源码地址
前言
在这一篇文章中将会做一个包含UI内容的能看股票的插件。
插件效果
首先是在设置中配置股票的编号,如sh000001,sh600519。
接着在侧边栏中有一个叫做Stock Prices的Tab框,点击之后就可以看到设置的这几个股票消息
当点击刷新按钮之后,就会重新刷新数据,上边的最新更新日期也会同步变化。
项目结构
项目结构如下:
- StockSettingsComponent保存了配置页面的样式。
- StockConfigurable是配置页面的配置类,加载了StockSettingsComponent这个组件。
- handler里的是一个OkHttp的单例实现类,以及调用股票接口的处理器,response是接口的返回。
- StockSettingsState中保存的是配置的持久化内容,这个文件会保存在本地。
- StockToolWindow是在侧边栏展示的内容,也就是最终看到的效果。
所有的图都是用javax.swing画的。
配置功能的实现
配置功能要做的事情是把股票编号的配置交给用户自己,首先定义了一个配置的持久化类。
import com.intellij.openapi.components.PersistentStateComponent;
import com.intellij.openapi.components.ServiceManager;
import com.intellij.openapi.components.State;
import com.intellij.openapi.components.Storage;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;/*** 股票配置的持久化类*/
@State(name = "top.codeease.stockwatch.storage.StockSettingsState",storages = @Storage("StockPluginSettings.xml")
)
public class StockSettingsState implements PersistentStateComponent<StockSettingsState> {/*** 默认股票符号,取上证指数*/public String stockSymbol = "sh000001";public static StockSettingsState getInstance() {return ServiceManager.getService(StockSettingsState.class);}@Nullable@Overridepublic StockSettingsState getState() {return this;}@Overridepublic void loadState(@NotNull StockSettingsState state) {this.stockSymbol = state.stockSymbol;}
}
这个持久化文件最终会保存在本地。接着定义一个组件类叫做StockSettingsComponent,就用一个 JPanel 包裹一个 JTextField。
import javax.swing.*;/*** 设置组件类*/
public class StockSettingsComponent {private JPanel panel;private JTextField stockSymbolTextField;public StockSettingsComponent() {panel = new JPanel();stockSymbolTextField = new JTextField(40);panel.add(new JLabel("请输入股票编号(用英文逗号分割):"));panel.add(stockSymbolTextField);}public JPanel getPanel() {return panel;}public String getStockSymbol() {return stockSymbolTextField.getText();}public void setStockSymbol(String stockSymbol) {stockSymbolTextField.setText(stockSymbol);}
}
最后就是一个配置类将上面两个类拼装起来了。
import com.intellij.openapi.options.Configurable;
import org.jetbrains.annotations.Nls;
import org.jetbrains.annotations.Nullable;
import top.codeease.stockwatch.component.StockSettingsComponent;
import top.codeease.stockwatch.storage.StockSettingsState;import javax.swing.*;/*** 股票配置的最终实现*/
public class StockConfigurable implements Configurable {private StockSettingsComponent settingsComponent;@Overridepublic @Nls(capitalization = Nls.Capitalization.Title) String getDisplayName() {return "Stock Plugin";}@Overridepublic @Nullable JComponent createComponent() {settingsComponent = new StockSettingsComponent();return settingsComponent.getPanel();}@Overridepublic boolean isModified() {StockSettingsState settings = StockSettingsState.getInstance();return !settingsComponent.getStockSymbol().equals(settings.stockSymbol);}@Overridepublic void apply() {StockSettingsState settings = StockSettingsState.getInstance();settings.stockSymbol = settingsComponent.getStockSymbol();}@Overridepublic void reset() {StockSettingsState settings = StockSettingsState.getInstance();settingsComponent.setStockSymbol(settings.stockSymbol);}
}
最终要将配置类注册到plugin.xml中。
找一个股票接口
这里以腾讯接口为例:https://qt.gtimg.cn/q=sh000001
点击后拿到的结果如下,不同的数据之间用~分割
v_sh000001="1~上证指数~000001~2974.01~2971.30~2963.85~268992597~0~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~~20240715155911~2.71~0.09~2977.31~2959.13~2974.01/268992597/268733339474~268992597~26873334~0.57~13.32~~2977.31~2959.13~0.61~429130.60~566227.31~0.00~-1~-1~0.88~0~2970.27~~~~~~26873333.9474~0.0000~0~ ~ZS~-0.03~1.76~~~~3322.13~2635.09~-0.69~-1.39~-1.10~4546667906679~~-10.22~-2.77~4546667906679~~~-8.14~-0.05~~CNY~0~~0.00~0";
下面是其中一些关键的参数:
0: 未知
1: 名字
2: 代码
3: 当前价格
4: 昨收
5: 今开
6: 成交量(手)
7: 外盘
8: 内盘
29: 最近逐笔成交
30: 时间
31: 涨跌
32: 涨跌%
33: 最高
34: 最低
35: 价格/成交量(手)/成交额
36: 成交量(手)
37: 成交额(万)
38: 换手率
39: 市盈率
41: 最高
42: 最低
43: 振幅
44: 流通市值
45: 总市值
46: 市净率
47: 涨停价
48: 跌停价
自定义一个接口的返回结构,取想展示的内容:
/*** 股票结果返回*/
@Data
public class GetStockPriceResponse {/*** 股票名称*/private String stockName;/*** 股票编号*/private String stockNo;/*** 当前价格*/private String lastTrade;/*** 涨跌幅*/private String change;/*** 昨收*/private String prevClose;/*** 今开*/private String open;
}
然后编写OkHTTP的单例实现类:
import okhttp3.OkHttpClient;
import java.util.concurrent.TimeUnit;/*** OkHttp模块的单例实现*/
public class OkHttpClientSingleton {private static OkHttpClient instance;private OkHttpClientSingleton() {// 私有构造函数,防止外部实例化}public static OkHttpClient getInstance() {if (instance == null) {synchronized (OkHttpClientSingleton.class) {if (instance == null) {OkHttpClient.Builder builder = new OkHttpClient.Builder();// 设置连接超时builder.connectTimeout(60, TimeUnit.SECONDS);// 设置读取超时builder.readTimeout(60, TimeUnit.SECONDS);// 设置写入超时builder.writeTimeout(60, TimeUnit.SECONDS);// 构建 OkHttpClient 实例instance = builder.build();}}}return instance;}
}
最后编写获取数据以及处理数据的处理器:
/*** 股票价格*/
public class StockPriceHandler {/*** 腾讯的股票API接口*/private String STOCK_API_TX = "https://qt.gtimg.cn/q=";public List<GetStockPriceResponse> fetchStockPrice(String stockSymbol) {OkHttpClient client = OkHttpClientSingleton.getInstance();String url = STOCK_API_TX + stockSymbol;Request request = new Request.Builder().url(url).build();String responseData = "";List<GetStockPriceResponse> stockPriceResponseList = new ArrayList<>();try {Response response = client.newCall(request).execute();responseData = response.body().string();stockPriceResponseList = dealData(responseData);System.out.println(responseData);} catch (IOException e) {e.printStackTrace();}return stockPriceResponseList;}/*** 接口数据处理,获取到腾讯的接口后会拿到这样一串字符串,如:* v_sh000001="1~上证指数~000001~2971.30~2970.39~2965.61~303713014~0~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~0.00~0~~20240712153511~0.91~0.03~2977.14~2963.30~2971.30/303713014/302581575979~303713014~30258158~0.65~13.27~~2977.14~2963.30~0.47~428104.13~563894.26~0.00~-1~-1~1.02~0~2970.97~~~~~~30258157.5979~0.0000~0~ ~ZS~-0.12~0.72~~~~3322.13~2635.09~0.13~-2.02~-2.82~4534435145087~~-16.75~-3.64~4534435145087~~~-8.19~0.01~~CNY~0~~0.00~0";* 以 ~ 进行分割,一些重要的数据* 0: 未知* 1: 名字* 2: 代码* 3: 当前价格* 4: 昨收* 5: 今开* 6: 成交量(手)* 7: 外盘* 8: 内盘* 29: 最近逐笔成交* 30: 时间* 31: 涨跌* 32: 涨跌%* 33: 最高* 34: 最低* 35: 价格/成交量(手)/成交额* 36: 成交量(手)* 37: 成交额(万)* 38: 换手率* 39: 市盈率* 41: 最高* 42: 最低* 43: 振幅* 44: 流通市值* 45: 总市值* 46: 市净率* 47: 涨停价* 48: 跌停价* @param responseData* @return*/private List<GetStockPriceResponse> dealData(String responseData) {List<GetStockPriceResponse> getStockPriceResponseList = new ArrayList<>();// 如果有多个股票号,先通过;进行拆分responseData = responseData.substring(0, responseData.length() - 1);String[] stockArray = responseData.split(";");for (String stockInfo : stockArray) {GetStockPriceResponse response = new GetStockPriceResponse();String[] split = stockInfo.split("~");response.setStockName(split[1]);response.setStockNo(split[2]);response.setLastTrade(split[3]);response.setChange(split[32]);response.setPrevClose(split[4]);response.setOpen(split[5]);getStockPriceResponseList.add(response);}return getStockPriceResponseList;}
}
完成最终的页面
股票页面由一个按钮JButton,一个展示时间的JLabel,以及表格JBTable组成,源码实现如下。
import com.intellij.openapi.project.Project;
import com.intellij.openapi.wm.ToolWindow;
import com.intellij.openapi.wm.ToolWindowFactory;
import com.intellij.ui.content.Content;
import com.intellij.ui.content.ContentFactory;
import com.intellij.ui.table.JBTable;
import org.jetbrains.annotations.NotNull;
import top.codeease.stockwatch.handler.StockPriceHandler;
import top.codeease.stockwatch.response.GetStockPriceResponse;
import top.codeease.stockwatch.storage.StockSettingsState;
import top.codeease.stockwatch.util.DateUtil;import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.List;/*** 股票展示页面*/
public class StockToolWindow implements ToolWindowFactory {private JPanel mainPanel;private JButton refreshButton;private JBTable stockTable;private DefaultTableModel tableModel;private JLabel lastUpdatedLabel;private final String[] columnNames = {"股票名称", "股票编号","当前价格","涨跌%","昨收","今开"};@Overridepublic void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) {mainPanel = new JPanel(new BorderLayout());// 创建按钮JPanel buttonPanel = new JPanel();refreshButton = new JButton("Refresh");lastUpdatedLabel = new JLabel("Last Updated: " + DateUtil.getNowTime());buttonPanel.add(refreshButton);buttonPanel.add(lastUpdatedLabel);// 创建表格Object[][] data = getDataArray();tableModel = new DefaultTableModel(data, columnNames);stockTable = new JBTable(tableModel);// 添加组件到主面板mainPanel.add(buttonPanel, BorderLayout.NORTH);mainPanel.add(new JScrollPane(stockTable), BorderLayout.CENTER);ContentFactory contentFactory = ContentFactory.SERVICE.getInstance();Content content = contentFactory.createContent(mainPanel, "", false);toolWindow.getContentManager().addContent(content);// 添加按钮操作逻辑refreshButton.addActionListener(e -> refreshFetchingStockPrice());}/*** 刷新股票的价格数据*/private void refreshFetchingStockPrice() {Object[][] data = getDataArray();tableModel = new DefaultTableModel(data, columnNames);stockTable.setModel(tableModel);lastUpdatedLabel.setText("Last Updated: " + DateUtil.getNowTime());}/*** 获取表格的数据列* @return*/private Object[][] getDataArray() {String stockSymbol = StockSettingsState.getInstance().stockSymbol;StockPriceHandler handler = new StockPriceHandler();List<GetStockPriceResponse> getStockPriceResponseList = handler.fetchStockPrice(stockSymbol);Object[][] data = new Object[getStockPriceResponseList.size()][];for (int i = 0; i < getStockPriceResponseList.size(); i++) {GetStockPriceResponse stockPriceResponse = getStockPriceResponseList.get(i);Object[] rowData = {stockPriceResponse.getStockName(),stockPriceResponse.getStockNo(),stockPriceResponse.getLastTrade(),stockPriceResponse.getChange(),stockPriceResponse.getPrevClose(),stockPriceResponse.getOpen()};data[i] = rowData;}return data;}
}
配置Plugin.xml
最后配置一下Plugin.xml,在extensions中将需要注册的类注册进去。
<extensions defaultExtensionNs="com.intellij"><!-- Add your extensions here --><applicationService serviceImplementation="top.codeease.stockwatch.storage.StockSettingsState"/><projectConfigurable instance="top.codeease.stockwatch.config.StockConfigurable"/><toolWindow id="Stock Prices" anchor="right" factoryClass="top.codeease.stockwatch.window.StockToolWindow"/>
</extensions>
这样一个股票插件就实现了。
源码地址
参考代码:https://github.com/OliverLiy/StockWatch