How to use Swing Timer ActionListener

爷,独闯天下 提交于 2020-01-05 03:50:06

问题


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.



来源:https://stackoverflow.com/questions/28521173/how-to-use-swing-timer-actionlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!