【Java练习】文本处理:实时股价

需求

可以查询股票当前价格。
用户可以设定数据刷新频率,程序会用绿色和红色的箭头表示股价走势。

思路

这个重点主要是定时访问接口,然后定时可以设置,用Timer可以实现。
GPT生成的代码,增加了设置属性方法,方便填充KEY

实现

由于有API访问,因此需要引入json转换的依赖

        <dependency>
            <groupId>org.json</groupId>
            <artifactId>json</artifactId>
            <version>20210307</version>
        </dependency>

public class StockPriceTracker extends JFrame {
    private JLabel priceLabel;
    private JLabel trendLabel;
    private JTextField symbolField;
    private JTextField frequencyField;
    private Timer timer;
    private double lastPrice = -1.0;
    private String urlPrefix;
    private String urlSuffix;
    private String apiKey;

    public StockPriceTracker(){
        setTitle("Stock Price Tracker");
        setSize(400, 200);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLayout(new GridLayout(4, 2));

        add(new JLabel("Stock Symbol:"));
        symbolField = new JTextField();
        add(symbolField);

        add(new JLabel("Refresh Frequency (seconds):"));
        frequencyField = new JTextField();
        add(frequencyField);

        priceLabel = new JLabel("Price: ");
        add(priceLabel);

        trendLabel = new JLabel();
        add(trendLabel);

        JButton startButton = new JButton("Start");
        startButton.addActionListener(e -> startTracking());

        JButton stopButton = new JButton("Stop");
        stopButton.addActionListener(e -> stopTracking());

        add(stopButton);
        add(startButton);

        urlPrefix = "https://www.alphavantage.co/query?function=GLOBAL_QUOTE&symbol=";
        urlSuffix = "&apikey=";
        apiKey = "YOUR_API_KEY";
    }

    public void setProperties(String key){
        apiKey = key;
    }

    public void setProperties(String prefix, String suffix, String key){
        urlPrefix = prefix;
        urlSuffix = suffix;
        apiKey = key;
    }

    private void startTracking() {
        if(timer != null){
            timer.stop();
        }

        int frequency = Integer.parseInt(frequencyField.getText()) * 1000;
        timer = new Timer(frequency, e -> updatePrice());
        timer.start();

    }

    private void stopTracking() {
        if(timer != null){
            timer.stop();
        }
    }

    private void updatePrice(){
        String symbol = symbolField.getText();
        String urlString = urlPrefix + symbol + urlSuffix + apiKey;
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");

            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String inputLine;
            StringBuilder content = new StringBuilder();
            while ((inputLine = reader.readLine()) != null){
                content.append(inputLine);
            }
            reader.close();
            connection.disconnect();

            JSONObject jsonObject = new JSONObject(content.toString());
            double price = jsonObject.getJSONObject("Global Quote").getDouble("05. price");

            SwingUtilities.invokeLater(() -> {
                priceLabel.setText("Price:" + price);
                if(lastPrice != -1){
                    if(price > lastPrice){
                        trendLabel.setText("↑");
                        trendLabel.setForeground(Color.GREEN);
                    }else if(price < lastPrice){
                        trendLabel.setText("↓");
                        trendLabel.setForeground(Color.RED);
                    }else{
                        trendLabel.setText("→");
                        trendLabel.setForeground(Color.BLACK);
                    }
                }
                lastPrice = price;
            });

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }

    public static void main(String[] args) {
        String Key = "FEYTUMTVFTFBW8T0";
        SwingUtilities.invokeLater(() -> {

            StockPriceTracker tracker = new StockPriceTracker();
            tracker.setProperties(Key);
            tracker.setVisible(true);
        });
    }

拓展

文本处理这个频道有不少API访问的代码段,所以这里的API访问可以封装到工具类里,比如:

public class ApiUtils {

    public static String getApiResponse(String questUrl) throws Exception {
        URL url = new URL(questUrl);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");

        BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
        String line;
        StringBuilder content = new StringBuilder();
        while((line = reader.readLine()) != null){
            content.append(line);
        }
        reader.close();
        connection.disconnect();
        return content.toString();
    }
}

当然了,用其它API的话记得注意修改json转义位置,请求方式这些,总的来说这个代码示例成分偏多,毕竟gpt生成的,需求也不难

  • 11
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值