[可以作为《编程导论(Java)·9.3.4键盘事件处理》的补充材料,GUI部分内容太多,同学们需要做一些例程自学各种控件的使用——yqj2065是木有心思在书中或上课时讲这些东西的。GUI部分搞清楚好莱坞原则/观察者模式、编写几个事件处理demo就可以了,其他请大家自学。]
扫描枪读取的数据,通常自带回车。开发相关系统时,需要编写一个模拟扫描枪的QRReaderDialog。
JTextField作为数据接受控件,在它上面按下Enter键,可以监听Action事件或Key事件;而“按下Enter键”,就需要用到java.awt.Robot。
一个小例子:在Netbeans中编写的InputDemo
package demo; import com.sun.glass.events.KeyEvent; import java.awt.Robot; /** * * @author yqj2065 */ public class InputDemo extends javax.swing.JFrame { private final Robot robot; public InputDemo() throws Exception { robot = new Robot(); //创建一个robot对象 initComponents(); } public void keyPress(int key) { robot.delay(50); robot.keyPress(key); robot.keyRelease(key); } private void initComponents() { //略 } private void input_TextFieldKeyPressed(java.awt.event.KeyEvent evt) { if (KeyEvent.VK_ENTER == evt.getKeyCode()) { KeyPressed_Label.setText(input_TextField.getText()); } } private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) { int i = (int) (Math.random() * 10000000) + 1; String str = i + "二维码数据"; input_TextField.setText(str); input_TextField.requestFocus(); this.keyPress(java.awt.event.KeyEvent.VK_ENTER); } private void input_TextFieldActionPerformed(java.awt.event.ActionEvent evt) { ActionPerformed_Label.setText(input_TextField.getText()); } /** * @param args the command line arguments */ public static void main(String args[]) {//略 } // Variables declaration - do not modify private javax.swing.JLabel ActionPerformed_Label; private javax.swing.JLabel KeyPressed_Label; private javax.swing.JTextField input_TextField; private javax.swing.JButton jButton1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; // End of variables declaration }
QRReaderDialog是一个简单的对话框,点击其上的Read once按钮,产生一条字符串——表示读取的二维码信息。MyJTextField将作为Read once按钮的Action事件监听器。
设计MyJTextField时,就有两个选项:MyJTextField在setText(qrCode)后是否自带回车。
如果自带回车,装箱操作窗口将监听MyJTextField的Action事件或Key事件;
不自带回车,装箱操作窗口将监听MyJTextField的内容变化事件,即对MyJTextField对象inputTextField,调用下面的语句:
inputTextField.getDocument().addDocumentListener(new MyDocumentListenerImpl());
两种方式都可以达到目的,前者使用java.awt.Robot,后者要自定义MyDocumentListener implements javax.swing.event.DocumentListener ,并给出其实现类。
package qrms.ui.util; import javax.swing.event.DocumentEvent; /** * * @author yqj2065 */ public abstract class MyDocumentListener implements javax.swing.event.DocumentListener { public abstract void textChangedHandle(); @Override public void insertUpdate(DocumentEvent e) { textChangedHandler(); } @Override public void removeUpdate(DocumentEvent e) { } @Override public void changedUpdate(DocumentEvent e) { } }