Java Swing JTable 简易版CSV阅读工具

背景描述:

        csv只能用excel打开,然后excel对源csv数据默认进行了格式化,导致源数据格式发生了变化。然而用记事本打开csv,数据对齐错乱不便于观察和查找数据,花费1小时怒写简易版CSV查看工具。


展示效果: 

废话不多说,先上效果图

Java Swing JTable 简易版CSV阅读工具_第1张图片






完整代码实现:

import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.List;

public class table extends JTable{
    private DefaultTableModel model;
    //窗口宽高
    static int width=1900;
    static int height=1000;
    private static table table =null;
    // 表头(列名)
    private static String[] columnNames = null;
    //Top Panel
    private static JPanel panel=new JPanel(new BorderLayout());
    //条件选择 checkBoxes
    private static List checkBoxes=new ArrayList<>();
    //文件选择、搜索相关按钮
    private static JButton fileSelBtn=new JButton("选择");
    private static JTextField textField=new JTextField();
    private static JCheckBox isAllSelCheckBox=new JCheckBox("全选");
    private static JButton searchBut=new JButton("搜索");
    private static JButton nextBtn=new JButton("下一个");
    //匹配到多少个
    private static JLabel label=new JLabel("");
    //文件路径
    private static JTextField filePathText=new JTextField();
    //放入搜索匹配的行数
    private static List rowNumb=null;
    //当前选中的行在rowNumb中的索引,默认index=0
    private static int rowNumbIndex=0;


    public static void main(String[] args) throws IOException {

        JFrame f = new JFrame();
        f.setTitle("CSV简易阅读工具");
        f.getContentPane().setLayout(new BorderLayout());

        //Top
        panel.setPreferredSize(new Dimension(width,250));
        f.getContentPane().add(panel,BorderLayout.NORTH);

        /**
         * 加载选择csv
         */
        loadSelCsv(f);

        f.setSize(width, height);
        f.setVisible(true);
    }

    /**
     * 构造表格
     * @param header
     */
    public table(String[] header) {
        model = new DefaultTableModel(header, 0);
        this.setModel(model);
    }


    /**
     * 插入一行数据
     * @param data
     */
    public void InsertValue(List data) {
        Thread thread = new Thread() {
            public void run() {
                Vector value = null;
                for(int i=0;i();
                    String[] da=data.get(i).split(",");
                    for (String str:da){
                        value.add(str);
                    }
                    addRow(value);
                    try {
                        sleep(10);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        };
        thread.start();
    }

    /**
     * 将添加记录
     *
     * @param value
     */
    public void addRow(final Vector value) {
        Thread thread = new Thread() {
            public void run() {
                Runnable runnable = new Runnable() {
                    public void run() {
                        model.addRow(value);
                    }
                };
                SwingUtilities.invokeLater(runnable);
            }
        };
        thread.start();
    }

    /**
     * 读取csv数据
     * @param path
     * @return
     * @throws IOException
     */
    public static Map> readCSV(String path) throws IOException {
        String line = "";
        Map> map=new HashMap>();
        //读取文件
        InputStreamReader isr= new InputStreamReader(new FileInputStream(path),"GBK");
        BufferedReader br = new BufferedReader(isr);
        List title= Collections.synchronizedList(new ArrayList());
        //放入csv数据
        List data=Collections.synchronizedList(new ArrayList());
        int i=0;
        while ((line = br.readLine()) != null) {
            //去掉引号
            line=line.replace("\"","");
            if(i==0) {
                title.add(line);
            }else {
                data.add(line);
            }
            i++;
        }
        map.put("title",title);
        map.put("data",data);
        br.close();
        isr.close();
        return map;
    }


    /**
     * 加载各个组件
     * @param f
     */
    public static void load(JFrame f,String path) throws IOException {
        Map> csv= readCSV(path);
        List title=csv.get("title");
        List data=csv.get("data");
        // 表头(列名)
        columnNames = title.get(0).split(",");

        /**
         * 加载条件
         */
        loadCheckBoxes();

        /**
         * 加载搜索面板
         */
        loadSearchPanel(data);

        /**
         * 加载表格
         * @param f
         */
        loadTable(f,data);

        /**
         * 刷新页面
         */
        f.revalidate();

    }


    /**
     * 加载csv文件
     */
    public static void loadSelCsv(JFrame f){
        JPanel csvPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
        csvPanel.setPreferredSize(new Dimension(width,50));
        JLabel filePath=new JLabel("文件路径:");
        csvPanel.add(filePath);
        filePathText.setPreferredSize(new Dimension(350,28));
        csvPanel.add(filePathText);
        csvPanel.add(fileSelBtn);
        panel.add(csvPanel,BorderLayout.NORTH);

        //监听文件选择
        fileSelBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                JFileChooser jfc=new JFileChooser();
                jfc.setFileFilter(new FileFilter() {
                    @Override
                    public String getDescription() {
                        return "CSV文件(*.csv)";
                    }
                    @Override
                    public boolean accept(File f) {
                        if(f.isDirectory()){
                            return true;
                        }
                        if(f.getName().toLowerCase().endsWith(".csv")) {
                            return true;
                        }
                        return false;
                    }
                });
                //显示对话框
                int ret=jfc.showSaveDialog(f.getContentPane());
                //获取选择的文件路径
                if(ret==JFileChooser.APPROVE_OPTION){
                    File file=jfc.getSelectedFile();
                    filePathText.setText(file.getAbsolutePath());
                    try {
                        load(f,file.getAbsolutePath());
                    } catch (IOException ioException) {
                        ioException.printStackTrace();
                    }
                }
            }
        });
    }

