Repainting a JPanel?

Here is the main method for my JPanel extension:

publicvoid paintComponent(Graphics g)

{

super.paintComponent(g);

setBackground(Color.white);

g.setColor(Color.green);

for(count = 0; count <= 500; count=count+x)

{

g.drawLine(count,0,count,500);

}

for(count = 0; count <=500; count=count+y)

{

g.drawLine(0,count,500,count);

}

g.setColor(Color.red);

g.drawLine(0,250,500,250);

g.setColor(Color.black);

for(count = 0; count < 50; count++)

{

g.drawLine(count*10, 500 - points[count], (count + 1)*10, 500 - points[count + 1]);

}

The first two for loops create a grid background. The third takes the first 50 values in an integer array and 'graphs' them by connecting the dots. I feed it one new integer at a time, and it shifts all the others over to the left, resulting in an oscilloscope-type display. However, whenever I feed it a new integer, I call the invalidate() and repaint() methods on it. But nothing happens. I tried making a new method just for plotting points, but it keeps giving me errors whenever I try using Graphics g. What do I do?

[1537 byte] By [jedifia] at [2007-11-26 18:07:57]
# 1

> I call the invalidate() and repaint() methods on it.

No need to call invalidate().

> But nothing happens

Well you need to understand how painting works. The paintComponent() method is called whenever the Paint Manager determines that the panel needs to be repainted. So when the GUI is displayed it is called once. If you minimize and restore the GUI is is called again. When you use the repaint() method, the Paint Manager simply calls the paint() method which in turn calls the paintComponent() method.

So you can't have code that calls repaint() multiple times, because you will loose all the painting the next time the Paint Manager decides to repaint the panel. So you have two choices:

a) build all the paint logic in the paintComponent() method (which can be inefficient if you have lots of painting to do)

b) do your custom painting on a BufferedImage and then just have the paintComponent() method paint the buffered image. For an example of this approach search the forum for my "drawonimage" example.

Sure something happens. The first line causes the

camickra at 2007-7-9 5:39:28 > top of Java-index,Desktop,Core GUI APIs...
# 2

Okay, cool. I rewrote the logic in the paintComponent() method to a createImage() method like you suggested. It turns out that my original method worked though: it was hanging due to a simple logic error that I've since fixed. Thanks for the input though, the BufferedImage idea works like a charm.

BTW, is there any easy way that I can get the volume (amplitude) of the sound coming in through the mic input without having to save it, and without using the JMF library?

If I were to create a BufferedReader that read the input stream from the mic, and just read int values from that, would it work?

Thanks

-Joe

jedifia at 2007-7-9 5:39:28 > top of Java-index,Desktop,Core GUI APIs...