I created a KeyListener
to check for a String
typed, if it is in the database. If yes let it proceed, if not, issue an alert.
The question now is that I have about 50 jTextFields
. Is it possible to create a KeyListener
that can be used for all jTextFields
? Or do I have to create one for each jTextField
? For in my code I specify that I'm taking String
of jTextField1
for example, not serving what I need now.
Here is the code for KeyListener
private final KeyListener listener = new KeyListener() {
@Override
public void keyTyped(KeyEvent e) {
}
@Override
public void keyReleased(KeyEvent e) {
int max = 4;
if (max == 4) {
String digitado = jTextField1.getText().trim();
if (digitado.length() == max) {
verificaStringDigitada(digitado);
}
}
}
@Override
public void keyPressed(KeyEvent e) {
}
};
Scanning method
public void verificaStringDigitada(String teste) {
CarroDao carroDao = new CarroDao();
List<Carro> carros = new ArrayList();
carros = carroDao.consultarCarros();
boolean ver = false;
for (Carro carro : carros) {
if (carros.contains(teste)) {
ver = true;
}
}
if (ver == false) {
JOptionPane.showMessageDialog(null, "Verifique a digitação!");
jTextField1.setText("");
}
}
Update1:
private final KeyAdapter listener = new KeyAdapter() {
@Override
public void keyReleased(KeyEvent e) {
JTextField field = (JTextField) e.getSource();
int max = 4;
if (max == 4) {
String digitado = field.getText().trim();
if (digitado.length() == max) {
CarroDao carroDao = new CarroDao();
List<Carro> carros = new ArrayList();
carros = carroDao.consultarCarros();
boolean ver = false;
for (Carro carro : carros) {
if (digitado.equals(carro.getNumero())) {
ver = true;
}
}
if (ver == false) {
JOptionPane.showMessageDialog(null, "Verifique a digitação!");
field.setText("");
}
}
}
}
};