On Wed, 19 Dec 2007 09:31:01 -0800, Daniel Pitts
<newsgroup.spamfilter@virtualinfinity.net> wrote:
Whoops, be careful.
You will freeze your UI completely if you use this approach!
Your loop should be done outside of the EDT. The synchronization will
be a bit tricky, but I bet you could figure it out. My suggestion is to
batch a number of results from "pickColour" in a separate worker thread,
and then use EventQueue.invokeLater() to add them to your buffered image
and call repaint().
Using that approach, the hard work will be done on the worker thread,
and the easy work on the EDT. This will keep your GUI responsive AND
your user informed.
Thanks for the advice.
My test code now looks as below.
rossum
// --- Partial Code Starts ---
class GraphPanel extends JPanel {
final int biXpos = 30;
final int biYpos = 60;
final int biHeight = 100;
final int biWidth = 150;
volatile BufferedImage mOffScreenImage;
/** To run the pixel clculations */
Thread mCalculator;
volatile boolean mStopCalcRequested = false;
public GraphPanel() {
// Set up off screen image
mOffScreenImage = new BufferedImage(biWidth,
biHeight, BufferedImage.TYPE_INT_BGR);
// Start pixel calculation thread
PixelCalc pc = new PixelCalc();
mCalculator = new Thread(pc);
mCalculator.start();
} // end constructor
/** Calculates colours for pixels */
class PixelCalc implements Runnable {
public void run() {
Graphics2D g2d = mOffScreenImage.createGraphics();
final int xLimit = mOffScreenImage.getWidth();
final int yLimit = mOffScreenImage.getHeight();
for (int x = 0; x < xLimit; ++x) {
for (int y = 0; y < yLimit; ++y) {
g2d.setColor(pickColour(x, y));
g2d.drawLine(x, y, x + 1, y + 1);
} // end for
// Check for termination request
if (mStopCalcRequested) { return; }
Thread.yield(); // Play nice
// Show partial progress
if (x % 50 == 49) {
repaint();
} // end if
// Artificial Delay
try {
Thread.sleep(20);
} catch (InterruptedException iex) {
repaint();
return;
} // end try/catch
} // end for
// Show completed image
repaint();
} // end run()
private Color pickColour(int x, int y) {
switch ((x + y) % 3) {
case 0: return Color.CYAN;
case 1: return Color.GREEN;
case 2: return Color.MAGENTA;
default: return Color.BLACK;
} // end switch
} // end pickColor()
} // end class PixelCalc
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);
// Resize
Container parent = this.getParent();
this.setSize(parent.getWidth(), parent.getHeight());
// Show image
g.drawImage(mOffScreenImage, biXpos, biYpos, null);
} // end paintComponent()
} // end class GraphPanel
// --- Partial Code Finishes ---
Still got problems. you can't access a buffered images graphics from a
different thread without synchronization. You might be better off
that time.
graphics object you created.