Mach Mitch
Mach Mitch

Reputation: 323

Add image to JPanel

i wanted to add image to my JPanel using swing without paint()/init() and such applet methods. Upon JPanel are some other components which i want to stay visible.

In short i want to add background image to my JPanel.

Upvotes: 1

Views: 5213

Answers (1)

Tom
Tom

Reputation: 340

You can extend JPanel like as shown in this link.

Quoting from the above mentioned link

public class ImageTest {

  public static void main(String[] args) {
    ImagePanel panel = new ImagePanel(new ImageIcon("images/background.png").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);
  }

}

Upvotes: 2

Related Questions