Java 工具

监听热键

// 需要引入jintellitype包,百度下载
public class GlobleHotKeyDemo extends JFrame {

    //定义热键标识,用于在设置多个热键时,在事件处理中区分用户按下的热键
    public static final int EXIT_KEY_MARK = 0;

    JButton exitBtn;
    public GlobleHotKeyDemo() {
        this.setTitle("全局热键设置");
        this.setBounds(100, 100, 600, 400);
        this.setLayout(null);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        exitBtn = new JButton("退出(Alt+Q)");
        exitBtn.setMargin(new Insets(0,0,0,0));
        exitBtn.setFocusable(false);
        exitBtn.setBounds(300, 20, 120, 30);
        exitBtn.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                System.exit(0);
            }
        });
        this.add(exitBtn);

        //第一步:注册热键,第一个参数表示该热键的标识,第二个参数表示组合键,如果没有则为0,第三个参数为定义的主要热键
        JIntellitype.getInstance().registerHotKey(EXIT_KEY_MARK, JIntellitype.MOD_ALT, (int)'Q');  

        //第二步:添加热键监听器
        JIntellitype.getInstance().addHotKeyListener(new HotkeyListener() {

            @Override
            public void onHotKey(int markCode) {
                switch (markCode) {  
                case EXIT_KEY_MARK:  
                    System.exit(0);
                    break;   
                }                 
            }
        });  
        windowListener();
        this.setVisible(true);
    }

    public static void main(String[] args) {
        new GlobleHotKeyDemo();
    }
 }

截屏

    public void screenShot(String path) {  
        Dimension d = Toolkit.getDefaultToolkit().getScreenSize();  
        Robot robot;
        try {
            robot = new Robot();
            BufferedImage bufferedImage = robot.createScreenCapture(new Rectangle(d.width, d.height));  
            ImageIO.write(bufferedImage, "jpg", new File(path + System.currentTimeMillis() + ".jpg"));  
            System.out.println("ok");  
        } catch (AWTException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }  
    }

访问剪切板

    /** 
     * 将字符串复制到剪切板。 
     */  
    public static void setSysClipboardText(String writeMe) {  
        Clipboard clip = Toolkit.getDefaultToolkit().getSystemClipboard();  
        Transferable tText = new StringSelection(writeMe);  
        clip.setContents(tText, null);  
    }  

    /** 
     * 从剪切板获得图片。 
     */  
    public static Image getImageFromClipboard() throws Exception {  
        Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();  
        Transferable cc = sysc.getContents(null);  
        if (cc == null)  
            return null;  
        else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))  
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);  
        return null;  
    }  

    /** 
     * 复制图片到剪切板。 
     */  
    public static void setClipboardImage(final Image image) {  
        Transferable trans = new Transferable() {  
            public DataFlavor[] getTransferDataFlavors() {  
                return new DataFlavor[] { DataFlavor.imageFlavor };  
            }  

            public boolean isDataFlavorSupported(DataFlavor flavor) {  
                return DataFlavor.imageFlavor.equals(flavor);  
            }  

            public Object getTransferData(DataFlavor flavor)  
                    throws UnsupportedFlavorException, IOException {  
                if (isDataFlavorSupported(flavor))  
                    return image;  
                throw new UnsupportedFlavorException(flavor);  
            }  

        };  
        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(trans,  
                null);  
    } 

Excel解析。需要引入apache-ant-1.8.2.jar

package com.yuan;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.tools.ant.Project;
import org.apache.tools.ant.taskdefs.Zip;
import org.apache.tools.ant.types.FileSet;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;


/*constructor ExcelParser(String filePath
 * getValueByCoordinate
 * deCompression()
 * compressToExcel(String, String)
 */

public class ExcelParser {
    String className = "ExcelParser";
    private String filePath;
    private String tempDirPath;
    private String deCompressPath;
    private String path_sheetssXml = "\\xl\\worksheets";
    //  private String deCompressPath = tempDirPath + "deCompressFiles";
    public boolean deCompressionCompleted = false;
    public Notifier noti;

    Element ele_si;
    Element ele_c;
    Element ele_r;

    //  public void Util.l(className,String methodName,String log){
    //      System.out.println("[" + CLASSNAME + "->"+ methodName + "]"+ log);
    //  }

    public ExcelParser(String filePath , Notifier noti) {
        this.filePath = filePath;
        this.noti = noti;
        initFile();
    }
    public ExcelParser(String filePath) {
        this.filePath = filePath;
        noti = new Notifier() {
            @Override
            public void onExcelDeCompressionCompleted() {
                // TODO Auto-generated method stub
            }
        };
        initFile();
    }

    ZipFile xlsxFile;
    NodeList siList; //sharedStringXML
    DocumentBuilderFactory dbf;
    NodeList nl;
    private boolean initFile() {
        String methodName = "initFile";

        File excelFile = new File(filePath);
        if (!excelFile.exists()) {
            Util.l(className,methodName,"Excel file isn't exist");
            return false;
        }
        Util.l(className,methodName , excelFile.getParent());

        //decompress and modified use 
        tempDirPath = excelFile.getParent() + "\\tempFiles\\";
        deCompressPath = tempDirPath + "deCompressFiles";
        System.out.println(tempDirPath);

        // 解压Book1.xlsx
        refreshExcel();
        return true;
    }


