Problem: I don't know where to put my painting code.
paintComponent
method of any component descended from JComponent
.Problem: The stuff I paint doesn't show up.
repaint
is invoked on your component whenever its appearance needs to be updated.Problem: My component's foreground shows up, but its background is invisible. The result is that one or more components directly behind my component are unexpectedly visible.
JPanel
s, for example, are opaque by default in many but not all look and feels. To make components such as JLabel
s and GTK+ JPanel
s opaque, you must invoke setOpaque(true)
on them.JPanel
or a more specialized JComponent
descendant, then you can paint the background by invoking super.paintComponent
before painting the contents of your component.paintComponent
method:
g.setColor(getBackground()); g.fillRect(0, 0, getWidth(), getHeight()); g.setColor(getForeground());
Problem: I used setBackground
to set my component's background color, but it seemed to have no effect.
JLabel
, for example, you must also invoke setOpaque(true)
on the label to make the label's background be painted.Problem: I'm using the exact same code as a tutorial example, but it doesn't work. Why?
paintComponent
method, then this method might be the only place where the code is guaranteed to work.Problem: How do I paint thick lines? patterns?
Problem: The edges of a particular component look odd.
setBorder
except on JPanel
s and custom subclasses of JComponent
.Border
objects? If so, don't invoke setBorder
on the component.Problem: Visual artifacts appear in my GUI.
setOpaque
method to set component opacity if necessary. For example, the content pane must be opaque, but components with transparent backgrounds must not be opaque.Problem: The performance of my custom painting code is poor.
getClip
or getClipBounds
method of Graphics
to determine which area you need to paint. The less you paint, the faster it will be.repaint
that specifies the painting region.Problem: The same transforms applied to seemingly identical Graphics
objects sometimes have slightly different effects.
Graphics
method translate
) before invoking paintComponent
, any transforms that you apply have a cumulative effect. This doesn't matter when doing a simple translation, but a more complex AffineTransform
, for example, might have unexpected results.If you don't see your problem in this list, see Solving Common Component Problems and Solving Common Layout Problems.