1
I created a KeyListener
for verification of a String
typed, if it is in the bank. If it does, it sends an alert.
The question now is that I have about 50 jTextFields
. It is possible to create a KeyListener
that can be used for all jTextFields
? Or I have to create one for each jTextField
? 'Cause in my code I specify that I’m picking up the String
of jTextField1
for example, not serving for what I need now.
Here is the code of 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) {
}
};
Method of making the check
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("");
}
}
}
}
};
I used your first suggestion, but this
ver == false
, even though the amount entered is in the bank. I couldn’t figure out why yet .– Rodrigo
I got something, I added the code in "update1" in the question. At first it is now checking correctly, when the value is not in the list, it displays the
JOptionPane
, when it is , he continues. I would still like to find out why it is not working from the previous suggested outside.– Rodrigo
@Rodrigo provide a [mcve] of its application then has nothing further to suggest as there is nothing to test.
– user28595
@Rodrigo see the edition, if it still persists, do what I guided in the previous comment.
– user28595