2010-12-11 68 views
2

我有一个文本字段和一个搜索按钮。如果用户输入正好13位数字(条形码),那么我想自动触发搜索。在文本字段中正好有13个字符时触发一个按钮

我在文本字段上有一个DocumentListener,并且正在处理insertUpdate方法以确定已输入了13位数字。我可以直接在那个时候调用搜索代码(并且它确实有效),但是尽管已经键入了第13个字符,但是在搜索完成之前它并不实际显示在屏幕上。

我宁愿而是触发搜索按钮,并尝试了两种方式:

DocumentListener dlBarcode = new DocumentAdaptor() { 
    public void insertUpdate(DocumentEvent e) { 
     String value = jtBarcode.getText(); 
     if (isBarcode(value)) { 
      ActionEvent ae = new ActionEvent((Object)jbSearch, 
          ActionEvent.ACTION_PERFORMED, ""); 
      Toolkit.getDefaultToolkit().getSystemEventQueue().postEvent(ae); 
     } 
    } 
}; 

二是使用方法:

jbSearch.dispatch(ae); 

这两种方法都似乎引起jbSearch的ActionListener的是触发。你能否建议我做错了什么?

回答

0

camickr的建议奇怪的是没有工作的第13个字符没有得到画,直到搜索已经完成。马克的评论建议使用SwingWorker做了诀窍。我的DocumentListener代码现在看起来像:

DocumentListener dlBarcode = new DocumentAdaptor() { 
public void insertUpdate(DocumentEvent e) { 
    String value = jtBarcode.getText(); 
    if (isBarcode(value)) { 
     PerformSearch ps = new PerformSearch(value); 
     ps.execute(); 
    } 
} 

而且我PerformSearch样子:

class PerformSearch extends SwingWorker<Product, Void> { 
private String key = null; 
public PerformSearch(String key) { 
    this.key = key; 
} 
@Override 
protected Product doInBackground() throws Exception { 
    return soap.findProduct(this.key); 
} 
protected void done() { 
    Product p = null; 
    try { 
     p = get(); 
    } catch (InterruptedException e) { 
    } catch (ExecutionException e) { 
    } 
    prod = p; 
    if (prod != null) { 
     ... populate text fields 
    } 
    else { 
     ... not found dialog 
    } 
} 

感谢您的帮助。非常感激。

3

不要以编程方式尝试“单击”按钮。它没有被按下,所以为什么试图欺骗你的代码认为它是?将动作与执行动作的动作分开是一个重要的原则。以类比的方式,想想你的汽车点火。转动钥匙会触发点火。因此,如果我想设计一个远程汽车启动器,我是否会创建一个机械机器人来插入和转动钥匙,或者我的系统是否应该直接向点火信号发出信号?

只需定义一个方法,将其称为performSearch或其他什么,并且您的按钮上都有ActionListener,而您的DocumentListener都各自调用该方法。

一个注意事项:不要忘记实际注册您的文档侦听器与您正在使用的文本控件。

2

我可以直接在那个时候调用搜索代码(并且它确实有效),但是虽然已经输入了第13个字符,但是直到搜索完成后才显示在屏幕上。

将调用包装到SwingUtilities.invokeLater()中的搜索代码中。这会将搜索放在事件派发线程的末尾,因此在搜索开始之前将更新文本字段。使用的invokeLater的

DocumentListener dlBarcode = new DocumentAdaptor() { 
    public void insertUpdate(DocumentEvent e) { 
     String value = jtBarcode.getText(); 
     if (isBarcode(value)) { 
      SwingUtilities.invokeLater(new Runnable() 
      { 
       public void run() 
       { 
        invokeSearchMethod(); 
       } 
      }); 
     } 
    } 
}; 
+0

我完全想他这么说。这很接近真实的答案,但我个人建议使用SwingWorker代替在后台执行搜索,然后在稍后对UI进行更新。 – 2010-12-12 07:10:50

+0

感谢您的建议,并且我尝试过使用invokeLater,但第13个字符仍然只在搜索完成后才会绘制。从invokeLater的文档中,我会认为Event Dispatch线程会在调用搜索之前完成绘制文本字段,但看起来不是。我将尝试下一步使用SwingWorker。 – Geoff 2010-12-12 11:17:11

相关问题