Reputation: 4562
I limit my JTextFields
to accept only numbers. I was using following code for this.
// my textboxes
t1=new JTextField(10);
t2=new JTextField(10);
t3=new JTextField(10);
// for the first one
t1.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= '0') && (c <= '9') ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
}
}
});
Suppose I have 20 texboxes
which need the same validation check. So do we need to write this code 20 times? Can I write a common method to implement this? I am new to Swing
.
Upvotes: 1
Views: 8161
Reputation: 61
//look event keypressed . : private void montoingresoKeyPressed(java.awt.event.KeyEvent evt) {
if(Character.isLetter(evt.getKeyChar()))
{
//do what you want on this event, when key is pressed named evt
}
}
Upvotes: 0
Reputation: 336
I would make a private boolean method (if it is only used in this class) or public if it it called for elsewhere as well eg. using reg ex:
public boolean checkToBeNumberInput(char c, KeyEvent e){
if(!char c.matches("[0-9]")||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
return false;
}
return true;
}
Then call for this boolean method and if it returns true:
if(checkToBeNumberInput()==false){
System.out.println("only numbers are allowed!");
}
This is a fast draft but I hope it helps someone
Upvotes: 0
Reputation: 285450
Again, use a DocumentFilter as this will handle copy and paste, this will allow filtering before the Document accepts the text:
import javax.swing.*;
import javax.swing.text.*;
public class DocListenerEg extends JPanel {
private static final int FIELD_COUNT = 5;
private JTextField[] fields = new JTextField[FIELD_COUNT];
public DocListenerEg() {
MyDocFilter myFilter = new MyDocFilter();
for (int i = 0; i < fields.length; i++) {
fields[i] = new JTextField(5);
((PlainDocument) fields[i].getDocument()).setDocumentFilter(myFilter);
add(fields[i]);
}
}
private class MyDocFilter extends DocumentFilter {
public void insertString(DocumentFilter.FilterBypass fb, int offset,
String text, AttributeSet attr) throws BadLocationException {
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
return;
}
}
fb.insertString(offset, text.toUpperCase(), attr);
}
public void replace(DocumentFilter.FilterBypass fb, int offset,
int length, String text, AttributeSet attrs)
throws BadLocationException {
for (char c : text.toCharArray()) {
if (!Character.isDigit(c)) {
return;
}
}
fb.replace(offset, length, text.toUpperCase(), attrs);
}
}
private static void createAndShowGui() {
DocListenerEg mainPanel = new DocListenerEg();
JFrame frame = new JFrame("DocListenerEg");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(mainPanel);
frame.pack();
frame.setLocationByPlatform(true);
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
createAndShowGui();
}
});
}
}
Upvotes: 9
Reputation: 723
Try DocumentFilter as described in http://www.jroller.com/dpmihai/entry/documentfilter
Upvotes: 4
Reputation: 13539
Create a class called :
NumberOnlyTextField
Make it extend JTextField, and add the addKeyListener(..) code in the constructor. There you have your very own number validation textfield.
Upvotes: 0
Reputation: 9795
Save your anonymus class into a variable:
KeyListener keyListener= new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= '0') && (c <= '9') ||
(c == KeyEvent.VK_BACK_SPACE) ||
(c == KeyEvent.VK_DELETE))) {
getToolkit().beep();
e.consume();
}
}
}
And then
t1.addKeyListener(keyListener);
t2.addKeyListener(keyListener);
t3.addKeyListener(keyListener);
...
Upvotes: 0