1. Welcome to the new MacRumors forums. See our announcement and read our FAQ

How to paintImmediately() in Java?

Discussion in 'Mac Programming' started by alumac, Apr 11, 2009.

  1. macrumors member


    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{
    [INDENT]public static void main() {
    [INDENT]//creates and displays a new ImageFrame (extends JFrame)[/INDENT]
    2. ImageFrame class - JFrame

    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();	
    3. ImagePanel class - JPanel

    class ImagePanel extends JPanel{
    [INDENT]//setting up the Panel
    [INDENT]public void paintComponent(Graphics g) //works fine
    if (image != null)
    g.drawImage(image, 0, 0, null);  	 		}
    [INDENT]public void loadimage()
    //code to load the image
    public void shuffleImage()
    //swap adjacent x and x-1
    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!
  2. macrumors member

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

    new Thread(
      new Runnable() {
    	public void run() {
    		panel.shuffle ();
    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.
  3. macrumors 6502

    Just invalidate the rect. It will redraw itself immediately.

Share This Page