Sentimental
Sentimental

Reputation: 187

Cannot move a panel slowly

I have a simple question. I want to move a JPanel (inside an another JPanel) a little each step, so it will looks like moving continuously ('Number' is my class extending JPanel):

Number n = (Number)this.findComponentAt(x, y);
 for(int pp= 0; pp<10; pp++){
try {
        Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
n.setLocation(x-10*pp, y);
n.repaint();
 }

The paintComponent method for Number is:

public void paintComponent(Graphics g){
  super.paintComponent(g);
  numIc.paintIcon(this, g, 0, 0);       
}

However, it is not moving step by step but moving suddenly to final destination after 10 delays! I searched questions but didn't find helpful answers.

Upvotes: 0

Views: 73

Answers (1)

camickr
camickr

Reputation: 324127

Read the section from the Swing tutorial on Concurrency so understand about the Event Dispatch Thread. The Thread.sleep() Method is causing the EDT to sleep so the GUI can't repaint itself.

Use a Swing Timer to schedule the animation. Take a look at the Table of Contents from the above link and you will also find a section on How to Use Swing Timers.

Also, why would you create a custom component just to paint an Icon? Just use a JLabel with an Icon and let the label to the painting. Don't reinvent the wheel.

Upvotes: 1

Related Questions