Reputation: 73
In my java project, I want to check the input in each JTextField in a few different classes (with the exact same code)..
Right now I have the same code copied over and over and I was suggested with 2 options:
Create a method and call the method instead.
Create a new class that extends from another class (I don't know which yet) that has the method needed.
The code I'm using now is:
totalAmount.addKeyListener(new KeyAdapter() {
@Override
public void keyTyped(KeyEvent arg0) {
//do something
}
});
And the new class is:
public class Listener extends KeyAdapter {
public void keyTyped(KeyEvent arg0){
//do something
}
}
The problem is that I don't know if I'm extending the right class, and how to use the new class I've written...
Thanks in advance!
Upvotes: 1
Views: 1432
Reputation: 7744
To do what you are wanting with your key adapter you would use
totalAmount.addKeyListener(new Listener());
and your code of your key adapter is correct.
public class Listener extends KeyAdapter {
public void keyTyped(KeyEvent arg0){
//do something
}
}
To get the text from a JTextField
you could either use this code inside your keyAdapter
System.out.println(totalAmount);
or, preferably you could use a document listener. This would be done by
public class documentListener implements DocumentListener //This is a listener
{
public void changedUpdate(DocumentEvent e){
}
public void removeUpdate(DocumentEvent e){
int lengthMe = e.getDocument().getLength();
System.out.println(e.getDocument().getText(0,lengthMe));
}
public void insertUpdate(DocumentEvent e){
int lengthMe = e.getDocument().getLength();
System.out.println(e.getDocument().getText(0,lengthMe));
}
}
and it would be added to the JTextField
with
totalAmount.getDocument().addDocumentListener(new documentListener());
Upvotes: 4