图片未显示在 window

Image not showing on the window

我已将我的代码缩减为这样一个简单的功能:在 window 上显示图片。但是为什么我试过之后图片还是不显示呢?我创建了一个 JFrame,然后创建了一个用于显示图片的 JPanel。然后将面板添加到框架中。对了,我导入了图片,双击得到了url.

import java.awt.*;

import javax.swing.*;

import com.sun.prism.Graphics;

public class GUI {
    JFrame frame=new JFrame("My game");
    JPanel gamePanel=new JPanel();

    public static void main(String[] args){
        GUI gui=new GUI();
        gui.go();
    }

    public void go(){

        frame.setSize(300, 400);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Background backPic=new Background();
        backPic.setVisible(true);
        frame.getContentPane().add(backPic);        

        JPanel contentPane=(JPanel) frame.getContentPane();
        contentPane.setOpaque(false);

        frame.setVisible(true);
        }

    class Background extends JPanel{
            public void paintComponent(Graphics g){
                ImageIcon backgroundIcon=new         ImageIcon("file:///E:/eclipse/EL/backgroundPicture.jpg");
                Image backgroundPic=backgroundIcon.getImage();

                Graphics2D g2D=(Graphics2D) g;
                g2D.drawImage(backgroundPic,0,0,this);
            }
        }
}

这是因为您导入了 com.sun.prism.Graphics。应该是 java.awt.Graphics.

我还会从您的路径中删除 "file:///" 位。而且您可能也不希望在每次绘制事件时都加载图像。这是背景的更好版本 class;-

class Background extends JPanel {

    Image backgroundPic;

    public Background() {
        ImageIcon backgroundIcon=new ImageIcon("E:/eclipse/EL/backgroundPicture.jpg");
        backgroundPic=backgroundIcon.getImage();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        Graphics2D g2D=(Graphics2D) g;
        g2D.drawImage(backgroundPic,10,10,this);
    }
}