Reputation: 1
private void jTextField1KeyPressed(java.awt.event.KeyEvent evt) {
int x=evt.getKeyCode();
if(x>=96&&x<=105)
{
evt.setKeyCode(8);//Here 8 is used for Backspace key to remove the numeric character entered
}
Int This code i want the user not to type any numeric value in jTextField but if he does so then i m trying to remove it off during runtime only.... I wrote this code but its not working as i expected it to be... Plzz Help me!!
Upvotes: 0
Views: 1224
Reputation: 2549
While perhaps not the very best way to do it, here is one very simple way.
You can override the paintComponent()
method of the JTextField
like this:
JTextField textField = new JTextField(text) {
@Override
protected void paintComponent(Graphics grphcs) {
super.paintComponent(grphcs);
String newStr = "";
for (char c : getText().toCharArray()) {
if (!Character.isDigit(c)) {
newStr += c;
}
}
setText(newStr);
}
};
Upvotes: 0
Reputation: 347204
You really should avoid KeyListeners
, they are too limiting for what you are ultimately trying to achieve and you're only going to end up with a mutation exception as you try and change the fields document while the field is trying to change the document.
You really should be using a DocumentFilter, that's what it's design for.
((AbstractDocument)field.getDocument()).setDocumentFilter(new DocumentFilter() {
@Override
public void insertString(FilterBypass fb, int offset, String text, AttributeSet attr) throws BadLocationException {
StringBuilder sb = new StringBuilder(64);
for (char c : text.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
fb.insertString(offset, text, attr);
}
@Override
public void replace(FilterBypass fb, int offset, int length, String text, AttributeSet attrs) throws BadLocationException {
StringBuilder sb = new StringBuilder(64);
for (char c : text.toCharArray()) {
if (Character.isDigit(c)) {
sb.append(c);
}
}
fb.replace(offset, length, sb.toString(), attrs);
}
});
This is a really basic example, there are plenty on SO.
Apart from avoiding mutation exceptions, the filter intercepts the update before it reaches the document/field, so the incoming changes won't be visible of the screen, you also capture any paste events or setText
calls.
Upvotes: 2