Set JPanel Background Image

Total Views : 121
Zoom In Zoom Out Read Later Print

This code will help you to know how you can set a image as a background of the JPanel in java.

JPanelBackgroundImage.java

package com.prodevsblog.how_to.swing;

import javax.swing.*;
import java.awt.*;

/**
 * Author Manjeet Verma
 * WebSite https://prodevsblog.com/
 */

public class JPanelBackgroundImage {
    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel(new ImageIcon("F:\\background.jpg").getImage());

        JFrame frame = new JFrame();

        frame.setSize(200, 200);
        frame.setTitle("Panel Background Image");

        frame.getContentPane().add(panel);
        frame.pack();
        frame.setVisible(true);
    }
}

class ImagePanel extends JPanel {
    private Image image;

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

    public ImagePanel(Image image) {
        this.image = image;
        Dimension size = new Dimension(image.getWidth(null), image.getHeight(null));
        setPreferredSize(size);

        setMinimumSize(size);
        setMaximumSize(size);

        setSize(size);
        setLayout(null);
    }

    public void paintComponent(Graphics g) {
        g.drawImage(image, 0, 0, null);
    }
}

Output of the code.

See More

Latest Photos