Become a MacRumors Supporter for $50/year with no ads, ability to filter front page stories, and private forums.

alumac

macrumors member
Original poster
Mar 31, 2009
40
0
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

Code:
class ImageGame{

[INDENT]public static void main() {

[INDENT]//creates and displays a new ImageFrame (extends JFrame)[/INDENT]

}[/INDENT]

}

2. ImageFrame class - JFrame

Code:
class ImageFrame extends JFrame{

[INDENT]ImagePanel panel = new ImagePanel(); //creates panel

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

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

[INDENT]if(source==loadimage)
{
panel.loadimage();
}[/INDENT]

[INDENT]if(source==shuffleimage)
{
panel.ShuffleImage();
}[/INDENT]

}
[/INDENT][/INDENT]

}

3. ImagePanel class - JPanel

Code:
class ImagePanel extends JPanel{

[INDENT]//setting up the Panel

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

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

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

repaint()
Thread.sleep(delay);
}[/INDENT]

}[/INDENT][/INDENT]


}

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

macrumors member
Original poster
Mar 31, 2009
40
0
figured it out

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..

Code:
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.
 
Register on MacRumors! This sidebar will go away, and you'll see fewer ads.