2

I have a BufferedImage that is being drawn onto a JPanel. What I'm trying to do is set the pixels of the BufferedImage by:

for (int yy = 0; yy < 18; yy++) {
    for (int xx = 0; xx < 24; xx++) {
        image.setRGB(xx * 32, yy * 32, 32, 32, pixels, 0, 32);
    }
}

pixels is defined and instantiated, 18 is the height of the image/32 and 24 is the width of the image/32. This method seems to work, but only half of the time. What happens is that it will sometimes draw all of the image, sometimes it will draw maybe the first third of it (then stop), and sometimes it will draw the first 1/5th and then skip to another part of the image and draw some there then stop. No errors thrown, the application isn't pausing or loading. Sometimes it works, sometimes it doesn't. Any reason why this could be occurring?

kneedhelp
  • 555
  • 4
  • 18

1 Answers1

3

My guess is that yours is a threading issue since the code you show could take quite a long time (relatively speaking) to work, and to get it to work best with Swing, you must make sure to run it in a background thread, and then notify the GUI when it is done, and have the GUI then update the image. A SwingWorker would work well for this.

Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
  • I failed to mention that it is in a swingworker. However, I have another thread (not the one the swingworker is called from) that constantly repaints the image, so maybe that could be interfering? Also, what do you mean by notify the GUI? – kneedhelp Jan 10 '16 at 20:04
  • @kneedhelp: by notify, I mean be sure to call `get()` on the SwingWorker to retrieve the image and call `repaint()` on the GUI when this nested loop has completed its function. I usually use a PropertyChangeListener for this purpose. – Hovercraft Full Of Eels Jan 10 '16 at 20:19
  • Oh so you mean like use the swingworker to return a BufferedImage to return a BufferedImage and then draw that on top of the JPanel? – kneedhelp Jan 10 '16 at 20:58
  • @kneedhelp: yes. Or even if you don't return the BufferedImage, if you try to change it in vitro, you still need to notify the GUI to repaint after its change is complete. And you should always call `get()` on a SwingWorker when it's done, regardless of whether you use what is returned, since this is how you catch exceptions from within the worker. If still stuck though, post your [mcve]. – Hovercraft Full Of Eels Jan 10 '16 at 21:19
  • You'll never believe this, but I added `System.out.println(pixels);` and it worked (after I changed the swingworker.) So I guess it was a timing issue or something. Thanks! – kneedhelp Jan 10 '16 at 21:32