【问题标题】:showMessageDialog() gets called for two times in FocusListenershowMessageDialog() 在 FocusListener 中被调用两次
【发布时间】:2012-11-13 04:00:03
【问题描述】:

我在 JFrame 中有 2 个文本字段,当焦点从 textfield1 丢失时,我想验证 textfield1 中的数据。所以我在FocusLost() 方法中使用了FocusListenershowMessageDialog(),然后将焦点重新设置回textfield1。当我单击除 textfield1 之外的 JFrame 窗口内的任何组件时,它工作正常,但是当我单击 JFrame 窗口外的任何位置时,showMessageDialog() 被调用 两次 并且焦点转到 textfield2 而焦点应保持在 textfield1 上。

    @Override
    public void focusGained(FocusEvent e) {}

    @Override
    public void focusLost(FocusEvent e) {
        boolean show = false;
        String theRegex = "[0-9]";
        Pattern checkRegex = Pattern.compile(theRegex);
        Matcher regexMatcher = checkRegex.matcher( MemberID );
        while ( !regexMatcher.find() && show==false){
            JOptionPane.showMessageDialog(null,"Please enter numbers","Validation Error",JOptionPane.ERROR_MESSAGE);
            MemberID_Text.requestFocusInWindow();
    MemberID_Text.selectAll();
            show = true;

        }

    }

【问题讨论】:

  • 您应该为此使用InputVerifier,这就是它的设计目的。以Validating Input 为例。听起来您不止一次将焦点侦听器附加到该字段。
  • 鉴于show 属性的使用,更合乎逻辑的标题是shown(过去时)或hide
  • 使用 DocumentFilter,大多数 Swing Listeners 被触发了两次
  • 如果您想要 JTextField 进行验证,请使用 JFormattedTextField
  • 只是一个让代码更干净的提示。我会选择:!show 而不是 show==false。

标签: java swing validation


【解决方案1】:

您可以这样做来验证是否输入了数字,并避免一起使用正则表达式

     class IntVerifier extends InputVerifier {

  @Override public boolean verify(JComponent input) {
      String text =((JTextField) input).getText();
      int n = 0; 

          try {
      n = Integer.parseInt(text); } 

      catch (NumberFormatException e) {
  return false; 
       }

  return true;
      }
      }

然后在文本字段上使用输入验证器

 IntVerifier intv = new IntVerifier();      
 myTextField = new JTextField();
 myTextField.setInputVerifier(intv);

【讨论】:

  • 请阅读验证的api文档(提示:它提到了副作用 :-)
  • @kleopatra 检查 JComponent 的输入是否有效。这种方法应该没有副作用。它返回一个布尔值,指示参数输入的状态。这不是我们想要的吗? link
  • 下一步:检查您的实施是否符合该合同......以及为什么不:-)
  • @singha 不要使用这个特定的实现,它违反了它的合同! (不过,只需返回 false 而不是显示 optionPane 即可修复它)
  • @kleopatra 感谢您对显示选项窗格的建议会导致副作用
猜你喜欢
  • 1970-01-01
  • 2011-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 2021-04-09
  • 2016-04-01
  • 2012-05-05
相关资源
最近更新 更多