2012-11-16 85 views
0

我想要做的是當我們要在TextField中輸入內容時,它不應該允許符號。如何排除符號?JTextField中的符號驗證

的代碼我使用:

if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') { 
     jTextField2.setText(""); 
    } 
+2

化妝主題明確 – vels4j

+6

使用['DocumentFilter'](http://docs.oracle.com/javase/6/docs/ API /使用javax /鞦韆/文本/ DocumentFilter.html)。 –

回答

6

你應該使用DocumentFilter。這裏是一個非常簡單的/基本演示例如:

import java.awt.FlowLayout; 

import javax.swing.JFrame; 
import javax.swing.JTextField; 
import javax.swing.SwingUtilities; 
import javax.swing.text.AbstractDocument; 
import javax.swing.text.AttributeSet; 
import javax.swing.text.BadLocationException; 
import javax.swing.text.DocumentFilter; 

public class TestDocumentFilter { 

    private void initUI() { 
     JFrame frame = new JFrame(TestDocumentFilter.class.getSimpleName()); 
     frame.setLayout(new FlowLayout()); 
     final JTextField textfield = new JTextField(20); 
     ((AbstractDocument) textfield.getDocument()).setDocumentFilter(new DocumentFilter() { 
      @Override 
      public void insertString(FilterBypass fb, int offset, String string, AttributeSet attr) throws BadLocationException { 
       string = string.replace("&", "").replace("@", ""); 
       super.insertString(fb, offset, string, attr); 
      } 

      @Override 
      public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException { 
       text = text.replace("&", "").replace("@", ""); 
       super.replace(fb, offset, length, text, attrs); 
      } 
     }); 
     frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
     frame.add(textfield); 
     frame.setSize(300, 300); 
     frame.setLocationRelativeTo(null); 
     frame.setVisible(true); 
    } 

    public static void main(String[] args) { 
     SwingUtilities.invokeLater(new Runnable() { 

      @Override 
      public void run() { 
       new TestDocumentFilter().initUI(); 
      } 
     }); 
    } 

} 
2

JFormattedTextField

它具有兩個屬性,而不是一個在JTextField中:

(1)字符串 「文本」 的節目和(2)的任何類「值」

所有你需要的是把它轉換的stringToValue()格式化,並valueToString()

import java.text.ParseException; 
import javax.swing.JFormattedTextField; 
import javax.swing.text.DefaultFormatter; 
import javax.swing.text.JTextComponent; 

... 

    DefaultFormatter formatter = new DefaultFormatter() { 
    { 
     setValueClass(String.class); // property "value" of String.class 
     setAllowsInvalid(false); // doesnt matter in current example, but very usefull 
     setCommitsOnValidEdit(true); // convert value back to text after every valid edit 
    } 
    @Override 
    public Object stringToValue(String string) throws ParseException { 
     string = string.replace("&","").replace("@",""); 
     return string; 
    } 
    }; 

    JTextComponent txt = new JFormattedTextField(formatter); 

再加上你可以

txt.addPropertyChangeListener("value", yourPropertyChangeListener); 

到更改後立即獲得價值