Reputation: 11
What I want to do is when we are going to type something inside the TextField, it should not allow symbols. How to exclude symbols?
The code I used:
if (evt.getKeyChar()=='&'||evt.getKeyChar()=='@') {
jTextField2.setText("");
}
Upvotes: 0
Views: 365
Reputation: 70
it has two properties instead of one in JTextField :
(1) String "text" shows and (2) any Class "value"
All you need is to put a formatter which converts stringToValue(), and 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);
plus you can
txt.addPropertyChangeListener("value", yourPropertyChangeListener);
to get value instantly after change
Upvotes: 2
Reputation: 47617
You should use a DocumentFilter. Here is a very simple/basic demo example:
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();
}
});
}
}
Upvotes: 6