0

I was learning the ways of using the JPanel and its other features and I kinda get how the "inserting background image" thing works but how do I specify it's size?

Here's my sample code:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class BgImageJPanel {
    public static void main(String[] args) {
        ImagePanel panel = new ImagePanel(
        new ImageIcon("C:\\Users\\Alex G\\Pictures\\Kda\\Evelynn.jpg").getImage());

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


    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);
    }
    public void paintComponent(Graphics g) {
        g.drawImage(img, 0, 0, null);
    }
}
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
  • Refer to this link: https://stackoverflow.com/questions/22162398/how-to-set-a-background-picture-in-jpanel – wuchunfu May 27 '20 at 04:54
  • 1) `public void paintComponent(Graphics g) {` should be `public void paintComponent(Graphics g) { spuer.paintComponent(g);` and `g.drawImage(img, 0, 0, null);` should be `g.drawImage(img, 0, 0, this);` 2) One way to get image(s) for an example is to hot link to images seen in [this Q&A](http://stackoverflow.com/q/19209650/418556). E.G. [This answer](https://stackoverflow.com/a/10862262/418556) hot links to an image embedded in [this question](https://stackoverflow.com/q/10861852/418556). – Andrew Thompson May 29 '20 at 04:51

0 Answers0