package edu.princeton.swing; import java.awt.*; import javax.swing.*; /** * PImagePanel is like a JPanel, except that its background can be set to an image. * * @author btsang * @version 7.1 */ public class PImagePanel extends JComponent { private Icon background; /** * Constructs a new PImagePanel. */ public PImagePanel(Icon background, LayoutManager layout) { this.background = background; setLayout(layout); setDoubleBuffered(true); setOpaque(true); } /** * Constructs a new PImagePanel. */ public PImagePanel(Icon background) { this(background, new FlowLayout()); } /** * Constructs a new PImagePanel. */ public PImagePanel() { this(null, new FlowLayout()); } /** * Override javax.swing.JComponent's getPreferredSize method so that the background image is * taken into consideration. */ public Dimension getPreferredSize() { Dimension size = super.getPreferredSize(); size.width = Math.max(size.width, background.getIconWidth()); size.height = Math.max(size.height, background.getIconHeight()); return size; } /** * Gets the background icon. * * @return The Icon being displayed in the background of this panel. */ public Icon getBackgroundIcon() { return background; } /** * Sets the background icon. * * @param background The Icon to be displayed in the background of this panel. */ public void setBackgroundIcon(Icon background) { this.background = background; } /** * Override javax.swing.JComponent's paintComponent method to paint the background * appropriately. */ protected void paintComponent(Graphics g) { Rectangle clip = g.getClipBounds(); g.setColor(getBackground()); g.fillRect(clip.x, clip.y, clip.width, clip.height); if (background != null) background.paintIcon(this, g, 0, 0); } }