Newer
Older
stockTray / stock_new / src / me / bell / TrayUpdate.java
ubt on 25 May 2018 8 KB stock new
package me.bell;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.swing.*;


public class TrayUpdate implements Runnable, ActionListener {

    public static String code; // 股票代码
    public static ArrayList<StockData> list; // 获取的股票数据

    public static StringToImage formatImg = new StringToImage();

    // 停市控制器
    public static boolean isStop = false;
    public static List<SettingData> settingList = new ArrayList<>();

    public TrayUpdate() throws Exception {

        // 先从配置文件取股票代码,
        String file = FileUtil.readTxtFile();
        // 获取配置文件参数
        if (null == file || file.isEmpty()) {
            code = "SZ:000014";
            SettingData data = new SettingData();
            data.setCode("SZ000014");
            createIcon(data);
            settingList.add(data);
        } else {
            StringBuffer sb = new StringBuffer();
            settingList = JSON.parseArray(file, SettingData.class);
            for (int i = 0; i < settingList.size(); i++) {
                String name = settingList.get(i).getCode();
                sb.append(name.substring(0, 2) + ":" + name.substring(2, name.length()) + "|");
                createIcon(settingList.get(i));
            }

            code = sb.toString();
        }
    }

    /**
     * 初始化图标
     */
    private void createIcon(SettingData settingData) throws Exception {
        //菜单初始化
        MenuItem exitItem1 = new MenuItem("Exit");
        MenuItem configItem1 = new MenuItem("Config");
        exitItem1.addActionListener(this);
        configItem1.addActionListener(this);
        exitItem1.setActionCommand("Exit");
        configItem1.setActionCommand("Config");

        MenuItem exitItem2 = new MenuItem("Exit");
        MenuItem configItem2 = new MenuItem("Config");
        exitItem2.addActionListener(this);
        configItem2.addActionListener(this);
        exitItem2.setActionCommand("Exit");
        configItem2.setActionCommand("Config");

        PopupMenu popupMenu1 = new PopupMenu();
        PopupMenu popupMenu2 = new PopupMenu();
        popupMenu1.add(configItem1);
        popupMenu1.add(exitItem1);
        popupMenu2.add(configItem2);
        popupMenu2.add(exitItem2);

        String currentDir = System.getProperty("user.dir");
        Image image = new ImageIcon(currentDir + "/src/me.bell/bg.png").getImage();

        //系统托盘初始化
        TrayIcon trayIcon1 = new TrayIcon(image, null, popupMenu1);
        trayIcon1.setImageAutoSize(true);
        SystemTray tray1 = SystemTray.getSystemTray();
        tray1.add(trayIcon1);
        settingData.setIcon1(trayIcon1);


        TrayIcon trayIcon2 = new TrayIcon(image, null, popupMenu2);
        trayIcon2.setImageAutoSize(true);
        SystemTray tray2 = SystemTray.getSystemTray();
        tray2.add(trayIcon2);
        settingData.setIcon2(trayIcon2);

    }


    @Override
    public void run() {

        // 循环请求网络数据
        while (true) {
            try {
                if (!isStop) {
                    // 返回的股票数据
                    list = HttpUtil.StockHttp(code);

                    // 是否有触发预警
                    checkLimit(list);

					// 下午3点停止
                    SimpleDateFormat sdf = new SimpleDateFormat("HH");
                    String time = sdf.format(new Date());
					if (Integer.parseInt(time)>=15) {
						isStop = true;
					}
                }

                Thread.sleep(2000);
            } catch (Exception e) {
                // 异常时退出程序
                System.exit(0);
            }
        }
    }

