Adding an image to a JPanel background

16,069
/**
 * @author
 *
 */
public class ImagePanel extends JPanel {

    private Image image = null;

    public ImagePanel(String filename) {
        this.image = new ImageIcon(filename).getImage();
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, image.getWidth(null), image.getHeight(null), null);
    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel("resources/image.jpg");

        JFrame frame = new JFrame("Frame");
        frame.setSize(800, 600);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        frame.setVisible(true);
    }
}
Share:
16,069
FadelMS
Author by

FadelMS

linkedin

Updated on June 25, 2022

Comments

  • FadelMS
    FadelMS almost 2 years

    How can I add an image to a JPanel background. The image will not be scaled or resized. Thanks.

  • mKorbel
    mKorbel over 12 years
    please remove JComponent.paint(Graphics g), that really wrong method for painting in Java6' Swing
  • trashgod
    trashgod over 12 years
    Won't this scale with resize? See also Initial Threads.
  • basickarl
    basickarl about 11 years
    Perfect, if only more people would be this short with there answers!