Java | 使用Java Swing做的时间戳转换和JSON格式化的桌面程序

引言

内网开发以后一些在线的工具都用不了了,时间戳互转和JSON还是经常用到的,因此只能自己用Swing写一个单机版的自己用用。本来打算用C++ QT做的,后来发现QT安装包足足有2G,我自己不喜欢在电脑上装太多的开发工具(其实电脑里好多都是绿色版的),而且使用C++ 开发速度相比较也会慢一点,再加上对java比较熟悉,也想过用Elctron,想想还是Java swing写的方便一点。于是在周末随手做好了。

代码

Tools

public class Tools {
    
    
    public static void main(String[] args) {
    
    
        new MyFrame("秋天的第一杯奶茶");
    }
}

MyFrame

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.io.IOException;

public class MyFrame extends JFrame {
    
    
    Container contentPane = this.getContentPane();
    TimePanel timePanel = new TimePanel();
    JsonPanel jsonPanel = new JsonPanel();

    public MyFrame(String title) {
    
    
        // 设置软件图标
        Image image;
        try {
    
    
            image = ImageIO.read(this.getClass().getResource("/MilkTea.png"));
            this.setIconImage(image);
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        JTabbedPane jTabbedPane = new JTabbedPane();
        jTabbedPane.setBackground(new Color(255, 255, 255));
        jTabbedPane.setFont(new Font("宋体", Font.BOLD, 20));
        jTabbedPane.add("时间戳转换", timePanel);
        jTabbedPane.add("JSON格式化", jsonPanel);
        contentPane.add(jTabbedPane);
        this.setTitle(title);
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension dimension = toolkit.getScreenSize();
        this.setBounds((dimension.width - 1125) / 2, (dimension.height - 900) / 2, 1125, 900);
        this.setMinimumSize(new Dimension(1000, 900));
        this.setResizable(true);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setVisible(true);
    }
}

TimePanel

import javax.swing.*;
import java.awt.*;
import java.text.ParseException;
import java.text.SimpleDateFormat;

public class TimePanel extends Panel {
    
    
    JLabel jLabel1 = new JLabel("时间戳:");
    JLabel jLabel2 = new JLabel("北京时间:");
    JButton jButton1 = new JButton("转换 >>");
    Choice choice1 = new Choice();
    JLabel jLabel3 = new JLabel("北京时间:");
    JLabel jLabel4 = new JLabel("时间戳:");
    JButton jButton2 = new JButton("转换 >>");
    Choice choice2 = new Choice();
    JTextField jTextField1 = new JTextField(20);
    JTextField jTextField2 = new JTextField(20);
    JTextField jTextField3 = new JTextField(20);
    JTextField jTextField4 = new JTextField(20);

    JLabel jLabel5 = new JLabel("当前时间戳(13位):");
    JLabel jLabel6 = new JLabel("当前北京时间:");
    JTextField jTextField5 = new JTextField(20);
    JTextField jTextField6 = new JTextField(20);
    JButton jButton3 = new JButton("刷 新");

    Panel panel1 = new Panel();
    Panel panel2 = new Panel();
    Panel panel3 = new Panel();

    final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyy-MM-dd HH:mm:ss");

    public TimePanel() {
    
    
        GridLayout gridLayout = new GridLayout(3, 1);
        this.setLayout(gridLayout);

        // panel3当前日期和时间戳
        panel3.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 50));
        jLabel5.setFont(new Font("宋体", Font.BOLD, 20));
        panel3.add(jLabel5);
        jTextField5.setFont(new Font("宋体", Font.BOLD, 20));
        panel3.add(jTextField5);
        jLabel6.setFont(new Font("宋体", Font.BOLD, 20));
        panel3.add(jLabel6);
        jTextField6.setFont(new Font("宋体", Font.BOLD, 20));
        panel3.add(jTextField6);
        jButton3.addActionListener(e -> new Thread(() -> {
    
    
            jTextField5.setText(String.valueOf(System.currentTimeMillis()));
            jTextField6.setText(simpleDateFormat.format(System.currentTimeMillis()));
        }).start());
        jTextField5.setText(String.valueOf(System.currentTimeMillis()));
        jTextField6.setText(simpleDateFormat.format(System.currentTimeMillis()));
        jButton3.setFont(new Font("宋体", Font.BOLD, 20));
        panel3.add(jButton3);
        this.add(panel3);

