2

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


 }});
aterai
  • 9,658
  • 4
  • 35
  • 44
Samuel Musa
  • 68
  • 2
  • 11
  • I don't see your attempt to try to use a Timer in your code posted. Please let's see what you've learned from the tutorials, and please show us exactly what problem you're having with your attempt. Also to help us now and to help yourself in the future, please edit your code and change your variable names to conform with Java naming conventions: class names all start with an upper-case letter and method/variable names with a lower-case letter. This will make it **much** easier for others (**us**) to understand your code better. – Hovercraft Full Of Eels Feb 14 '15 at 22:52
  • Also, what is Oracle? Another JButton? A JLabel? If it's a different component such as a JLabel, you're probably better off using a CardLayout (and a Swing Timer) to swap components. – Hovercraft Full Of Eels Feb 14 '15 at 22:55
  • Then yes, use a CardLayout, and swap the components using a Swing Timer as in [this example](http://stackoverflow.com/a/25276481/522444). – Hovercraft Full Of Eels Feb 14 '15 at 22:57

1 Answers1

4

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.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Chronio
  • 757
  • 3
  • 8