PDA

View Full Version : How to paintImmediately() in Java?




alumac
Apr 11, 2009, 07:06 PM
Hello,

I'm developing a Slide Image Puzzle in Java. I'm randomly shuffling the Image in a for loop and I want the Image to be painted on the screen after each iteration of the for loop. Using repaint() doesn't work so I'm wondering how I can implement paintImmediately() to do this.

Here's a simplified version of my program structure

1. ImageGame class - main app

class ImageGame{

public static void main() {

//creates and displays a new ImageFrame (extends JFrame)

}

}

2. ImageFrame class - JFrame

class ImageFrame extends JFrame{

ImagePanel panel = new ImagePanel(); //creates panel

//has a menu with options "loadImage" and "shuffleImage"

public void actionPerformed(ActionEvent evt)
{
Object source = evt.getSource();

if(source==loadimage)
{
panel.loadimage();
}

if(source==shuffleimage)
{
panel.ShuffleImage();
}

}


}

3. ImagePanel class - JPanel

class ImagePanel extends JPanel{

//setting up the Panel

public void paintComponent(Graphics g) //works fine
{
super.paintComponent(g);
if (image != null)
{
g.drawImage(image, 0, 0, null); }
}

public void loadimage()
{
//code to load the image
}

public void shuffleImage()
{
for(i=0;i<x;i++)
{
//swap adjacent x and x-1

repaint()
Thread.sleep(delay);
}

}


}


The repaint() doesn't work in the loop because Java only performs the repaint() at the last iteration. Therefore, I want to use paintImmediately() to paint the panel at every iteration so that the user can see how the tiles are being swapped. I understand that paintImmediately() can only be called from the EDT (event dispatch thread) so my guess is that it needs to be in the ImageFrame() class in the ActionPerformed(). I can't figure out how to do this!

Does anyone know how it can be implemented?

Thanks in advance!



alumac
Apr 12, 2009, 05:07 AM
I figured it out. If the shuffle function runs in a seperate thread, then the repaint() will be synchronous (basically it works!) :)

So I just changed a little bit of code.

When calling panel.shuffle() in class ImageFrame, I did the following..

new Thread(
new Runnable() {
public void run() {
panel.shuffle ();
}
}
).start();

Then, I simply added Thread.sleep() to in the shuffle function and voila. Probably not the most efficient way of doing this but its what I need at the moment.

garethlewis2
Apr 12, 2009, 05:10 AM
Just invalidate the rect. It will redraw itself immediately.