Share this blog!

How to add a background image to a jPanel



The default jPanel allows users to add a background color by calling
 .setBackground(Color colorname); 
but there is no way to set a background image so easily. The only option is to call in a separate class with modifications. You can simply use the following code to add a background image to a jPanel.
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

/**
 *
 * @author Sachi
 */
class ImagePanel extends JPanel {

  private Image img;
  public ImagePanel(String img) {
    this(new ImageIcon(img).getImage());
  }
  public ImagePanel(Image img) {
    this.img = img;
    Dimension size = new Dimension(img.getWidth(null), img.getHeight(null));
    setPreferredSize(size);
    setMinimumSize(size);
    setMaximumSize(size);
    setSize(size);
    setLayout(null);
  }
  @Override
  public void paintComponent(Graphics g) {
    g.drawImage(img, 0, 0, null);
  }
}
You can use the above class as follows:-
ImagePanel panel = new ImagePanel(new ImageIcon(getClass()
                                     .getResource("/Resources/background.png"))
                                     .getImage());

Next PostNewer Post Previous PostOlder Post Home

1 comment: