Richard,
The exact instances when paint() gets called is
very dependent on the JVM implementation. For
example, (commenting out Java2D stuff), running
your example on JDK 1.1.7 produces 2 paints at
startup, and 2 on each resize. On 1.2.2 with HotSpot,
there is one at startup, and 1 with each mouse
position change on resizing.
If your paint method is complicated, the standard
way to alleviate flickering is to use double-buffering.
You can roll your own double buffering code with the
AWT, but Swing has it built-in. Attached is a version
of StringArt that only paints when needed.
<<StringArt.java>>
--Andy
[EMAIL PROTECTED]
(206) 662-4943
import java.awt.*;
import java.awt.geom.*;
public class StringArt {
public static void main(String[] args) {
Frame f = new ApplicationFrame("StringArt v1.0");
javax.swing.JComponent c = new javax.swing.JComponent() {
private int mNumberOfLines = 25;
private Color[] mColors = { Color.red, Color.green, Color.blue };
private Dimension pd = new Dimension(0, 0);
public void paintComponent(Graphics g) {
Dimension d = getSize();
if (pd.width == d.width && pd.height == d.height) return;
pd = d;
Graphics2D g2 = (Graphics2D)g;
System.out.println("Paint");
g.clearRect(0, 0, d.width, d.height);
for (int i = 0; i < mNumberOfLines; i++) {
double ratio = (double)i / (double)mNumberOfLines;
Line2D line = new Line2D.Double(0, ratio * d.height,
ratio * d.width, d.height);
g2.setPaint(mColors[i % mColors.length]);
g2.draw(line);
}
}
};
c.setOpaque(true);
c.setDoubleBuffered(true);
f.add(c);
f.setSize(200, 200);
f.setVisible(true);
}
}
> ----------
> From: R.M.Everson[SMTP:[EMAIL PROTECTED]]
> Sent: Tuesday, February 01, 2000 8:02 AM
> To: [EMAIL PROTECTED]
> Subject: [JAVA2D] Paint invoked 3 times
>
> <<File: StringArt.java>><<File: ATT1314667.txt>><<File:
>ApplicationFrame.java>><<File: ATT1314668.txt>>
>
> Hello,
>
> Can anyone shed any light on this, please?
>
> I'm puzzled why the paint method is invoked 3 times when a frame is
> first displayed. For small applications this isn't a problem, but if
> the paint method is complicated it results in annoying flickering.
>
> To see a demo compile the following StringArt.java and
> ApplicationFrame.java from Jonathan Knudsen's book. On startup I get
> "Paint" printed 3 times. In fact, if you run the ShowOff class from
> the same book the image is redrawn three times. In both cases simply
> exposing the window results in a single invocation of paint().
>
> Any pointers, cures or expressions of sympathy gratefully received.
>
> Many thanks,
> Richard Everson.
>
>
StringArt.java