在JAVA 中,想一个编辑框输入内容,如果一遇到输入的字符不属于字符串或数字或'_',则马上提示错误,自动清空刚才输入的错误字符,如何实现?

解决方案 »

  1.   

    你说的是用AWT
    还是在网页中啊?
    要是用的是AWT.SWING的话,用TextListener 中的void textValueChanged(TextEvent e)  方法。
    Pattern p = Pattern("[^w\-]");
    应该用这个吧,。初学。
      

  2.   

    主要是给文本框加个键盘监听器
    public void keyReleased(KeyEvent e)
    {

    }
    public void keyTyped(KeyEvent e)
    {
            // text1.setText("123456789");
    }
    public void keyPressed(KeyEvent e)
    {   
          char k=e.getKeyChar();
          if  ((k>='A' && k<= 'z') || (k>='0' && k<='9')|| k == '_')
             {
             //JOptionPane.showMessageDialog(null,"正常");
            
             }
      else
         text1.setText("");
    }
      

  3.   

    我想用正则表达式实现,在SWING中设计
      

  4.   

    /**
         * this class is used to restrict the input, it makes sure that
         * the text of the text field is a digit string.that is, 'a','Z',
         * '_','$'and so on are all forbidden.
         * @author feng
         *
         */
        private class OnlyDigit extends PlainDocument{
            private JTextField f;        public OnlyDigit(JTextField f){
                this.f = f;
            }
            public void insertString(int offset,
                                     String str, 
                                     AttributeSet attSet) 
            throws BadLocationException{
                StringBuffer tmp = new StringBuffer(f.getText());
                tmp.insert(offset,str);
                Pattern p = Pattern.compile("^-?\\d*(\\.)?\\d*$");
                Matcher m = p.matcher(tmp.toString());
                if(m.find()){
                    super.insertString(offset,str,attSet);                
                }
            }
        }----------------        a = new JTextField(5);
    //......        
            a.setDocument(new OnlyDigit(a));
      

  5.   

    [^a-zA-Z0-9_]
    正则只能匹配,不能帮你删除清空
    配合后台正好