我正在尝试从USB刷卡读卡器中提取卡号。我放在一起的代码适用于1次滑动,GUI冻结。如果线程睡眠位被注释掉,则GUI不会冻结,但我在输出时得到0。关于我正在做什么的任何建议都会有所帮助。这是代码
userText.getDocument().addDocumentListener(new DocumentListener() {
@Override
public void changedUpdate(DocumentEvent e) {
validate(e);
}
@Override
public void removeUpdate(DocumentEvent e) {
validate(e);
}
@Override
public void insertUpdate(DocumentEvent e) {
validate(e);
}
public void validate(DocumentEvent e) {
String currText = "";
try {
Document doc = (Document) e.getDocument();
currText = doc.getText(0, doc.getLength());
} catch (BadLocationException e1) {
e1.printStackTrace();
}
if (currText.contains("%")) { // To check if the field has key-in data or CardReader data
Runnable doRun = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000); // This delay is to make sure that the Card data is on the JTextField after a swipe
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String check = userText.getText();
String s[] = check.split("[;=]");
if(s.length > 1){
System.out.println(s[1]); //Extract the Card number
userText.setText("");
userText.setText(s[1]);
Thread.currentThread().interrupt();
//Thread.currentThread().isInterrupted();
return;
}
}
};
SwingUtilities.invokeLater(doRun);
System.out.println("Checked");
} ;
}
});
JButton loginButton = new JButton("Check");
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Username " + userText.getText();
data += ", Code: "
+ new String(passwordText.getPassword());
statusLabel.setText(data);
}
});
编辑:根据Boris和RealSkeptic的建议,这是工作代码,
if (currText.contains("%")) { // To check if the field has key-in data or CardReader data
/* Runnable doRun = new Runnable() {
@Override
public void run() {
try {
Thread.sleep(1000); // This delay is to make sure that the Card data is on the JTextField after a swipe
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String check = userText.getText();
String s[] = check.split("[;=]");
if(s.length > 1){
System.out.println(s[1]); //Extract the Card number
userText.setText("");
userText.setText(s[1]);
Thread.currentThread().interrupt();
//Thread.currentThread().isInterrupted();
return;
}
}
};
SwingUtilities.invokeLater(doRun); */
SwingWorker<Void, Void> worker = new SwingWorker<Void, Void>(){
protected Void doInBackground() throws Exception {
try {
Thread.sleep(1000); // This delay is to make sure that the Card data is on the JTextField after a swipe
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String check = userText.getText();
String s[] = check.split("[;=]");
if(s.length > 1){
System.out.println(s[1]); //Extract the Card number
userText.setText("");
userText.setText(s[1]);
}
return null;
}
};
worker.execute();
System.out.println("Checked");
} ;