Search code examples
javajlabeljtextfield

Refreshing a label through jtextfield


i am developing a project to a class and i came up with a stand-still. So, what i want to do is to refresh the label when the user presses enter in the textfield to verify the ID.

Here is my code to catch when "enter" key is pressed, it's an event of the textfield "txtNbi":

if (evt.getKeyCode() == 10) {
    this.BI = txtNbi.getText();
    String BIs[];
    BIs = DadosAplicacao.getInstance().getBIs();
    for (int i = 0; i < BIs.length; i++) {
        System.out.println("BI: " + this.BI + "\nBIlista: " + BIs[i]);
        if (this.BI.equals(BIs[i])) {
            encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
            this.repaint();
        } else {
            encontrou.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Cross.png")));
            this.repaint();
        }
    }
}

txtNbi = name of my textfield;
BIs = array of strings that get pre-inserted IDs from the 'DadosAplicacao' class;
encontrou = name of my label that receives the image as an icon

So here is my problem:

I have the following data:
- BIs[0] = 12345678
- BIs[1] = 87654321
- BIs[2] = 54321678

When i type in the first 2 the label doesn't change to the "Ok.png" icon, but when i type the last one the label changes his icon to "Ok.png"!

Can anyone help me fix this?


Solution

  • you need a break after you found the typed ID

    if(this.BI.equals(BIs[i]))
    {
        encontrou.setIcon(newjavax.swing.ImageIcon(getClass().getResource("/pt/estg/dint/imagens/Ok.png")));
        this.repaint();
        break;
    }