01: package org.gui4j.core.swing;
02:
03: import java.awt.BorderLayout;
04: import java.awt.Dimension;
05: import java.awt.Graphics;
06: import java.awt.Image;
07: import java.awt.Insets;
08:
09: import javax.swing.JPanel;
10:
11: /**
12: * A normal JPanel with the added possibility to
13: * optionally set a background image.
14: * The image will be scaled to match the current size
15: * of the panel.
16: */
17: public class JPanelImage extends JPanel {
18: public static final String SCALE = "scale";
19: public static final String TILE = "tile";
20: public static final String SINGLE = "single";
21:
22: private Image img;
23: private String mode;
24:
25: public JPanelImage() {
26: this (null);
27: }
28:
29: /**
30: * Constructor.
31: * @param img The background image. If it is <code>null</code>,
32: * this JPanelImage will behave like a normal JPanel.
33: */
34: public JPanelImage(Image img) {
35: super (new BorderLayout());
36: this .img = img;
37: }
38:
39: protected void paintComponent(Graphics g) {
40: // We implement the background image as custom painting.
41: // The background of the normal JPanel will be painted by its
42: // UI delegate in super.paintComponent() and then we
43: // "overpaint" it by the image. That way, we don't have to call
44: // setOpaque(false) and the handling of null image is straight forward.
45:
46: super .paintComponent(g);
47: if (img != null && isOpaque()) {
48: Insets insets = getInsets();
49: int top = insets.top;
50: int left = insets.left;
51: Dimension size = getSize();
52: size = new Dimension(size.width
53: - (insets.left + insets.right), size.height
54: - (insets.top + insets.bottom));
55:
56: if (mode == SCALE) {
57: g.drawImage(img, left, top, size.width, size.height,
58: this );
59: } else if (mode == TILE) {
60: int width = img.getWidth(this );
61: int height = img.getHeight(this );
62: if (width > 0 && height > 0) {
63: for (int row = top; row < size.height; row += height) {
64: for (int col = left; col < size.width; col += width) {
65: g.drawImage(img, col, row, this );
66: }
67: }
68: }
69: } else // SINGLE or no mode specified
70: {
71: g.drawImage(img, left, top, this );
72: }
73: }
74: }
75:
76: public void setImg(Image image) {
77: img = image;
78: //repaint();
79: }
80:
81: public void setMode(String mode) {
82: this.mode = mode;
83: }
84:
85: }
|