Java JTextField中的符号验证
我想做的是,当我们要在文本字段中键入某些内容时,它应该不允许使用符号。如何排除符号 我使用的代码是:Java JTextField中的符号验证,java,swing,jtextfield,keylistener,documentfilter,Java,Swing,Jtextfield,Keylistener,Documentfilter,我想做的是,当我们要在文本字段中键入某些内容时,它应该不允许使用符号。如何排除符号 我使用的代码是: if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') { jTextField2.setText(""); } 你应该使用一个。下面是一个非常简单/基本的演示示例: import java.awt.FlowLayout; import javax.swing.JFrame; import javax.swing.J
if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') {
jTextField2.setText("");
}
你应该使用一个。下面是一个非常简单/基本的演示示例:
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();
}
});
}
}
它有两个属性,而不是JTextField中的一个:
(1) 字符串“text”显示和(2)任何类的“value”
您所需要的只是放置一个格式设置程序,用于转换stringToValue()和valueToString()
而且你可以
txt.addPropertyChangeListener("value", yourPropertyChangeListener);
要在更改后立即获取值,请使用。
txt.addPropertyChangeListener("value", yourPropertyChangeListener);