Use swing timer correctly to hide Jlabel

1

I need to hide a Jlabel with Swing Timer after 5 seconds, the problem is mainly that once the Timer starts, this apparently is not stopping at any time, since when using the Show button for the second time, the Jlabel disappears almost instantaneously, what would be missing in this code so that the mentioned thing is fulfilled?

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;

public class respuesta extends javax.swing.JFrame{

    public respuesta() { 
        initComponents();
        label1.setVisible(false);
    }

public void ocultar(){
        int delay = 5000; //millisegundos
        ActionListener taskPerformer = new ActionListener() {
           @Override
           public void actionPerformed(ActionEvent evt) {
                 label1.setVisible(false);
           }
        };
     new Timer(delay, taskPerformer).start();
}

private void btnMostrarActionPerformed(java.awt.event.ActionEvent evt) {                                            
        label1.setVisible(true);
        ocultar();
} 

public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new respuesta().setVisible(true);
            }
        });
    }

}
    
asked by Dexen142 11.05.2017 в 15:37
source

1 answer

2

To prevent a recurrence, simply invoke the method setRepeats from javax.swing.Timer with false ; That is:

Timer timer = new Timer(delay, evt -> {
    label1.setVisible(false);
});
timer.setRepeats(false);
timer.start();

More information at How to Use Swing Timers .

    
answered by 11.05.2017 / 16:48
source