简体   繁体   中英

How to use Swing Timer ActionListener

So I wanted to complete an action then pause for a certain amount of time then complete another action. I heard Thread.sleep() isn't good because it freezes the gui or something like that before completing the task. I know I need to use javax.swing.Timer or java.util.Timer for one execution task but I really don't understand how. Here's the code. Credit is a JButton .

Credits.addActionListener(new ActionListener() {

        public  void actionPerformed (ActionEvent e){
          Credits.setVisible(false);
          Oracle.setBounds(550,280,500,500);    
          Oracle.setFont(new java.awt.Font("Arial", Font.BOLD, 40));
          Oracle.setForeground(new java.awt.Color(240,240,240));
          Oracle.setText("Credits To:");
          // I want to wait  or pause or sleep  for 5000 milliseconds  
          // Then Change The Icon 
 TimeClassAdd tcAdd = new TimeClassAdd();
    timer = new Timer(1000, tcAdd);
    timer.start();
    timerLabel.setText("IT HAS BEGUN");

  long stopTime = System.currentTimeMillis();
  long elapsedTime = stopTime - startTime;
  while (elaspedTime >= 5000) {
     break;}


 Oracle.setIcon(OraclePNG);


 }});

As the example in the Java API docs for javax.swing.Timer shows:

int delay = 5000; //milliseconds
ActionListener taskPerformer = new ActionListener() {
    public void actionPerformed(ActionEvent evt) {
        //...Perform a task...
    }
};
Timer timer = new Timer(delay, taskPerformer);
timer.setRepeats(false);
timer.start();

Hint: Use the Java API docs if you're unsure how something works. It saves you a lot of trouble.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM