监听热键
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);
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) {
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;
public class ExcelParser {
String className = "ExcelParser";
private String filePath;
private String tempDirPath;
private String deCompressPath;
private String path_sheetssXml = "\\xl\\worksheets";
public boolean deCompressionCompleted = false;
public Notifier noti;
Element ele_si;
Element ele_c;
Element ele_r;
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() {
}
};
initFile();
}
ZipFile xlsxFile;
NodeList siList;
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());
tempDirPath = excelFile.getParent() + "\\tempFiles\\";
deCompressPath = tempDirPath + "deCompressFiles";
System.out.println(tempDirPath);
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) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
}
}
private void refreshTempDir() {
File tempDir = new File(tempDirPath);
if(tempDir.exists()) {
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);
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;
}
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);
if(((String)column.getAttribute("r")).equals(col+String.valueOf(rowName))){
result = getTextByCellName(column, siList);
Util.l(className,methodName, "result:" + result);
}
}
}
} catch (ZipException e) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
} catch (IOException e) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
} catch (SAXException e) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
} catch (ParserConfigurationException e) {
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")) {
int rIndex = Integer.parseInt(value.getTextContent());
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) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
return "";
}
return value.getFirstChild().getTextContent();
}
}
public boolean isdeCompressionCompleted(){
return deCompressionCompleted;
}
public interface Notifier {
public void onExcelDeCompressionCompleted();
}
public void compressToExcel(String srcPathNameDir,String targerFile) {
new Thread(new Runnable() {
@Override
public void run() {
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();
}
void creatSharedStringXml() {
}
void newSheetXml() {
}
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) {
e.printStackTrace();
}
NodeList list_row_sheetXml = doc_sheet.getElementsByTagName("row");
Element target_row = null;
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);
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) {
if (target_colOfRow.getAttribute("t") != null&& target_colOfRow.getAttribute("t").equals("s")) {
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 {
}
}
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) {
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");
}
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) {
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) {
TransformerFactory factory = TransformerFactory.newInstance();
Transformer former;
try {
former = factory.newTransformer();
former.transform(new DOMSource(doc), new StreamResult(new File(filePath)));
} catch (TransformerException e) {
e.printStackTrace();
}
}
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);
}
} 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);
}
}
}
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++) {
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"));
if (countOfResult!=-1&&results.size()>=countOfResult) {
break;
}
}
}
}
if (countOfResult!=-1&&results.size()>=countOfResult) {
break;
}
}
} catch (IOException | SAXException | ParserConfigurationException e) {
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 {
}
return results;
}
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);
}
} 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);
}
}
}
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+"";
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"));
if (countOfResult!=-1&&results.size()>=countOfResult) {
break;
}
}
}
}
if (countOfResult!=-1&&results.size()>=countOfResult) {
break;
}
}
} catch (IOException | SAXException | ParserConfigurationException e) {
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 {
}
return results;
}
public void closeFile() {
String methodName = "closeFile";
try {
xlsxFile.close();
} catch (IOException e) {
e.printStackTrace();
Util.l(className, methodName, e.getMessage());
}
}
public void refreshExcel() {
String methodName = "refreshExcel()";
try {
xlsxFile = new ZipFile(new File(filePath));
dbf = DocumentBuilderFactory.newInstance();
ZipEntry sharedStringXML = xlsxFile.getEntry("xl/sharedStrings.xml");
if (sharedStringXML!=null) {
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);
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());
}
}
}
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;
public static void l(String className ,String methodName ,String info){
System.out.println("[" + className + "]" + ".."
+ methodName + "() ->" + info);
if (isSaveLog) {
try {
if (writer==null) {
String rootPath = System.getProperty("java.class.path");
File ff = new File(rootPath);
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) {
e.printStackTrace();
}
}
}
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");
result = subString.substring(0, atEndIndex);
return result;
}
public static String getStatusFromText(String text){
if(text.equals("PASS")||text.equals("NA")||text.equals("FAIL"))return text;
return null;
}
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};
}
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;
}
public static String ingeterToCol(int i) {
String buffer = "";
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;
}
public static int getIntegerFormString(String string) {
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() {
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);
textFont = new Font("微软雅黑", 0, 10);
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++)
{
if (this.rates[i].equals(Integer.valueOf(ConfigLoader.rate)))
{
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);
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();
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.setOpaque(true);
setLayout(new BorderLayout());
setBorder(new EmptyBorder(0, 0, 0, 0));
setOpaque(false);
add(southPane, "South");
add(centerPane, "Center");
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) {
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.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() {
String path = worker.getText();
File file = new File(path);
if (file.exists()&&useDecodeMode) {
try {
dataSaver.encode(file);
useDecodeMode = false;
setComponentsEnabled(true);
} catch (Exception e1) {
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.encode();
} catch (Exception e1) {
e1.printStackTrace();
showErrMesgbox("decode csv file failed");
return 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);
if (file.exists()) {
try {
dataSaver.decode(file);
useDecodeMode = true;
showErrMesgbox("decode completed");
} catch (Exception e1) {
e1.printStackTrace();
return false;
}
} else {
if(!openSerialPort()) return false;
if (!this.dataSaver.creatCsv()) {
showErrMesgbox("无法保存数据");
return false;
}
this.readTa.setBackground(Color.white);
checkDate();
}
setComponentsEnabled(false);
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.encode();
} catch (Exception e) {
e.printStackTrace();
}
this.currentData = currentTime;
String fileName = filePath + fileDate.format(new Date()) + "-" + portname + ".csv";
this.dataSaver = new DataSaved(fileName);
this.dataSaver.creatCsv();
}
}
int lenLineData = 0;
boolean isLine = false;
public void serialEvent(SerialPortEvent event)
{
switch (event.getEventType())
{
case 10:
break;
case 7:
break;
case 9:
break;
case 8:
break;
case 6:
break;
case 3:
break;
case 4:
break;
case 5:
break;
case 2:
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] == CR)
{
hasCR = true;
byte[] a = new byte[this.lenLineData - 1];
for (int j = 0; j < a.length; j++) {
a[j] = this.lineData[j];
}
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];
}
mainAction(new String(a));
}
}
}
catch (IOException e)
{
showErrMesgbox(e.getMessage());
}
break;
}
}
private void mainAction(String a) {
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) {
return;
}
this.readTa.setBackground(Color.white);
String result = "NG";
if (readString.equals(getSampleValue())) {
result = "OK";
}
if (result.equals("NG"))
{
this.readTa.setBackground(Color.red);
playSound();
}
updateIndex(result);
String time = this.df.format(new Date());
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);
}
if (enabled==false&&list_length_available!=0) {
this.scannedText.setEnabled(enabled);
} else if(enabled){
this.scannedText.setEnabled(enabled);
}
}
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) {
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) {
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) {
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);
}
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);
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) {
e1.printStackTrace();
}
}
}
try {
dataSaver.encode();
} catch (Exception e1) {
e1.printStackTrace();
}
}
public String getSelectedPort(){
return portname;
}
FocusListener focusListener;
boolean sw = false;
public void setNoti(boolean sw){
this.sw = sw;
}
}