JPanel not showing background image

2019-02-27 12:50发布

问题:

It is very simple program and i have tried my best but the JPanel doesn't come up with a background image. I just want a simple background image on my panel.

Here is my code:

import javax.swing.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.*;
import java.awt.Graphics;

class PanelEx extends JPanel
{
    BufferedImage img;

    PanelEx()
    {
        try
        {
            img = ImageIO.read(new File("C:/Users/Pictures/s_4261.jpg"));
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
    }
    public void printComponent(Graphics g)
    {
        g.drawImage(img,0,0,null);
    }
}

class JPanelEx2 extends JFrame
{
    PanelEx pe;

    public static void main(String args[])
    {
        new JPanelEx2();
    }

    JPanelEx2()
    {
        pe = new PanelEx();

        add(pe);
        setTitle("JPanel Title");
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setSize(320,240);
        setVisible(true);
    }
}

Thanks in advance

回答1:

Replace

public void printComponent(Graphics g) {

with

@Override
public void paintComponent(Graphics g) {
  super.paintComponent(g);


回答2:

Don't use a JPanel. Just use a JLabel with an Icon then you don't need custom code.

See Background Panel for more information as well as a solution that will paint the image on a JPanel with 3 different painting options:

  1. scaled
  2. tiled
  3. actual