        // panel1将时间戳转换为时间
        panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        jLabel1.setFont(new Font("宋体", Font.BOLD, 20));
        panel1.add(jLabel1);
        jTextField1.setFont(new Font("宋体", Font.BOLD, 20));
        panel1.add(jTextField1);
        choice1.setFont(new Font("宋体", Font.BOLD, 20));
        choice1.add("毫秒(ms)");
        choice1.add("秒(s)");
        panel1.add(choice1);
        jButton1.setFont(new Font("宋体", Font.BOLD, 20));
        panel1.add(jButton1);
        jLabel2.setFont(new Font("宋体", Font.BOLD, 20));
        panel1.add(jLabel2);
        jTextField2.setFont(new Font("宋体", Font.BOLD, 20));
        panel1.add(jTextField2);
        this.add(panel1);

        jButton1.addActionListener(e -> {
    
    
            if ("".equals(jTextField1.getText())) {
    
    
                JOptionPane.showMessageDialog(TimePanel.this, "请输入日期");
                return;
            }
            int index = choice1.getSelectedIndex();
            String format = "";
            if (index == 0) {
    
    
                try {
    
    
                    format = simpleDateFormat.format(Long.parseLong(jTextField1.getText()));
                } catch (Exception ex) {
    
    
                    JOptionPane.showMessageDialog(TimePanel.this, "时间戳格式错误!");
                    return;
                }
            }
            if (index == 1) {
    
    
                try {
    
    
                    format = simpleDateFormat.format(Long.parseLong(jTextField1.getText()) * 1000);
                } catch (Exception ex) {
    
    
                    JOptionPane.showMessageDialog(TimePanel.this, "时间戳格式错误!");
                    return;
                }
            }
            jTextField2.setText(format);
        });

        // panel2将时间转换为时间戳
        panel2.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));
        jLabel3.setFont(new Font("宋体", Font.BOLD, 20));
        panel2.add(jLabel3);
        jTextField3.setFont(new Font("宋体", Font.BOLD, 20));
        panel2.add(jTextField3);
        jButton2.setFont(new Font("宋体", Font.BOLD, 20));
        panel2.add(jButton2);
        choice2.setFont(new Font("宋体", Font.BOLD, 20));
        choice2.add("毫秒(ms)");
        choice2.add("秒(s)");
        panel2.add(choice2);
        jLabel4.setFont(new Font("宋体", Font.BOLD, 20));
        panel2.add(jLabel4);
        jTextField4.setFont(new Font("宋体", Font.BOLD, 20));
        panel2.add(jTextField4);
        this.add(panel2);
        jButton2.addActionListener(e -> {
    
    
            if ("".equals(jTextField3.getText())) {
    
    
                JOptionPane.showMessageDialog(TimePanel.this, "请输入日期");
                return;
            }
            int index = choice2.getSelectedIndex();
            String format = "";
            if (index == 0) {
    
    
                try {
    
    
                    format = String.valueOf(simpleDateFormat.parse(jTextField3.getText()).getTime());
                } catch (ParseException ex) {
    
    
                    JOptionPane.showMessageDialog(TimePanel.this, "日期格式错误!");
                    return;
                }
            }
            if (index == 1) {
    
    
                try {
    
    
                    format = String.valueOf(simpleDateFormat.parse(jTextField3.getText()).getTime() / 1000);
                } catch (ParseException ex) {
    
    
                    JOptionPane.showMessageDialog(TimePanel.this, "日期格式错误!");
                    return;
                }
            }
            jTextField4.setText(format);
        });
    }
}

JsonPanel

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JsonPanel extends Panel {
    
    
    JTextArea jTextArea1 = new JTextArea(42, 35);
    JTextArea jTextArea2 = new JTextArea(42, 65);
    JButton jButton = new JButton("转换 >>");
    JsonFormatUtil jsonFormatUtil = new JsonFormatUtil();

    public JsonPanel() {
    
    
        this.setLayout(new FlowLayout(FlowLayout.CENTER, 10, 10));

        final JScrollPane jScrollPane1 = new JScrollPane(jTextArea1);
        //设置矩形大小.参数依次为(矩形左上角横坐标x,矩形左上角纵坐标y,矩形长度,矩形宽度)
        jScrollPane1.setBackground(new Color(255, 251, 240));
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
        jScrollPane1.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jTextArea1.setFont(new Font("Consolas", Font.PLAIN, 15));
        this.add(jScrollPane1);

        jButton.setFont(new Font("宋体", Font.BOLD, 20));
        this.add(jButton);
        jButton.addActionListener(e -> {
    
    
            if ("".equals(jTextArea1.getText())) {
    
    
                JOptionPane.showMessageDialog(JsonPanel.this, "请输入json字符串");
                return;
            }
            String json = jsonFormatUtil.formatJson(jTextArea1.getText());
            jTextArea2.setText(json);
        });

        JScrollPane jScrollPane2 = new JScrollPane(jTextArea2);
        //设置矩形大小.参数依次为(矩形左上角横坐标x,矩形左上角纵坐标y,矩形长度,矩形宽度)
        jScrollPane2.setBackground(new Color(255, 251, 240));
        //默认的设置是超过文本框才会显示滚动条,以下设置让滚动条一直显示
        jScrollPane2.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
        jTextArea2.setFont(new Font("Consolas", Font.PLAIN, 15));
        this.add(jScrollPane2);
    }
}

