我想要做的是当我们要在TextField中输入内容时,它不应该允许符号。如何排除符号?
我使用的代码:
if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') {
jTextField2.setText("");
}
答案 0 :(得分: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();
}
});
}
}
答案 1 :(得分:2)
它在JTextField中有两个属性而不是一个:
(1)字符串“text”表示和(2)任何Class“value”
你需要的只是放一个格式化程序来转换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);
在变更后立即获得价值