0

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.

Ryan T. Grimm
  • 1,307
  • 1
  • 9
  • 17
Sentimental
  • 187
  • 2
  • 13
  • I can't really tell from the limited information in your question, but you're probably sleeping on the event dispatch thread, which causes your GUI to sleep. – Gilbert Le Blanc Mar 19 '14 at 02:29
  • *"I searched questions but didn't find helpful answers."* Which questions? Links please.. – Andrew Thompson Mar 19 '14 at 05:43
  • 1
    possible duplicate of [animate JPanel (slide in) with timer](http://stackoverflow.com/questions/16316132/animate-jpanel-slide-in-with-timer) – trashgod Mar 19 '14 at 07:28

1 Answers1

1

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.

camickr
  • 321,443
  • 19
  • 166
  • 288
  • If I use Swing.Timer in the main panel I have to handle the event in actionPerformed() methods. But as the main panel contains many objects of Number, others will be affected. Btw, there are some other operations for Number class, so I use JPanel. – Sentimental Mar 19 '14 at 20:33
  • @Sentimental, still no reason to use a JPanel to paint the Icon. – camickr Mar 19 '14 at 23:47
  • I want to set the location of the Number component; however, it is not convenient to use JLabel's setLocation. – Sentimental Mar 29 '14 at 19:06