    public boolean deCompression() {
        refreshTempDir();
        if(initFile()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    doDeCompression();
                }
            }).start();
        }

        return true;
    }

    private void doDeCompression() {
        String methodName = "doDeCompression";
        try {
            ZipInputStream is = new ZipInputStream(new FileInputStream(new File(filePath)));
            ZipEntry  zip;
            while((zip=is.getNextEntry())!=null){
                Util.l(className,methodName,"deCompressing file:" + zip.getName());
                Util.l(className,methodName , deCompressPath);
                File file = new File(deCompressPath,zip.getName());
                if(!file.exists()){
                    (new File(file.getParent())).mkdirs();
                    if(!file.isDirectory()) file.createNewFile();
                }
                FileOutputStream w = new FileOutputStream(file);
                BufferedInputStream buf = new BufferedInputStream(is);
                int a;
                while((a=buf.read())!=-1){
                    w.write(a);
                }
                w.close();
            }
            is.close();
            Util.l(className,"doDeCompression()" , "deCompression complete");
            deCompressionCompleted = true;
            noti.onExcelDeCompressionCompleted();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        }
    }



    private void refreshTempDir() {
        File tempDir = new File(tempDirPath);
        if(tempDir.exists()) {
            //          System.out.println("deleted"+tempDir.deleteOnExit());
            deleteDir(tempDir);
        }
        tempDir.mkdirs();
    }

    private static boolean deleteDir(File dir) {

        if (dir.isDirectory()) {
            String[] children = dir.list();
            for (int i=0; i<children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }
        return dir.delete();
    }

    public boolean compressToExcel() {

        return true;
    }

    public String getValueByCoordinate(String sheetName,String cellName){
        int sheetNum = 0;
        for (; sheetNum < nl.getLength(); sheetNum++) {
            Element element = (Element) nl.item(sheetNum);// 将node转化为element,用来得到每个节点的属性
            if(sheetName.equals(element.getAttribute("name"))) break;
        }
        int[] i =seperate(cellName);
        return getValueByCoordinate(sheetNum,cellName.substring(0, i[0]),Integer.valueOf(cellName.substring(i[0],i[1])));
    }


    public String getValueByCoordinate(int sheetNum,String cellName){
        int[] i = seperate(cellName);
        return getValueByCoordinate(sheetNum,cellName.substring(0, i[0]),Integer.valueOf(cellName.substring(i[0],i[1])));
    }

    //
    private int[] seperate(String cellName) {
        int i = 0;
        char[] array = cellName.toCharArray();
        for (; i < array.length; i++) {
            if(array[i]>47&&array[i]<58) break;
        }
        int[] vars= {i,array.length};
        return vars;
    }

    //ex:C12  rowName:12  col:C
    //   sheetNum:0~
    //   
    public String getValueByCoordinate(int sheetNum,String col,int rowName) {
        String result = null;
        String methodName = "getValueByCoordinate(int sheetNum,String col,int rowName)";
        Util.l(className,methodName,"start:" +" sheetNum=" + sheetNum + " col=" + col + " rowName=" +rowName);
        col = col.toUpperCase();
        try {
            ZipEntry sheetXML = xlsxFile.getEntry("xl/worksheets/" + "sheet"+ (sheetNum+1) + ".xml");
            if (sheetXML==null) {
                Util.l(className,methodName , "sheetXML is null");
            } else {

            }
            InputStream sheetXMLIS = xlsxFile.getInputStream(sheetXML);
            Document sheetdoc = dbf.newDocumentBuilder().parse(sheetXMLIS);
            NodeList sheet1Rowdata = sheetdoc.getElementsByTagName("row");
            for (int j = 0; j < sheet1Rowdata.getLength(); j++) { //
                Element row = (Element) sheet1Rowdata.item(j);
                if(row==null) {
                    Util.l(className,methodName, "row is null."+"j="+j); 
                    continue;
                }
                NodeList columndata = row.getElementsByTagName("c");
                for (int k = 0; k < columndata.getLength(); k++) {
                    Element column = (Element) columndata.item(k);
                    //                      Util.l(className,methodName, "column.getAttribute(r)="+((String)column.getAttribute("r")));
                    //                      Util.l(className,methodName, "col+String.valueOf(rowName))=" + col+String.valueOf(rowName));
                    if(((String)column.getAttribute("r")).equals(col+String.valueOf(rowName))){
                        result = getTextByCellName(column, siList);
                        Util.l(className,methodName, "result:" + result);
                    }
                }
            }
            //          xlsxFile.close();
        } catch (ZipException e) {
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        } catch (SAXException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        } catch (ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        }
        return result;
    }

    private String getTextByCellName(Element column,NodeList siList) {
        String methodName = "getTextByCellName";
        Util.l(className, methodName, "");
        NodeList values = column.getElementsByTagName("v");
        Element value = (Element) values.item(0);
        if (column.getAttribute("t") != null&& column.getAttribute("t").equals("s")) {
            // 如果是共享字符串则在sharedstring.xml里查找该列的值 
            int rIndex = Integer.parseInt(value.getTextContent());// 在sharesStringXML里log信息存放的位置号
            Element si= (Element) siList.item(rIndex);
            NodeList tList = si.getElementsByTagName("t");
            String cellText = "";
            for (int l = 0; l < tList.getLength(); l++) {
                Element t = (Element)tList.item(l);
                cellText = cellText + t.getTextContent();
            }
            Util.l(className, methodName, " end1");
            return cellText;
        } else{
            Util.l(className, methodName, " end2:");
            try {
                value.getFirstChild().getTextContent();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
                Util.l(className, methodName, e.getMessage());
                return "";
            }
            return value.getFirstChild().getTextContent();
        }
    }

    public boolean isdeCompressionCompleted(){
        return deCompressionCompleted;
    }

    public interface Notifier {
        public void onExcelDeCompressionCompleted();
    }

    //压缩到Excel文件
    //srcPathNameDir:要砸锁的文件所在目录,targerFile:生成的文件名字
    public void compressToExcel(String srcPathNameDir,String targerFile) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                File zipFile = new File(targerFile);  
                File srcdir = new File(srcPathNameDir);  
                if (!srcdir.exists()) throw new RuntimeException(srcPathNameDir + "不存在!");  
                Project prj = new Project();  
                Zip zip = new Zip();  
                zip.setProject(prj);  
                zip.setDestFile(zipFile);  
                FileSet fileSet = new FileSet();  
                fileSet.setProject(prj);  
                fileSet.setDir(srcdir);  
                zip.addFileset(fileSet);  
                zip.execute();  
            }
        }).start();
    }

    /* \xl\worksheets\sheet1.xml
     * <row r="12" x14ac:dyDescent="0.15" spans="4:7">   spans="4:7"内的跨度修改
     *   <c r="E12" t="s">        按照 “行号顺序” 增加对应标签
     *      <v>25</v>
     *   </c>
     *   
     *   
     *   xl/sharedStrings.xml
     *   <sst count="30" uniqueCount="28">    count和uniqueCount的值需要+1
     *   <si><t>s</t></si>    增加该标签,<t></t>内为内容
     */
    void creatSharedStringXml() {

    }

    void newSheetXml() {

    }




    /*
     * ex:C12  rowName:12  col:C
     * sheetNum:0~
     */
    Document doc_sharedString;
    Document doc_sheet;
    void modifyContentByCoordinate(int sheetNum,String col,int rowName,String content) {
        String methodName = "modifyContentByCoordinate";
        if(!deCompressionCompleted) {
            Util.l(className,methodName, "deCompressionCompleted=" +deCompressionCompleted);
            return;
        }


        File file_sheetXml = new File(path_sheetssXml,"sheet"+(sheetNum+1)+".xml");
        if (!file_sheetXml.exists()) {
            Util.l(className,methodName, "sheetXml don't exits");
            return ;
        }


        DocumentBuilderFactory fac_sheet =  DocumentBuilderFactory.newInstance();
        try {

            doc_sheet = fac_sheet.newDocumentBuilder().parse(file_sheetXml);
        } catch (SAXException | IOException | ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        NodeList list_row_sheetXml = doc_sheet.getElementsByTagName("row");
        Element target_row = null; //<row  </row>
        int add_row_index = -1;
        for (int i = 0; i < list_row_sheetXml.getLength(); i++) {
            Element e = (Element) list_row_sheetXml.item(i);
            String rowNum = e.getAttribute("r");
            int rowN = Integer.valueOf(rowNum);
            if (rowN==rowName) {
                target_row = (Element) list_row_sheetXml.item(i);
                break;
            }
            if(rowN>rowName){
                add_row_index = i;
                break;
            }
        }
        if (target_row!=null) {
            Element target_colOfRow = null;
            int add_col_index = -1;
            String spans = target_row.getAttribute("spans");
            int state = isColInArrange(spans,col); // return -1 ,0,1 
            if (state==0) {                        //该列在已有的列范围内
                NodeList list_col_sheetXml = target_row.getElementsByTagName("c");
                for (int i = 0; i < list_col_sheetXml.getLength(); i++) {
                    Element e = (Element) list_col_sheetXml.item(i);
                    String colNum = e.getAttribute("r");
                    if(colNum.equals(col+rowName)){
                        target_colOfRow = (Element) list_col_sheetXml.item(i);
                        break;
                    }

                    if(getIntOfCol(colNum)>getIntOfCol(col)){
                        add_col_index = i;
                        break;
                    }
                }

                if (target_colOfRow!=null) {    //源sheet内该cell有值   <c </c>
                    if (target_colOfRow.getAttribute("t") != null&& target_colOfRow.getAttribute("t").equals("s")) {   //已经使用SharedString的情况
                        String index_string = ((Element)target_colOfRow.getElementsByTagName("v").item(0)).getTextContent();
                        int index = Integer.valueOf(index_string);
                        modifyItemAtSharedStringXml(content, index-1);
                    } else {               
                        int sharedNum = addNewItemAtSharedStringXml(content);
                        target_colOfRow.setAttribute("t", "s");
                        ((Element)target_colOfRow.getElementsByTagName("v").item(0)).setTextContent((sharedNum-1)+"");
                        saveDoc(doc_sheet,deCompressPath+"\\xl\\worksheets\\sheet"+(sheetNum+1)+".xml");
                    }
                } else {                        //源sheet内该行有数据,但该列没有数据
                //  target_row. // 20170104
                }

            }

            if (state==-1) {

            }

            if (state==1) {

            }
        } else {

        }


    }


    private int isColInArrange(String spans ,String col) {
        String[] array = spans.split(":");
        int s = Integer.valueOf(array[0]);
        int e = Integer.valueOf(array[1]);
        int c = Integer.valueOf(getIntOfCol(col));
        if(c<s) return -1;
        if(c>e) return 1;
        return 0;
    }

    int getIntOfCol(String col) {
        char[] array = col.toCharArray();
        int result = 0;
        for (int i = 0; i < array.length; i++) {
            if (array[i]>='A'&&array[i]<='Z') {
                result = result*26 + (array[i]-'@');
            } else if (result!=0) {
                break;
            }
        }
        return result;
    }

    void modifyItemAtSharedStringXml(String content,int index) {
        String methodName = "modifyItemAtSharedStringXml";
        File file_sharedStringXml = new File(deCompressPath+"\\xl\\sharedString.xml");
        if (!file_sharedStringXml.exists()) {
            Util.l(className,methodName, "sharedStringXml don't exits");
            return;
        }
        DocumentBuilderFactory fac_sharedString =  DocumentBuilderFactory.newInstance();
        try {
            doc_sharedString = fac_sharedString.newDocumentBuilder().parse(file_sharedStringXml);
        } catch (SAXException | IOException | ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        NodeList list_si = doc_sharedString.getElementsByTagName("si");
        Element e = (Element) ((Element) list_si.item(index)).getElementsByTagName("t").item(0);
        e.setTextContent(content);
        saveDoc(doc_sharedString,deCompressPath+"\\xl\\sharedStrings.xml");
    }

    /*
     * return new sharedString' si count
     */
    int addNewItemAtSharedStringXml(String content) {
        String methodName = "addNewItemAtSharedStringXml";
        File file_sharedStringXml = new File(deCompressPath+"\\xl\\sharedString.xml");
        if (!file_sharedStringXml.exists()) {
            Util.l(className,methodName, "sharedStringXml don't exits");
            return -1;
        }
        DocumentBuilderFactory fac_sharedString =  DocumentBuilderFactory.newInstance();
        try {
            doc_sharedString = fac_sharedString.newDocumentBuilder().parse(file_sharedStringXml);
        } catch (SAXException | IOException | ParserConfigurationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        NodeList list_si = doc_sharedString.getElementsByTagName("si");
        Element s = (Element) doc_sharedString.getFirstChild();
        String count = s.getAttribute("count");
        String uniqueCount = s.getAttribute("uniqueCount");
        s.setAttribute("count", (Integer.valueOf(count)+1)+"");
        s.setAttribute("uniqueCount", (Integer.valueOf(uniqueCount)+1)+"");
        Node newSi =  list_si.item(0).cloneNode(false);
        Node newT = list_si.item(0).getFirstChild().cloneNode(false);
        newSi.appendChild(newT);
        s.appendChild(newSi);
        NodeList list_si_changed = s.getElementsByTagName("si");
        Element e = (Element) ((Element) list_si_changed.item(list_si_changed.getLength()-1)).getElementsByTagName("t").item(0);
        e.setTextContent(content);
        saveDoc(doc_sharedString,deCompressPath+"\\xl\\sharedStrings.xml");
        return Integer.valueOf(uniqueCount)+1;
    }

    private void saveDoc(Document doc,String filePath) {
        // TODO Auto-generated method stub
        TransformerFactory factory = TransformerFactory.newInstance();
        Transformer former;
        try {
            former = factory.newTransformer();
            former.transform(new DOMSource(doc), new StreamResult(new File(filePath)));
        } catch (TransformerException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    /*
     * search fuction
     * content : the string you want to find
     * countOfResult : the num of result you want to find ,if countOfResult=-1 ,return all result
     * isSubString: specify content is substring of cell or not. ex :  he is sub of hello 
     * return : sheetNum:cellName, 
     */

    public ArrayList<String> getCoordinateByContent(String content , int countOfResult , boolean isSubString) {
        String methodName = "getCoordinateByContent";
        ArrayList<String> results = new ArrayList<>();
        int index = -1;
        ArrayList<Integer> indexs = new ArrayList<Integer>();
        if (siList!=null) {

            for (int i = 0; i < siList.getLength(); i++) {
                Element e = (Element) siList.item(i);
                if (isSubString) {
                    if((((Element)e.getElementsByTagName("t").item(0)).getTextContent()).contains(content)){
                        Util.l(className, methodName, (((Element)e.getElementsByTagName("t").item(0)).getTextContent()));
                        index = i;
                        indexs.add(i);
                        Util.l(className, methodName, "index in sharedString.xml is " + i);
                        //                      break;
                    }
                } else {
                    if(content.equals(((Element)e.getElementsByTagName("t").item(0)).getTextContent())){
                        index = i;
                        indexs.add(i);
                        Util.l(className, methodName, "index in sharedString.xml is " + i);
                        //                      break;
                    }
                }
            }
            //          if (index!=-1) {
            if(indexs.size()>=1){
                for (int k2 = 0; k2 < indexs.size(); k2++) {
                    Util.l(className, methodName, "the target string is in sharedString.xml, so go on");
                    index = indexs.get(k2);
                    String string_index = index+"";
                    for (int i = 0; i < nl.getLength(); i++) {
                        Util.l(className, methodName, "parser sheet" + (i+1) );
                        ZipEntry sheetXML = xlsxFile.getEntry("xl/worksheets/" + "sheet"+ (i+1) + ".xml");
                        InputStream is_sheetXml;
                        try {
                            is_sheetXml = xlsxFile.getInputStream(sheetXML);
                            Document doc_sheetXml;
                            doc_sheetXml = dbf.newDocumentBuilder().parse(is_sheetXml);
                            NodeList list_row = doc_sheetXml.getElementsByTagName("row");
                            for (int j = 0; j < list_row.getLength(); j++) {
                                NodeList list_cell = ((Element)list_row.item(j)).getElementsByTagName("c");
                                for (int k = 0; k < list_cell.getLength(); k++) {
//                                  Util.l(className, methodName, "k="+k+",j="+j+","+"i="+i);
                                    Element e = (Element)list_cell.item(k);
                                    String t = e.getAttribute("t");
                                    NodeList l_v = e.getElementsByTagName("v");
                                    Element e_v = (Element)l_v.item(0);
                                    if(e_v!=null&&t!=null&&t.equals("s")){
                                            if(e_v.getTextContent().equals(string_index)){
                                                results.add((i+1) + ":" + e.getAttribute("r"));  //format sheetNum:cellName
                                                if (countOfResult!=-1&&results.size()>=countOfResult) { 
                                                    break;
                                                }
                                            }
                                    }
                                }
                                if (countOfResult!=-1&&results.size()>=countOfResult) { 
                                    break;
                                }
                            }

                        } catch (IOException | SAXException | ParserConfigurationException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                            Util.l(className, methodName, e.getMessage());
                        }
                        if (countOfResult!=-1&&results.size()>=countOfResult) { 
                            break;
                        }
                    }
                }
            } else{
                Util.l(className, methodName, "the target string isn't in sharedString.xml");
            }
        } else {  //若果没有sharedString.xml

        }

        return results; //只考虑唯一解情况
    }

    /*
     * search method
     * sheetNum : 0~
     * content : the string you want to find
     * countOfResult : the num of result you want to find
     * 
     * return : sheetNum:cellName
     */
    public ArrayList<String> getCoordinateByContent(int sheetNum , String content , int countOfResult , boolean isSubString){
        String methodName = "getCoordinateByContent";
        ArrayList<String> results = new ArrayList<>();
        int index = -1;
        ArrayList<Integer> indexs = new ArrayList<Integer>();
        if (siList!=null) {

            for (int i = 0; i < siList.getLength(); i++) {
                Element e = (Element) siList.item(i);
                if (isSubString) {
                    if((((Element)e.getElementsByTagName("t").item(0)).getTextContent()).contains(content)){
                        Util.l(className, methodName, (((Element)e.getElementsByTagName("t").item(0)).getTextContent()));
                        index = i;
                        indexs.add(i);
                        Util.l(className, methodName, "index in sharedString.xml is " + i);
                        //                      break;
                    }
                } else {
                    if(content.equals(((Element)e.getElementsByTagName("t").item(0)).getTextContent())){
                        index = i;
                        indexs.add(i);
                        Util.l(className, methodName, "index in sharedString.xml is " + i);
                        //                      break;
                    }
                }
            }
            //          if (index!=-1) {
            if(indexs.size()>=1){
                for (int k2 = 0; k2 < indexs.size(); k2++) {
                    Util.l(className, methodName, "the target string is in sharedString.xml, so go on");
                    index = indexs.get(k2);
                    String string_index = index+"";
                    //                  for (int i = 0; i < nl.getLength(); i++) {
                    int i = sheetNum;
                    Util.l(className, methodName, "parser sheet" + (i+1) );
                    ZipEntry sheetXML = xlsxFile.getEntry("xl/worksheets/" + "sheet"+ (i+1) + ".xml");
                    InputStream is_sheetXml;
                    try {
                        is_sheetXml = xlsxFile.getInputStream(sheetXML);
                        Document doc_sheetXml;
                        doc_sheetXml = dbf.newDocumentBuilder().parse(is_sheetXml);
                        NodeList list_row = doc_sheetXml.getElementsByTagName("row");
                        for (int j = 0; j < list_row.getLength(); j++) {
                            NodeList list_cell = ((Element)list_row.item(j)).getElementsByTagName("c");
                            for (int k = 0; k < list_cell.getLength(); k++) {
                                Element e = (Element)list_cell.item(k);
                                String t = e.getAttribute("t");
                                if(t!=null&&t.equals("s")){
                                    if(((Element)e.getElementsByTagName("v").item(0)).getTextContent().equals(string_index)){
                                        results.add((i+1) + ":" + e.getAttribute("r"));  //format sheetNum:cellName
                                        if (countOfResult!=-1&&results.size()>=countOfResult) { 
                                            break;
                                        }
                                    }
                                }
                            }
                            if (countOfResult!=-1&&results.size()>=countOfResult) { 
                                break;
                            }
                        }

                    } catch (IOException | SAXException | ParserConfigurationException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                        Util.l(className, methodName, e.getMessage());
                    }
                    if (countOfResult!=-1&&results.size()>=countOfResult) { 
                        break;
                    }
                    //                  }
                }
            } else{
                Util.l(className, methodName, "the target string isn't in sharedString.xml");
            }
        } else {  //若果没有sharedString.xml

        }

        return results; //只考虑唯一解情况
    }

    public void closeFile() {
        String methodName = "closeFile";
        // TODO Auto-generated method stub
        try {
            xlsxFile.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        }
    }

    public void refreshExcel() {
        String methodName = "refreshExcel()";
        // TODO Auto-generated method stub
        try {
            xlsxFile = new ZipFile(new File(filePath));
            //            xlsxFile = new ZipFile(new File("C:\\Users\\tstcit\\Desktop\\新建 Microsoft Excel 工作表 (2).xlsx"));
            dbf = DocumentBuilderFactory.newInstance();
            // 先读取sharedStrings.xml这个文件备用
            ZipEntry sharedStringXML = xlsxFile.getEntry("xl/sharedStrings.xml");
            if (sharedStringXML!=null) { //如果 没有sharedString.xml,就不实例化相关的变量
                InputStream sharedStringXMLIS = xlsxFile.getInputStream(sharedStringXML);
                Document sharedString;
                sharedString = dbf.newDocumentBuilder().parse(sharedStringXMLIS);
                siList = sharedString.getElementsByTagName("si");
            }
            ZipEntry workbookXML = xlsxFile.getEntry("xl/workbook.xml");
            InputStream workbookXMLIS = xlsxFile.getInputStream(workbookXML);
            Document doc = dbf.newDocumentBuilder().parse(workbookXMLIS);
            // 获取一共有几个sheet
            nl = doc.getElementsByTagName("sheet");
            if(nl.getLength()==0){
                nl = doc.getElementsByTagName("s:sheet");
            }
            Util.l(className,methodName ,"has " + nl.getLength()+" sheets");
        } 
        catch(Exception e){
            e.printStackTrace();
            Util.l(className, methodName, e.getMessage());
        }
    }
}

//Util 类
package com.yuan;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class Util {
    static FileWriter writer;
    static boolean isSaveLog = false;

    /*运行时将log保存到本地文件内 ,需要制定保存路径
     * 
     */
    public static void l(String className ,String methodName ,String info){
        System.out.println("[" + className + "]" + ".." 
                + methodName + "() ->" + info);
        if (isSaveLog) {    //运行时将log保存到本地文件内
            try {
                if (writer==null) {
                    String rootPath = System.getProperty("java.class.path");
                    File ff = new File(rootPath);
                    //      File log = new File(ff.getParent()+"\\log.txt");
                    File log = new File("log.txt");
                    if (log.exists()) log.delete();
                    log.createNewFile();
                    writer = new FileWriter(log);
                }
                writer.write("[" + className + "]" + ".." 
                        + methodName + "() ->" + info + "\n");
                writer.flush();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
    /*
     *  ex: Tx: AT+HEADINFO=1,0
     *      Rx: +HEADINFO=1,OK
     *          OK
     *     
     *   --> AT+HEADINFO
     */
    public static String getAtCmdFromText(String text){
        String result = "";
        if(text==null||!text.contains("AT+"))return null;
        int atHeadIndex = text.indexOf("AT+");
        String subString = text.substring(atHeadIndex);
        int atEndIndex = subString.indexOf("\n");
        //      MainLauncher.printLog("atHeadIndex=" + atHeadIndex+" atEndIndex="+atEndIndex+ "  text=" + text);
        result = subString.substring(0, atEndIndex);
        //      MainLauncher.printLogln(" " + result );
        return result;
    }

    public static String getStatusFromText(String text){
        if(text.equals("PASS")||text.equals("NA")||text.equals("FAIL"))return text;
        return null;
    }

    /* ex: A12
     * 
     * -->{"A","12"}
     */
    public static String[] seperateStringAndInt(String s) {
        char[] c = s.toCharArray();
        String col = "" , row = "";
        for (int i = 0; i < c.length; i++) {
            if(c[i]>='A'&&c[i]<='Z') {
                col+=c[i];
            }else {
                row+=c[i];
            }
        }
        return new String[]{col,row};
    }

    /*
     * ex: A-->1  Z-->26 AA-->27
     */
    public static int colToIngeter(String col) {
        char[] c = col.toCharArray();
        int result = 0;
        for (int i = 0; i < c.length; i++) {
            result = result*26 + (c[i]-'A'+1);
        }
        return result;
    }


    /*
     * ex: 1-->A  26-->Z 27-->AA
     */
    public static String ingeterToCol(int i) { 
        String buffer = "";
        //      i--;
        do{
            int a = i%26;
            if (a!=0) {
                buffer+=(char)(a + 'A'-1);
                i=i/26;
            } else{
                a=(i-1)%26;
                buffer+=(char)(a + 'A');
                i=(i-1)/26;
            }
        }while(i>0);
        char[] c = buffer.toCharArray();
        buffer = "";
        for (int j = c.length-1; j >=0 ; j--) {
            buffer+=c[j];
        }
        return buffer;
    }

    /*
     * ex: A12
     * 
     * --> 12
     */
    public static int getIntegerFormString(String string) {
//      System.out.println("aaa"+string);
//      char[] array = string.toCharArray();
//      String numBuffer = "";
//      for (int i = 0; i < array.length; i++) {
//          if (array[i]>='0'&&array[i]<='9') {
//              numBuffer+=array[i];
//          } else if (!numBuffer.equals("")) {
//              break;
//          }
//      }
//      System.out.println("SSS"+numBuffer);
//      return Integer.valueOf(numBuffer);
        return Integer.valueOf(seperateStringAndInt(string)[1]);
    }

}

串口通信.引入RXTXcomm.jar

package module;



import entry.UIEntry;
import gnu.io.CommPortIdentifier;
import gnu.io.NoSuchPortException;
import gnu.io.PortInUseException;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import gnu.io.UnsupportedCommOperationException;

import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Font;
import java.awt.GridLayout;
import java.awt.Image;
import java.awt.TextArea;
import java.awt.TextField;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.TextEvent;
import java.awt.event.TextListener;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;
import java.util.TooManyListenersException;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;

import sun.audio.AudioPlayer;
import sun.audio.AudioStream;

public class UIRs232Sub
extends JPanel
implements ActionListener, SerialPortEventListener, TextListener, FocusListener
{
    private static final long serialVersionUID = -7270865686330790103L;
    public static int WIN_WIDTH = (int) (421*ConfigLoader.scroll_width);
    public static int WIN_HEIGHT = (int) (245*ConfigLoader.scroll_height);
    public JComboBox<?> portCombox;
    private JComboBox<?> rateCombox;
    private JComboBox<?> dataCombox;
    private JComboBox<?> stopCombox;
    private JComboBox<?> parityCombox;
    public Button openPortBtn;
    public Button closePortBtn;
    private Button confirm;
    public TextField scannedText;
    protected List<TextField> list_scannedText;
    protected int list_length = 8;
    public TextField worker;
    private TextArea readTa;
    private JLabel statusLb;
    public String portname;
    public String rate;
    public String data;
    public String stop;
    public String parity;
    protected CommPortIdentifier portId;
    protected Enumeration<?> ports;
    protected List<String> portList;
    protected SerialPort serialPort;
    protected OutputStream outputStream = null;
    protected SimpleDateFormat df;
    protected InputStream inputStream = null;
    protected String mesg;
    protected String sampleValue = "";
    protected String filePath = "E:\\helloworld.csv";
    protected DataSaved dataSaver;
    protected int sendCount;
    protected String worker1 = "17";
    protected int reciveCount;
    protected Integer[] rates = { Integer.valueOf(2400), Integer.valueOf(4800), Integer.valueOf(9600), Integer.valueOf(14400), Integer.valueOf(19200), Integer.valueOf(38400), Integer.valueOf(56000), Integer.valueOf(115200) };
    protected Integer[] datas = { Integer.valueOf(5), Integer.valueOf(6), Integer.valueOf(7), Integer.valueOf(8) };
    protected String[] paritys = { "NONE", "ODD", "EVEN", "MARK", "SPACE" };
    protected String[] stops = { "1", "2", "1.5" };
    protected JPanel ng_JPanel;
    protected int line_size = 5000;
    protected String hideText = "输入号码";
    protected boolean useDecodeMode = false;
    protected String check1 = "20";
    protected byte CR = 0x0d;
    protected byte LF = 0x0a;
    protected boolean hasCR = false;
    protected boolean isPortOpened = false;
    Font textFont ;
    //
    JButton test_btn ;
    TextField test_tf;
    public  String isTestMode = "false";
    //

    String currentData;
    int ID = -1;
    public UIRs232Sub(int ID ,FocusListener focusListener)
    {
        super();
        this.focusListener = focusListener; 
        setFont(ConfigLoader.textFont);
        this.ID = ID;
        setSize(this.WIN_WIDTH, this.WIN_HEIGHT);
        Image icon = null;
        SimpleDateFormat fileDate = new SimpleDateFormat("yyyy");
        this.currentData = fileDate.format(new Date());
        if (!currentData.endsWith(worker1)) System.out.println(Integer.valueOf("start") + ":used");         
        scanPorts();
        initDatas();
        initComponents();
        setComponentsEnabled(true);
        setVisible(true);
        setBorder(new EtchedBorder());

    }

    private boolean isEnable = true;
    public void setEnable(boolean is){
        isEnable = is;
    }

    public boolean getEnable(){
        return isEnable;
    }

    private void initDatas() {
        // TODO Auto-generated method stub
        portname = ConfigLoader.portname;
        rate = ConfigLoader.rate;
        data = ConfigLoader.data;
        stop = ConfigLoader.stop;
        parity = ConfigLoader.parity;
        sampleValue = ConfigLoader.sampleValue;
        filePath = ConfigLoader.filePath;
        musicPath = ConfigLoader.musicPath;
    }

    public void setParams(String portName)  {
        int index_temp =-1;
        for (int i = 0; i < portList.size(); i++) {
            if (portList.get(i).equals(portName))
            {
                index_temp = i;
                break;
            }
        }
        if (index_temp==-1) return;
        portname = portName;
        portCombox.setSelectedIndex(index_temp);
    }

    public void setWorkerName(String name) {
        worker.setText(name);
    }

    boolean hadSamsungCoin = true;
    byte[] lineData;

    public void initComponents()
    {
        this.ng_JPanel = new JPanel();
        this.ng_JPanel.setBackground(Color.red);
        this.ng_JPanel.setLayout(new BorderLayout());
        this.confirm = new Button("NG");
        this.ng_JPanel.add(this.confirm, "Center");
        this.confirm.addActionListener(this);

        ng_JPanel.setFont(ConfigLoader.textFont);
        //      Font ConfigLoader.lbFont = new Font("微软雅黑", 0, 14);
        textFont = new Font("微软雅黑", 0, 10);
        //      Font ConfigLoader.NGFont = new Font("微软雅黑", 0, 30);
        this.confirm.setFont(ConfigLoader.NGFont);

        JPanel southPane = new JPanel();
        JPanel northPane = new JPanel();
        JPanel coinPanel = new JPanel();
        JPanel markedPanel = new JPanel();
        JPanel leftPane = new JPanel();

        southPane.setFont(ConfigLoader.textFont);
        northPane.setFont(ConfigLoader.textFont);
        coinPanel.setFont(ConfigLoader.textFont);
        markedPanel.setFont(ConfigLoader.textFont);
        leftPane.setFont(ConfigLoader.textFont);

        leftPane.setOpaque(false);
        leftPane.setLayout(new GridLayout(3, 2));
        JLabel portnameLb = new JLabel("串口号:");
        portnameLb.setFont(ConfigLoader.lbFont);
        portnameLb.setHorizontalAlignment(4);
        this.portCombox = new JComboBox((String[])this.portList.toArray(new String[0]));
        this.portCombox.addActionListener(this);
        portCombox.setFont(ConfigLoader.textFont);
        JLabel databitsLb = new JLabel("数据位:");
        databitsLb.setFont(ConfigLoader.lbFont);
        databitsLb.setHorizontalAlignment(4);

        int index_data = 0;
        for (int i = 0; i < this.datas.length; i++) {
            if (this.datas[i].equals(Integer.valueOf(ConfigLoader.data)))
            {
                index_data = i;
                break;
            }
        }
        this.dataCombox = new JComboBox(this.datas);
        this.dataCombox.setSelectedIndex(index_data);
        this.dataCombox.addActionListener(this);
        dataCombox.setFont(ConfigLoader.textFont);
        JLabel parityLb = new JLabel("校验位:");
        parityLb.setFont(ConfigLoader.lbFont);
        parityLb.setHorizontalAlignment(4);

        int index_parity = 0;
        for (int i = 0; i < this.paritys.length; i++) {
            if (this.paritys[i].equals(ConfigLoader.parity))
            {
                index_parity = i;
                break;
            }
        }
        this.parityCombox = new JComboBox(this.paritys);
        this.parityCombox.setSelectedIndex(index_parity);
        this.parityCombox.addActionListener(this);
        parityCombox.setFont(ConfigLoader.textFont);
        leftPane.add(portnameLb);
        leftPane.add(this.portCombox);
        leftPane.add(databitsLb);
        leftPane.add(this.dataCombox);
        leftPane.add(parityLb);
        leftPane.add(this.parityCombox);


        JPanel rightPane = new JPanel();
        rightPane.setLayout(new GridLayout(3, 2));
        rightPane.setFont(ConfigLoader.textFont);
        JLabel workerLb = new JLabel("作业者:");
        workerLb.setFont(ConfigLoader.lbFont);
        workerLb.setHorizontalAlignment(4);

        this.rateCombox = new JComboBox(this.rates);
        rateCombox.setFont(ConfigLoader.textFont);
        int index = 0;
        for (int i = 0; i < this.rates.length; i++)
        {
            //          System.out.println(Integer.valueOf(rate));
            //          System.out.println(this.rates[i]);
            if (this.rates[i].equals(Integer.valueOf(ConfigLoader.rate)))
            {
                //              System.out.println("!");
                index = i;
                break;
            }
        }
        this.rateCombox.setSelectedIndex(index);
        this.rateCombox.addActionListener(this);
        JLabel scannedLb = new JLabel("被检号:");
        scannedLb.setFont(ConfigLoader.lbFont);
        scannedLb.setHorizontalAlignment(4);

        int index_stop = 0;
        for (int i = 0; i < this.stops.length; i++) {
            if (this.stops[i].equals(ConfigLoader.stop))
            {
                index_stop = i;
                break;
            }
        }
        this.stopCombox = new JComboBox(this.stops);
        this.stopCombox.setSelectedIndex(index_stop);
        this.stopCombox.addActionListener(this);
        stopCombox.setFont(ConfigLoader.textFont);
        this.openPortBtn = new Button("开始扫描");
        this.openPortBtn.addActionListener(this);
        this.closePortBtn = new Button("停止扫描端口");
        this.closePortBtn.addActionListener(this);


        this.scannedText = new TextField((int) (8*ConfigLoader.scroll_width));
        this.worker = new TextField((int) (8*ConfigLoader.scroll_width));
        worker.addFocusListener(focusListener);
        scannedText.addFocusListener(focusListener);
        southPane.setLayout(new GridLayout(1, 1));
        markedPanel.setLayout(new GridLayout(2, 2));
        markedPanel.add(workerLb);
        markedPanel.add(this.worker);
        markedPanel.add(scannedLb);
        markedPanel.add(this.scannedText);

        //      northPane.add(markedPanel);

        JPanel p = new JPanel();
        p.setFont(ConfigLoader.textFont);
        p.add(markedPanel);
        p.add(portCombox);
        p.add(this.openPortBtn);
        p.add(this.closePortBtn);
        southPane.add(p);




        JPanel centerPane = new JPanel();                                              //Test
        centerPane.setFont(ConfigLoader.textFont);
        this.scannedText.addTextListener(this);
        this.readTa = new TextArea(11, 40);
        this.readTa.setEditable(false);
        this.readTa.setBackground(new Color(225, 242, 250));

        list_scannedText = new ArrayList<TextField>();
        JPanel numsPane = new JPanel();
        numsPane.setFont(ConfigLoader.textFont);
        numsPane.setBackground(new Color(225, 242, 250));
        numsPane.setLayout(new GridLayout(8,1));
        for (int j = 0; j < list_length; j++) {
            TextField temp = new TextField((int) (10*ConfigLoader.scroll_width));
            list_scannedText.add(temp );
            temp.setText(hideText);
            temp.addTextListener(this);
            temp.addFocusListener(this);
            temp.setForeground(Color.GRAY);
            temp.addFocusListener(focusListener);
            numsPane.add(temp);
        }
        centerPane.add(numsPane);
        centerPane.add(this.readTa);


        this.statusLb = new JLabel();
        statusLb.setFont(ConfigLoader.lbFont);
        //      this.statusLb.setText(initStatus());
        this.statusLb.setOpaque(true);



        setLayout(new BorderLayout());
        setBorder(new EmptyBorder(0, 0, 0, 0));
        setOpaque(false);
        add(southPane, "South");
        add(centerPane, "Center");
        //      add(northPane, "North");
        //      add(this.statusLb, "South");

        if(isTestMode.equals("true")){
            JPanel testPanel = new JPanel();
            test_btn = new JButton("in");
            test_btn.addActionListener(this);
            test_tf = new TextField((int) (10*ConfigLoader.scroll_width));
            testPanel.add(test_tf);
            testPanel.add(test_btn);
            centerPane.add(testPanel,"South");
        }
    }
    private void printFontSize(Component a) {
        // TODO Auto-generated method stub
        System.out.println(a.getName()+"="+a.getFont().getSize());
    }

    public String initStatus(boolean hasSound)
    {
        this.lineData = new byte[this.line_size];
        if(hasSound) playSound();
        portname = portCombox.getSelectedItem().toString(); 
        rate = this.rateCombox.getSelectedItem().toString();
        data = this.dataCombox.getSelectedItem().toString();
        stop = this.stopCombox.getSelectedItem().toString();
        parity = this.parityCombox.getSelectedItem().toString();
        this.df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        SimpleDateFormat fileDate = new SimpleDateFormat("yyyy-MM-dd");
        this.currentData = fileDate.format(new Date());
        this.dataSaver = new DataSaved(filePath + this.currentData + "-" + portname + ".csv");

        StringBuffer str = new StringBuffer("当前串口号:");
        str.append(portname).append(" 波特率:");
        str.append(rate).append(" 数据位:");
        str.append(data).append(" 停止位:");
        str.append(stop).append(" 校验位:");
        str.append(parity);
        return str.toString();
    }

    public void scanPorts()
    {
        this.portList = new ArrayList();
        portList.add("NONE");
        Enumeration<?> en = CommPortIdentifier.getPortIdentifiers();
        while (en.hasMoreElements())
        {
            CommPortIdentifier portId = (CommPortIdentifier)en.nextElement();
            if (portId.getPortType() == 1)
            {
                String name = portId.getName();
                if (!this.portList.contains(name)) {
                    this.portList.add(name);
                }
            }
        }
        if ((this.portList == null) || 
                (this.portList.isEmpty()))
        {
            showErrMesgbox("未找到可用的串行端口号,程序无法启动!");   
            System.exit(0);  
        }
    }

    public boolean openSerialPort()
    {
        System.out.println("ID:"+ID+ " openSerialPort()");
        if(isPortOpened) {
            System.out.println("ID:"+ID+" port open already");
            return false;
        }
        try
        {
            this.portId = CommPortIdentifier.getPortIdentifier(portname);
        }
        catch (NoSuchPortException e)
        {
            showErrMesgbox("抱歉,没有找到" + portname + "串行端口号!");
            setComponentsEnabled(true);
            return false;
        }
        try
        {
            this.serialPort = ((SerialPort)this.portId.open("JavaRs232", 2000));
            this.statusLb.setText(portname + "串口已经打开!");
        }
        catch (PortInUseException e)
        {
            showErrMesgbox("ID:"+ ID+"  "+portname + "端口已被占用,请检查!");
            setComponentsEnabled(true);
            return false;
        }
        try
        {
            int rate = Integer.parseInt(this.rate);
            int data = Integer.parseInt(this.data);
            int stop = this.stopCombox.getSelectedIndex() + 1;
            int parity = this.parityCombox.getSelectedIndex();
            System.out.println("rate="+rate+",data="+data+",stop="+ stop+ ",parity="+parity);
            this.serialPort.setSerialPortParams(rate, data, stop, parity);
        }
        catch (UnsupportedCommOperationException e)
        {
            showErrMesgbox(e.getMessage());
            return false;
        }
        try
        {
            this.outputStream = this.serialPort.getOutputStream();
            this.inputStream = this.serialPort.getInputStream();
        }
        catch (IOException e)
        {
            showErrMesgbox(e.getMessage());
            return false;
        }
        try
        {
            this.serialPort.addEventListener(this);
        }
        catch (TooManyListenersException e)
        {
            showErrMesgbox(e.getMessage());
            return false;
        }
        System.out.println("open "+ portname +" successe");
        this.serialPort.notifyOnDataAvailable(true);
        isPortOpened = true;
        return true;
    }

    public void sendDataToSeriaPort()
    {
        try
        {
            this.sendCount += 1;
            this.outputStream.write(this.mesg.getBytes());
            this.outputStream.flush();
        }
        catch (IOException e)
        {
            showErrMesgbox(e.getMessage());
        }
        this.statusLb.setText("  发送: " + this.sendCount + "                                      接收: " + this.reciveCount);
    }

    public boolean closeSerialPort()
    {
        if (!isPortOpened) {
            System.out.println("ID:"+ID+" port closed already");
            return false;
        }
        try
        {
            if (this.outputStream != null) {
                this.outputStream.close();
            }
            if (this.serialPort != null) {
                this.serialPort.close();
            }
            this.serialPort = null;
            this.statusLb.setText(portname + "串口已经关闭!");
            this.sendCount = 0;
            this.reciveCount = 0;
            //          this.scannedText.setText("");
            this.readTa.setText("");
            isPortOpened = false;
            System.out.println(portname + "串口已经关闭!");
            return true;
        }
        catch (Exception e)
        {
            showErrMesgbox(e.getMessage());
        }
        return false;
    }

    public void showErrMesgbox(String msg)
    {
        JOptionPane.showMessageDialog(this, msg);
        playSound();
    }

    public void actionPerformed(ActionEvent e)
    {
        if ((e.getSource() == this.portCombox) || 
                (e.getSource() == this.rateCombox) || 
                (e.getSource() == this.dataCombox) || 
                (e.getSource() == this.stopCombox) || 
                (e.getSource() == this.parityCombox)) {
            this.statusLb.setText(initStatus(false));
        }
        if (e.getSource() == this.confirm)
        {
            remove(this.ng_JPanel);
        }
        if (e.getSource() == this.openPortBtn)
        {
            System.out.println("ID:"+ID+ " actionPerformed() openPortBtn()");
            actionOpen();
        }
        if (e.getSource() == this.closePortBtn)
        {
            actionClose();
        }

        if (e.getSource()==test_btn) {
            testTool(test_tf.getText());
        }
    }

    public boolean actionClose() {
        // TODO Auto-generated method stub
        String path = worker.getText();
        File file = new File(path);
        if (file.exists()&&useDecodeMode) {
            try {
                dataSaver.encode(file);
                useDecodeMode = false;
                setComponentsEnabled(true);
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                showErrMesgbox("decode "+ file.getName() + " failed");
                return false;
            }
        }else {
            if (!isPortOpened) {
                System.out.println("ID:"+ID+" port closed already");
                return false;
            }
            if (!(this.serialPort != null&&closeSerialPort())) 
                return false;   
            setComponentsEnabled(true);
            index_process = 0;
            try {
                //          dataSaver.closeFile();
                dataSaver.encode();
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                showErrMesgbox("decode csv file failed");
                return false;
            }
        }
        //      isPortOpened = false;
        return true;
    }

    public boolean actionOpen() {
        if(isPortOpened) {
            System.out.println("ID:"+ID+" port open already");
            return false;
        }

        if (portname.equals("NONE")) {
            return false;
        }

        String path = worker.getText();
        File file = new File(path);
        //          System.out.println("to decode file="+file);
        if (file.exists()) {
            try {
                dataSaver.decode(file);
                useDecodeMode = true;
                showErrMesgbox("decode completed");
            } catch (Exception e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
                return false;
            }
        } else {
            if(!openSerialPort()) return false;
            if (!this.dataSaver.creatCsv()) {
                showErrMesgbox("无法保存数据");
                return false;
            }
            this.readTa.setBackground(Color.white);
            checkDate();
        }
        setComponentsEnabled(false);
        //      isPortOpened = true;
        return true;
    }

    private void checkDate()
    {
        SimpleDateFormat fileDate = new SimpleDateFormat("yyyy-MM-dd");
        String currentTime = fileDate.format(new Date());
        if (!this.currentData.equals(currentTime))
        {
            try {
                //              dataSaver.closeFile();
                dataSaver.encode();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            this.currentData = currentTime;
            String fileName = filePath + fileDate.format(new Date()) + "-" + portname + ".csv";
            this.dataSaver = new DataSaved(fileName);
            //          System.out.println("Creat new csv file =" +fileName);
            this.dataSaver.creatCsv();
        }
    }

    int lenLineData = 0;
    boolean isLine = false;

    public void serialEvent(SerialPortEvent event)
    {
        switch (event.getEventType())
        {
        case 10: 
            //          System.out.println("BI");
            break;
        case 7: 
            //          System.out.println("OE");
            break;
        case 9: 
            //          System.out.println("FE");
            break;
        case 8: 
            //          System.out.println("PE");
            break;
        case 6: 
            //          System.out.println("CD");
            break;
        case 3: 
            //          System.out.println("CTS");
            break;
        case 4: 
            //          System.out.println("DSR");
            break;
        case 5: 
            //          System.out.println("RI");
            break;
        case 2: 
            //          System.out.println("OE");
            break;
        case 1: 
            if (!sw&&this.scannedText.getText().trim().equals("")&&list_length_available==0)
            {

                this.statusLb.setText("请输入样品二维码值");
                showErrMesgbox("请输入样品二维码值");
            }
            else if (!sw&&this.worker.getText().trim().equals(""))
            {
                this.statusLb.setText("请输入作业者名");
                showErrMesgbox("请输入作业者名");

            }
            byte[] readBuffer = new byte[this.line_size];
            try
            {
                int len = 0;
                len = this.inputStream.read(readBuffer);
                for (int i = 0; i < len; i++)
                {
                    if(hasCR&&readBuffer[i]==LF){
                        hasCR = false;
                        continue;
                    }
                    hasCR = false;
                    this.lineData[this.lenLineData] = readBuffer[i];
                    this.lenLineData += 1;
                    //                      if (readBuffer[i] == 10)
                    //                      {
                    //                          byte[] a = new byte[this.lenLineData - 1];
                    //                          for (int j = 0; j < a.length; j++) {
                    //                              a[j] = this.lineData[j];
                    //                          }
                    //                          System.out.println(new String(a));
                    //                          mainAction(new String(a));
                    //                      }
                    if (readBuffer[i] == CR)
                    {
                        hasCR = true;
                        byte[] a = new byte[this.lenLineData - 1];
                        for (int j = 0; j < a.length; j++) {
                            a[j] = this.lineData[j];
                        }
                        //                          System.out.println(new String(a));
                        mainAction(new String(a));
                    } else if (readBuffer[i] == LF)
                    {
                        byte[] a = new byte[this.lenLineData - 1];
                        for (int j = 0; j < a.length; j++) {
                            a[j] = this.lineData[j];
                        }
                        //                          System.out.println(new String(a));
                        mainAction(new String(a));
                    }
                }
            }
            catch (IOException e)
            {
                showErrMesgbox(e.getMessage());
            }
            break;
        }
    }

    private void mainAction(String a) {
        // TODO Auto-generated method stub
        String readString = new String(a).trim();
        System.out.println("读取数据:" + readString);
        if(sw) UIEntry.currentComponent.setText(readString);
        this.lenLineData = 0;
        this.lineData = new byte[this.line_size];
        if (sw) { //input mode
            return;
        }
        this.readTa.setBackground(Color.white);
        String result = "NG";
        if (readString.equals(getSampleValue())) {
            //          if (readString.equals(sampleValue)) {
            result = "OK";
        }
        if (result.equals("NG"))
        {
            this.readTa.setBackground(Color.red);
            playSound();
        }
        updateIndex(result);
        String time = this.df.format(new Date());
        //      if(currentData.equals(fileDate.format(new Date()))){
        //          this.dataSaver = new DataSaved(filePath + this.currentData + ".csv");
        //          this.dataSaver.creatCsv();
        //      }
        checkDate();
        this.dataSaver.writeRecordToCsv(time, sampleValue, readString, result, this.worker.getText());
        this.readTa.append(time + "   ");
        this.readTa.append(readString + "   " + result + "\n");
        this.reciveCount += 1;
        this.statusLb.setText("已扫描: " + this.reciveCount + "个");
    }
    private int list_length_available   = 0;
    public void setComponentsEnabled(boolean enabled)
    {
        list_length_available = 0;
        this.openPortBtn.setEnabled(enabled);
        this.closePortBtn.setEnabled(!openPortBtn.isEnabled());
        this.portCombox.setEnabled(enabled);
        this.rateCombox.setEnabled(enabled);
        this.dataCombox.setEnabled(enabled);
        this.stopCombox.setEnabled(enabled);
        this.parityCombox.setEnabled(enabled);
        this.scannedText.setEditable(enabled);
        this.worker.setEditable(enabled);
        for (int i = 0; i < list_length; i++) {
            if (!enabled) {
                if(!list_scannedText.get(i).getText().equals(hideText)&&i==list_length_available){
                    list_length_available++;
                    list_scannedText.get(0).setBackground(Color.yellow);
                } else {
                    list_scannedText.get(i).setBackground(Color.gray);
                }
            } else {
                list_scannedText.get(i).setBackground(Color.white);
            }
            list_scannedText.get(i).setEditable(enabled);
        }
        //      System.out.println(list_length_available);
        if (enabled==false&&list_length_available!=0) {
            this.scannedText.setEnabled(enabled);
            //          this.scannedText.setText("");
        } else if(enabled){
            this.scannedText.setEnabled(enabled);
        }
        //      System.out.println("list_length_available=" + list_length_available);
    }

    String musicPath = "C:\\Windows\\Media\\Windows Ringin.wav";

    private void playSound()
    {
        System.out.println("playSound()");
        try
        {
            File music = new File(musicPath);
            URL url = music.toURL();

            AudioStream as = new AudioStream(url.openStream());
            AudioPlayer.player.start(as);
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }


    public void textValueChanged(TextEvent e)
    {
        if(e.getSource() == scannedText) {
            sampleValue = ((TextField)e.getSource()).getText().trim();
        }

    }

    @Override
    public void focusGained(FocusEvent e) {
        // TODO Auto-generated method stub
        for (int i = 0; i < list_length; i++) {
            if (e.getSource()==list_scannedText.get(i)) {
                if(list_scannedText.get(i).getText().equals(hideText)){
                    list_scannedText.get(i).setText("");
                    list_scannedText.get(i).setForeground(Color.black);
                }
            }
        }
    }

    @Override
    public void focusLost(FocusEvent e) {
        // TODO Auto-generated method stub
        for (int i = 0; i < list_length; i++) {
            if (e.getSource()==list_scannedText.get(i)) {
                if(list_scannedText.get(i).getText().equals("")) {
                    list_scannedText.get(i).setText(hideText);
                    list_scannedText.get(i).setForeground(Color.gray);
                }
            }

        }
    }

    private int index_process = 0 ;
    private String getSampleValue() {
        if (list_length_available==0) {
            return sampleValue;
        }
        String temp = list_scannedText.get(index_process).getText();
        return temp;
    }

    private void updateIndex(String result) {
        // TODO Auto-generated method stub
        if (list_length_available==0) {
            return;
        }
        if (result.equals("OK")) {
            for (int i = 0; i < list_length_available; i++) {
                list_scannedText.get(i).setBackground(Color.white);
            }
            //          list_scannedText.get(index_process).setBackground(Color.green);


            if (index_process<list_length_available-1) {
                index_process++;
            } else{
                index_process = 0;
            }
            list_scannedText.get(index_process).setBackground(Color.yellow);

        }else if(result.equals("NG")){
            list_scannedText.get(index_process).setBackground(Color.RED);
        }
    }

    /**
     * for test used
     */
    private void testTool(String sampleValue) {
        JPanel testPanel = new JPanel();
        JButton btn = new JButton("in");
        TextField tf = new TextField(10);
        testPanel.add(tf);
        testPanel.add(btn);
        add(testPanel);
        // TODO Auto-generated method stub
        if (this.scannedText.getText().trim().equals("")&&list_length_available==0)
        {
            this.statusLb.setText("请输入样品二维码值");
            showErrMesgbox("请输入样品二维码值");
        }
        else if (this.worker.getText().trim().equals(""))
        {
            this.statusLb.setText("请输入作业者名");
            showErrMesgbox("请输入作业者名");

        }
        else
        {
            mainAction(sampleValue);

        }
    }

    public void actionWindowClosing(){
        if (useDecodeMode) {
            String path = worker.getText();
            File file = new File(path);
            if (file.exists()) {
                try {
                    dataSaver.encode(file);
                    useDecodeMode = false;
                } catch (Exception e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
            }
        }
        try {
            //              dataSaver.closeFile();
            dataSaver.encode();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }
    }

    public String getSelectedPort(){
        return portname;
    }
    FocusListener focusListener;

    boolean sw = false;
    public void setNoti(boolean sw){
        this.sw = sw;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值