How to use Swing Timer ActionListener

2019-07-21 03:03发布

问题:

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);


 }});

回答1:

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.