    /**
     * 判断是否需要预警
     *
     * @param list
     */
    public static void checkLimit(ArrayList<StockData> list) {
        try {

            for (StockData d1 : list) {
                for (SettingData d2 : settingList) {
                    //比对代码相同的票
                    if (d2.getCode().contains(d1.getCode2()) && !d2.isDialog()) {
                        //上限
                        if (null != d2.getMax() && d1.getPrice().compareTo(d2.getMax()) == 1
                                && d2.getMax().compareTo(new BigDecimal(0))==1) {
                            showLimitDialog(1, d1.getName(), d1.getPrice().toString());
                            d2.setDialog(true);
                        }
                        //下限
                        if (null != d2.getMin() && d1.getPrice().compareTo(d2.getMin()) == -1
                                && d2.getMin().compareTo(new BigDecimal(0))==1) {
                            showLimitDialog(0, d1.getName(), d1.getPrice().toString());
                            d2.setDialog(true);
                        }
                        //浮动(如果未设置,默认大于5%)
                        if ((null != d2.getWarn() && d1.getPercent().abs().compareTo(d2.getWarn().abs()) == 1) ||
                                d1.getPercent().abs().compareTo(new BigDecimal(5)) == 1){
                            showLimitDialog(2, d1.getName(), d1.getPercent().toString());
                            d2.setDialog(true);
                        }

                        //分拆价格显示
                        String[] prices = d1.getPrice().toString().split("\\.");
                        Image img1 = formatImg.StrToImg(prices[1].substring(0, 2), setColor(d1.getEarn()));
                        Image img2 = formatImg.StrToImg(prices[0], setColor(d1.getEarn()));
                        // 设置图片
                        d2.getIcon1().setImage(img1);
                        // 设置悬浮提示
                        d2.getIcon1().setToolTip(getToolTips(d1));
                        d2.getIcon2().setImage(img2);
                        d2.getIcon2().setToolTip(getToolTips(d1));

                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 预警弹窗
     *
     * @param i
     */
    private static void showLimitDialog(int i, String name, String value) {

        final TipWindow tw = new TipWindow(200, 120);
        // tw.setTitle("预警提示");

        JPanel headPan = new JPanel();
        JPanel btnPan = new JPanel();

        JButton update = new JButton("CLOSE");
        JLabel head = new JLabel();
        if (i == 0) {
            head.setForeground(Color.green);
            head.setText("<html>警告! 已到价格下限<br><br> "+name+" " + value + "</html>");
        } else if (i == 1) {
            head.setForeground(Color.red);
            head.setText("<html>恭喜! 已到价格上限<br><br> "+name+" " + value + "</html>");
        } else if (i == 2) {
            head.setForeground(Color.blue);
            head.setText("<html>注意! 股价波动<br><br> "+name+" " + value + "%</html>");
        } else {
            return;
        }

        headPan.add(head);
        btnPan.add(update);

        update.addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                //初始化提醒
//                for (SettingData data:settingList){
//                    data.setDialog(false);
//                }
                tw.close();
            }
        });

        tw.add(headPan, BorderLayout.CENTER);
        tw.add(btnPan, BorderLayout.SOUTH);
        tw.setAlwaysOnTop(true);
        tw.setResizable(false);
        tw.setVisible(true);
        tw.run();

    }


    /**
     * 涨跌判断
     *
     * @param earn
     * @return
     */
    public static int setColor(BigDecimal earn) {

        if (earn.compareTo(new BigDecimal(0))==1){
            return 1;
        } else if (earn.compareTo(new BigDecimal(0))==-1){
            return -1;
        } else {
            return 0;
        }

    }


    /**
     * 获取悬浮提示内容
     *
     * @param data
     * @return
     */
    public static String getToolTips(StockData data) {

        return data.getName() + " " + data.getCode1() + data.getCode2()
                + "    ↑:" + data.getMax() + "    ↓:" + data.getMin() +"    "+ data.getPercent() + "%  ";

    }



    @Override
    public void actionPerformed(ActionEvent e) {
        //菜单响应
        String action = e.getActionCommand();

        if (action.equals("Exit")) {
            System.exit(0);
        }

        if (action.equals("Config")) {
            //打开配置面板
            ConfigGui config = new ConfigGui(settingList);
            config.setVisible(true);
        }
    }
}