    /**
     * 加载条件选择
     */
    public static void loadCheckBoxes(){
        //条件选择
        JPanel selPanel=new JPanel(new FlowLayout(FlowLayout.LEFT));
        selPanel.setPreferredSize(new Dimension(width,150));
        panel.add(selPanel,BorderLayout.CENTER);
        for(String t:columnNames){
            JCheckBox checkBox = new JCheckBox(t);
            checkBoxes.add(checkBox);
            selPanel.add(checkBox);
        }
    }

    /**
     * 加载搜索面板
     */
    public static  void loadSearchPanel(List data){
        JPanel searchPanel=new JPanel(new FlowLayout(FlowLayout.RIGHT));
        searchPanel.setPreferredSize(new Dimension(width,50));
        panel.add(searchPanel,BorderLayout.SOUTH);

        searchPanel.add(label);
        searchPanel.add(isAllSelCheckBox);

        textField.setPreferredSize(new Dimension(150,28));
        searchPanel.add(textField);

        searchPanel.add(searchBut);

        searchPanel.add(nextBtn);

        //监听搜索按钮
        searchBut.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                //先移除所有选择的行
                table.clearSelection();
                String text=textField.getText();
                //搜索字段
                Map map=new HashMap<>();
                for (JCheckBox checkBox:checkBoxes){
                    map.put(checkBox.getText(),checkBox.isSelected()==true?"true":"false");
                }

                //放入搜索匹配的行数
                rowNumb=new ArrayList<>();

                int rowIndex=0;
                for (String rowData:data){
                    String[] rowD=rowData.split(",");
                    //默认搜索到
                    boolean isSearch=true;
                    for (int c=0;c=rowD.length){
                            isSearch=false;
                            continue;
                        }
                        String value=rowD[c];
                        String isSearchField=map.get(name);
                        if("true".equals(isSearchField)){
                            if(!value.contains(text)){
                                isSearch=false;
                            }
                        }
                    }
                    if(isSearch){
                        rowNumb.add(rowIndex);
                    }
                    rowIndex++;
                }
                //查询到n个
                label.setText("查询到"+rowNumb.size()+"个");

                //选中查询到的行,并设置其背景颜色
                for (Integer ind:rowNumb){
                    //防止添加行出错
                    if(ind>=table.getRowCount()){
                        continue;
                    }
                    table.addRowSelectionInterval(ind,ind);
                }
                table.setSelectionBackground(Color.orange);//选中行设置背景色
                //跳转到第一个查询到的
                table.scrollRectToVisible(table.getCellRect(rowNumb.get(0), 0, true));
                rowNumbIndex=0;
            }
        });

        //监听下一个
        nextBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(rowNumb==null){
                    return;
                }
                rowNumbIndex=rowNumbIndex+1;
                if (rowNumbIndex>=rowNumb.size()){
                    rowNumbIndex=0;
                }
                //跳转到下一行
                table.scrollRectToVisible(table.getCellRect(rowNumb.get(rowNumbIndex), 0, true));
            }
        });

        //监听全选按钮
        isAllSelCheckBox.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if(isAllSelCheckBox.isSelected()){
                    for (JCheckBox checkBox:checkBoxes){
                        checkBox.setSelected(true);
                    }
                }else {
                    for (JCheckBox checkBox:checkBoxes){
                        checkBox.setSelected(false);
                    }
                }
            }
        });


    }

    /**
     * 加载表格
     * @param f
     * @param data
     */
    public static void loadTable(JFrame f,List data){
        table = new table(columnNames);
        //选中行设置背景色
        table.setSelectionBackground(Color.orange);
        //设置JTable的列宽随着列表内容的大小进行调整
        table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
        for (int i = 0; i < columnNames.length; i++) {
            table.getColumnModel().getColumn(i).setPreferredWidth(200);
        }
        //加载数据
        table.InsertValue(data);
        JScrollPane scroll = new JScrollPane(table);
        f.getContentPane().add(scroll, BorderLayout.CENTER);
    }
}

你可能感兴趣的:(java,swing,java,swing,jtable,csv)