1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91
| public class MyRenderPanel extends JComponent {
public static final String RENDER_METHOD_PROPERTY = "RenderMethod";
public enum RenderMethod {
ACTIVE, OFFSCREEN
}
private RenderMethod renderMethod = RenderMethod.ACTIVE;
private BufferedImage image = null;
/** Getter.
* @see #setRenderMethod
*/
public RenderMethod getRenderMethod() {
return renderMethod;
}
/** Setter.
* @see #getRenderMethod
*/
public void setRenderMethod(RenderMethod value) {
if (value == null) {
value = RenderMethod.ACTIVE
}
RenderMethod oldValue = renderMethod;
renderMethod = value;
firePropertyChange(RENDER_METHOD_PROPERTY, oldValue, value);
if (value == RenderMethod.ACTIVE) {
image = null;
}
repaint();
}
[...]
/** Dessin personnalise.
* @param graphics Surface de dessin independante de la sortir.
* @param width Largeur de la surface de dessin.
* @param height Hauteur de la surface de dessin.
*/
private void renderDrawing(Graphics2D graphics, double width, double height) {
[...]
}
/** {@inheritDoc}
*/
@Override protected void paintComponent(Graphics graphics) {
// Peinture par defaut du composant.
super.paintComponent(graphics);
// Calcul de la taille de la surface de dessin independament du Border du composant.
Dimension size = getSize();
Insets insets = getInsets();
int width = size.width - (insets.left + insets.right);
int height = size.height - (insets.top + insets.bottom);
//Rendu.
RenderMethod renderMethod = getRenderMethod();
switch (renderMethod) {
// Rendu dans une image.
case OFFSCREEN: {
// L'image est reinitialisee si la taille du composant a change.
if ((image == null) || (width != image.getWidth() || (height != image.getHeight())) {
// Taille d'image non-valide.
if ((width <= 0) || (height <= 0)) {
return;
}
image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
try {
renderDrawing(g2d, width, height);
}
finally {
g2d.dispose();
}
}
g.drawImage(image, 0, 0, null);
}
break;
// Dessin direct a l'ecran.
case ACTIVE:
default: {
Graphics2D g2d = (Graphics2D)graphics.create(insets.left, insets.top, width, height);
try {
renderDrawing(g2d, width, height);
}
finally {
g2d.dispose();
}
}
}
} |
Partager