showMessageDialog()在FocusListener中被调用两次

时间:2012-11-13 04:00:03

标签: java swing validation

我在JFrame中有2个文本字段,我想在textfield1中丢失焦点时验证textfield1中的数据。所以我使用了FocusListener并在showMessageDialog()方法中使用了FocusLost(),然后将焦点重新设置回textfield1。当我点击JFrame窗口中除textfield1之外的任何组件时,它工作正常,但当我点击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;

        }

    }

1 个答案:

答案 0 :(得分:0)

您可以执行此操作来验证是否输入了数字,并且一起避免使用正则表达式

     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);