JsonFormatUtil

public class JsonFormatUtil {
    
    
    /**
     * 单位缩进字符串。
     */
    private static String SPACE = "    ";

    /**
     * 返回格式化JSON字符串。
     *
     * @param s 未格式化的JSON字符串。
     * @return 格式化的JSON字符串。
     */
    public String formatJson(String s) {
    
    
        String json = s.replace("\n", "");
        StringBuffer result = new StringBuffer();

        int length = json.length();
        int number = 0;
        char key = 0;

        //遍历输入字符串。
        for (int i = 0; i < length; i++) {
    
    
            //1、获取当前字符。
            key = json.charAt(i);

            //2、如果当前字符是前方括号、前花括号做如下处理:
            if ((key == '[') || (key == '{')) {
    
    
                //(1)如果前面还有字符,并且字符为“:”,打印:换行和缩进字符字符串。
                if ((i - 1 > 0) && (json.charAt(i - 1) == ':')) {
    
    
                    result.append('\n');
                    result.append(indent(number));
                }

                //(2)打印:当前字符。
                result.append(key);

                //(3)前方括号、前花括号,的后面必须换行。打印:换行。
                result.append('\n');

                //(4)每出现一次前方括号、前花括号;缩进次数增加一次。打印:新行缩进。
                number++;
                result.append(indent(number));

                //(5)进行下一次循环。
                continue;
            }

            //3、如果当前字符是后方括号、后花括号做如下处理:
            if ((key == ']') || (key == '}')) {
    
    
                //(1)后方括号、后花括号,的前面必须换行。打印:换行。
                result.append('\n');

                //(2)每出现一次后方括号、后花括号;缩进次数减少一次。打印:缩进。
                number--;
                result.append(indent(number));

                //(3)打印:当前字符。
                result.append(key);

                //(4)如果当前字符后面还有字符,并且字符不为“,”,打印:换行。
                if (((i + 1) < length) && (json.charAt(i + 1) != ',')) {
    
    
                    result.append('\n');
                }

                //(5)继续下一次循环。
                continue;
            }

            //4、如果当前字符是逗号。逗号后面换行,并缩进,不改变缩进次数。
            if ((key == ',')) {
    
    
                result.append(key);
                result.append('\n');
                result.append(indent(number));
                continue;
            }

            //5、打印:当前字符。
            result.append(key);
        }

        return result.toString();
    }

    /**
     * 返回指定次数的缩进字符串。每一次缩进三个空格,即SPACE。
     *
     * @param number 缩进次数。
     * @return 指定缩进次数的字符串。
     */
    private String indent(int number) {
    
    
        StringBuffer result = new StringBuffer();
        for (int i = 0; i < number; i++) {
    
    
            result.append(SPACE);
        }
        return result.toString();
    }
}

效果

时间戳转换
小工具
JSON格式化
小工具

注意

需要指定程序的编码否则Choice对象里的text属性显示会乱码

在idea中的设置,Eclipse自行百度
设置

总结

遇到一个bug就是swing包下的JConboBox对象,不知道是我用法不对还是本身就是这样的,当我点击转换后,下拉列表就失灵,除非点一下其他Tab菜单,网上查很多资料,也没发现有人遇到和我一样的问题,后来没办法,用的AWT包下的Choice对象实现的下拉列表。

在桌面软件开发中第一梯度时C++ QT,C# WPF,Electron,而Swing AWT这类都属于第二梯队的技术,但是对语言比较熟悉来说,再加上软件本身逻辑也不复杂,用起来还是很顺手的。

我将程序打包成了exe,需要的可以私信留下邮箱地址。

点赞转发关注,你的支持是我最大的动力!

猜你喜欢

转载自blog.csdn.net/y1534414425/article/details/108839545
今日推荐