51工具盒子

依楼听风雨
笑看云卷云舒,淡观潮起潮落

写一个看股票的插件,还真有意思

# 前言 {#前言}

在IDEA插件开发系列的上一篇文章中,我介绍了ConvertX插件是如何实现的。因为ConvertX插件没有涉及UI相关的内容,因此在这一篇文章中,我会带大家一起做一个包含UI内容的插件,一个能看股票的插件。

# 插件效果 {#插件效果}

首先是在设置中配置股票的编号,如sh000001,sh600519。

接着在侧边栏中有一个叫做Stock Prices的Tab框,点击之后,设置的这几个股票就出现了

当点击刷新按钮之后,就会重新刷新数据,上边的最新更新日期也会同步变化。

# 源码地址 {#源码地址}

代码已在github开源,可以直接访问,大家觉得有用的点点star哦:https://github.com/OliverLiy/StockWatch

# 项目结构 {#项目结构}

首先还是先看一下项目结构:

从上到下依次介绍:

  • 1、StockSettingsComponent保存了配置页面的样式。
  • 2、StockConfigurable是配置页面的配置类,加载了StockSettingsComponent这个组件。
  • 3、handler里的是一个OkHttp的单例实现类,以及调用股票接口的处理器,response是接口的返回。
  • 4、StockSettingsState中保存的是配置的持久化内容,这个文件会保存在本地。
  • 5、StockToolWindow是在侧边栏展示的内容,也就是最终看到的效果。

所有的图都是用javax.swing画的,如果想实现更加多的功能,可以把这块代码好好看看。

# 配置功能的实现 {#配置功能的实现}

配置功能要做的事情是把股票编号的配置交给用户自己,首先定义了一个配置的持久化类叫做StockSettingsState

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;

/**

  • @author by: 神秘的鱼仔

  • @ClassName: StockSettingsState

  • @Description: 股票配置的持久化类

  • @Date: 2024/7/5 下午4:17 / @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 @Override public StockSettingsState getState() { return this; }

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

这个持久化文件最终会保存在本地。

接着定义一个组件类叫做StockSettingsComponent,就用一个JPanel包裹一个JTextField。

import javax.swing.*;

/**

  • @author by: 神秘的鱼仔

  • @ClassName: StockSettingsComponent

  • @Description: 设置组件类

  • @Date: 2024/7/5 下午4:03 */ 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.*;

/**

  • @author by: 神秘的鱼仔

  • @ClassName: StockConfigurable

  • @Description: 股票配置的最终实现

  • @Date: 2024/7/9 上午10:09 */ public class StockConfigurable implements Configurable { private StockSettingsComponent settingsComponent;

    @Override public @Nls(capitalization = Nls.Capitalization.Title) String getDisplayName() { return "Stock Plugin"; }

    @Override public @Nullable JComponent createComponent() { settingsComponent = new StockSettingsComponent(); return settingsComponent.getPanel(); }

    @Override public boolean isModified() { StockSettingsState settings = StockSettingsState.getInstance(); return !settingsComponent.getStockSymbol().equals(settings.stockSymbol); }

    @Override public void apply() { StockSettingsState settings = StockSettingsState.getInstance(); settings.stockSymbol = settingsComponent.getStockSymbol(); }

    @Override public void reset() { StockSettingsState settings = StockSettingsState.getInstance(); settingsComponent.setStockSymbol(settings.stockSymbol); } }

最终要将配置类注册到plugin.xml中,我们等全部介绍完后一起放进去。

# 找一个股票接口 {#找一个股票接口}

股票接口网上一找一大片,我这里找了个腾讯的接口:https://qt.gtimg.cn/q=sh000001 (opens new window)

点击后拿到的结果长下面这样,不同的数据之间用~分割

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: 跌停价

自定义一个接口的返回结构,只取我想展示的内容:

/**
 * @author by: 神秘的鱼仔
 * @ClassName: GetStockPriceResponse
 * @Description: 股票结果返回
 * @Date: 2024/7/12 下午5:03
 */
@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;

/**

  • @author by: 神秘的鱼仔

  • @ClassName: OkHttpClientSingleton

  • @Description: OkHttp模块的单例实现

  • @Date: 2024/7/12 上午9:52 */ 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;
    

    } }

最后编写获取数据以及处理数据的处理器:

/**
 * @author by: 神秘的鱼仔
 * @ClassName: StockPriceExecutor
 * @Description: 股票价格
 * @Date: 2024/7/12 下午2:41
 */
public class StockPriceHandler {
/**
 * 腾讯的股票API接口
 */
private String STOCK_API_TX = &quot;https://qt.gtimg.cn/q=&quot;;

public List&lt;GetStockPriceResponse&gt; fetchStockPrice(String stockSymbol) {
    OkHttpClient client = OkHttpClientSingleton.getInstance();
    String url = STOCK_API_TX + stockSymbol;
    Request request = new Request.Builder()
            .url(url)
            .build();
    String responseData = &quot;&quot;;
    List&lt;GetStockPriceResponse&gt; stockPriceResponseList = new ArrayList&lt;&gt;();
    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=&quot;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&quot;;
 * 以 ~ 进行分割,一些重要的数据
 *  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&lt;GetStockPriceResponse&gt; dealData(String responseData) {
    List&lt;GetStockPriceResponse&gt; getStockPriceResponseList = new ArrayList&lt;&gt;();
    // 如果有多个股票号,先通过;进行拆分
    responseData = responseData.substring(0, responseData.length() - 1);
    String[] stockArray = responseData.split(&quot;;&quot;);
    for (String stockInfo : stockArray) {
        GetStockPriceResponse response = new GetStockPriceResponse();
        String[] split = stockInfo.split(&quot;~&quot;);
        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;

/**

  • @author by: 神秘的鱼仔

  • @ClassName: StockToolWindow

  • @Description: 股票展示页面

  • @Date: 2024/7/11 下午11:04 */ public class StockToolWindow implements ToolWindowFactory { private JPanel mainPanel; private JButton refreshButton; private JBTable stockTable; private DefaultTableModel tableModel; private JLabel lastUpdatedLabel; private final String[] columnNames = {"股票名称", "股票编号","当前价格","涨跌%","昨收","今开"};

    @Override public void createToolWindowContent(@NotNull Project project, @NotNull ToolWindow toolWindow) { mainPanel = new JPanel(new BorderLayout());

     // 创建按钮
     JPanel buttonPanel = new JPanel();
     refreshButton = new JButton(&quot;Refresh&quot;);
     lastUpdatedLabel = new JLabel(&quot;Last Updated: &quot; + 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, &quot;&quot;, false);
     toolWindow.getContentManager().addContent(content);
    
     // 添加按钮操作逻辑
     refreshButton.addActionListener(e -&gt; 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}

最后配置一下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>

这样一个股票插件就实现了。

# 总结 {#总结}

在这一期的文章中,我们实现了一个股票的插件,这个系列接下来还会持续更新,大家可以持续关注哦。

赞(4)
未经允许不得转载:工具盒子 » 写一个看股票的插件,还真有意思