| RHS => Allan => Programming 2 => Notes => Tips using Swing |
Updated:
02/02/2004 23:36 WebMaster: allanhn@rhs.dk |
Tips using Swing
Source: Various tutorials from Sun
When a component needs to be displayed or redrawn its paint() or update() method is automatically invoked with an appropriate Graphics context - standard components paints (or repaints) automatically, you don't have to change or do anything!!
If you need to paint from an object (i.e. using drawRect() etc.) decide which superclass to use - normally JPanel or more specialized component will do.
Keep all your painting inside paintComponent(Graphics
g)
Before performing any custom painting you should paint the components
background ("erase everything") by invoking super.paintComponent(Graphics
g).
This is extra important if any component is lying behind this one
(they may have to be updated as well).
The object of type Graphics provides methods for the painting (drawRect(), drawImage(), drawString() etc.)
repaint() requests that components
is to be scheduled to paint itself. Don't call paintComponent(),
call repaint() - let the system decide!
When pace is tight the system might combine multiple repaint() requests
into a single - you have no guarantee that all your repaint() requests
will be performed.
repaint() has 2 useful forms:
| void repaint() | requests entire component to be repainted | |
| void repaint(int, int, int, int) | requests only part of component to be repainted This form can help performance to increase significantly |
The painting area can be reduced using repaint(int, int, int, int) or by using Graphics.setClip().
When using setClip() always remember to restore the
original area:
| Rectangle oldArea = g.getClipBounds(); Rectangle newArea = new Rectangle(.....); g.setClip(newArea); //perform custom painting g.setClip(oldArea); |
NEVER override
paint() when you are using Swing!!
You'll confuse the automatic painting
system!
So remember: NEVER override paint() when
you are using Swing!!
Prefer Icon to Image when
you are using Swing (if possible).
Some components (like JLabel) needs to invoke their setOpaque(true) if background color is to be changed.
To improve performance of image-animation: