忽略Java代码中的focusLost(),SWT.Verify或其他SWT侦听器

时间:2010-09-15 15:52:21

标签: java swt messagebox lost-focus

在实际的SWT监听器之外,有没有办法通过代码忽略监听器?

例如,我有一个实现SWT Text Widgets的java程序,小部件有:

  • SWT.Verify侦听器以过滤掉不需要的文本输入。
  • ModifyListeners等待正确数量的有效输入字符,并自动将焦点(使用setFocus())设置为下一个有效字段,并按Tab键顺序跳过其他文本窗口小部件。
  • focusLost(FocusEvent)FocusListeners,等待文本小部件失去焦点,执行其他输入验证,并根据用户输入执行SQL查询。

我遇到的问题是清除文本小部件。其中一个小部件的格式为“#### - ##”(四个数字,一个连字符,然后是两个数字),我已经实现了这个侦听器,它是SWT Snippet Snippet179的修改版本。该文本小部件的初始文本是“ - ”,以向用户提供关于预期格式的视觉反馈。只有数字是可接受的输入,并且程序会在适当的位置自动跳过连字符。

     /*
      * This listener was adapted from the "verify input in a template (YYYY/MM/DD)" SWT Code
      * Snippet (also known as Snippet179), from the Snippets page of the SWT Project.
      * SWT Code Snippets can be found at:
      * http://www.eclipse.org/swt/snippets/
      */
     textBox.addListener(SWT.Verify, new Listener() 
  {
   boolean ignore;
   public void handleEvent(Event e) 
   {
    if (ignore) return;
    e.doit = false;
    StringBuffer buffer = new StringBuffer(e.text);
    char[] chars = new char[buffer.length()];
    buffer.getChars(0, chars.length, chars, 0);
    if (e.character == '\b') 
    {
     for (int i = e.start; i < e.end; i++) 
     {
      switch (i) 
      {
       case 0: /* [x]xxx-xx */
       case 1: /* x[x]xx-xx */
       case 2: /* xx[x]x-xx */
       case 3: /* xxx[x]-xx */ 
       case 5: /* xxxx-[x]x */
       case 6: /* xxxx-x[x] */
       {
        buffer.append(' '); 
        break;
       }
       case 4: /* xxxx[-]xx */
       {
        buffer.append('-');
        break;
       }
       default:
        return;
      }
     }
     textBox.setSelection(e.start, e.start + buffer.length());
     ignore = true;
     textBox.insert(buffer.toString());
     ignore = false;
     textBox.setSelection(e.start, e.start);
     return;
    }

    int start = e.start;
    if (start > 6) return;
    int index = 0;
    for (int i = 0; i < chars.length; i++) 
    {
     if (start + index == 4) 
     {
      if (chars[i] == '-') 
      {
       index++;
       continue;
      }
      buffer.insert(index++, '-');
     }
     if (chars[i] < '0' || '9' < chars[i]) return;
     index++;
    }
    String newText = buffer.toString();
    int length = newText.length();
    textBox.setSelection(e.start, e.start + length);
    ignore = true;
    textBox.insert(newText);
    ignore = false;

    /*
     * After a valid key press, verifying if the input is completed 
     * and passing the cursor to the next text box.
     */
    if (7 == textBox.getCaretPosition())
    {
                /*
                 * Attempting to change the text after receiving a known valid input that has no results (0000-00).
                 */
                if ("0000-00".equals(textBox.getText()))
                {
                    // "0000-00" is the special "Erase Me" code for these text boxes.
                    ignore = true;
                    textBox.setText("    -  ");
                    ignore = false;    
                }

     // Changing focus to a different textBox by using "setFocus()" method.
     differentTextBox.setFocus();
    }
   }
  }
  );

正如您所看到的,我从代码中的不同点清除此文本小部件的唯一方法是分配“0000-00”

textBox.setText("000000")

并在侦听器中检查该输入。收到该输入后,监听器将文本更改回“ - ”(四个空格,一个连字符,然后两个空格)。

还有一个focusLost Listener解析此文本小部件的空格,然后为了避免不必要的SQL查询,如果输入无效(即包含空格),它会清除/重置所有字段。

 // Adding focus listener to textBox to wait for loss of focus to perform SQL statement.
 textBox.addFocusListener(new FocusAdapter() 
 {
  @Override
  public void focusLost(FocusEvent evt) 
  {
   // Get the contents of otherTextBox and textBox. (otherTextBox must be <= textBox)
   String boxFour = otherTextBox.getText();
   String boxFive = textBox.getText();

   // If either text box has spaces in it, don't perform the search.
   if (boxFour.contains(" ") || boxFive.contains(" "))
   {
       // Don't perform SQL statements.  Debug statement.
       System.out.println("Tray Position input contains spaces.  Ignoring.");

                //Make all previous results invisible, if any.
                labels.setVisible(false);
                differentTextBox.setText("");
                labelResults.setVisible(false);
   }
   else
   {
             //... Perform SQL statement ...
            }
  }
 }
 );

行。通常,我在此代码中使用SWT MessageBox小部件与用户进行通信,或者希望在验证输入后将文本小部件更改回空状态。问题是消息框似乎创建了一个focusLost事件,并且使用.setText(string)方法受到文本小部件上存在的SWT.Verify侦听器的影响。

有关在代码中有选择地忽略这些侦听器但是为所有其他用户输入保留它们的任何建议吗?

提前感谢您的协助。

2 个答案:

答案 0 :(得分:2)

如果您为侦听器命名而不是使用匿名侦听器,则可以随时添加和删除它。

示例:

 // Adding focus listener to textBox to wait for loss of focus to perform SQL statement.
 FocusAdapter focusTextBox = new FocusAdapter() 
 {
  @Override
  public void focusLost(FocusEvent evt) 
  {
   // Get the contents of otherTextBox and textBox. (otherTextBox must be <= textBox)
   String boxFour = otherTextBox.getText();
   String boxFive = textBox.getText();

   // If either text box has spaces in it, don't perform the search.
   if (boxFour.contains(" ") || boxFive.contains(" "))
   {
       // Don't perform SQL statements.  Debug statement.
       System.out.println("Tray Position input contains spaces.  Ignoring.");

                //Make all previous results invisible, if any.
                labels.setVisible(false);
                differentTextBox.setText("");
                labelResults.setVisible(false);
   }
   else
   {
             //... Perform SQL statement ...
            }
  }
 };

然后,您可以通过执行以下操作添加侦听器:

textBox.addFocusListener(focusTextBox);

删除就像这样简单:

textBox.removeFocusListener(focusTextBox);

确保在完成您想要以编程方式实现的内容后重新启用侦听器,或者您的代码不会像您期望的那样行事。

答案 1 :(得分:1)

我没有测试您的代码,但是在侦听器中尝试方法isFocusControl()以查看用户是否输入了文本,或者当焦点不在{{1时}时使用setText()设置文本}}