尝试在 JFrame 上绘制图像

Trying to draw an image on a JFrame

我正在尝试在 JFrame 上绘制图像,但它似乎不起作用。这是绘制图像的面板:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import javax.swing.JPanel;

public class GraphicsPanel extends JPanel {

public BufferedImage image;

public GraphicsPanel(){

}
  @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            g.drawImage(image, 0, 0, null);
        }
}

这是 JFrame:

import java.awt.Dimension;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class Spelplan extends javax.swing.JFrame {

public static BufferedImage image;
public static GraphicsPanel pane;

public Spelplan() {
    try {
        image = ImageIO.read(new File("*IMAGE PATH*"));  
    }
    catch(IOException e) {
        System.out.println("Image not found");
    }

    pane = new GraphicsPanel(); 
    pane.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    pane.setVisible(true);

    initComponents();
    this.setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    this.add(pane);
    this.pack();
    pane.repaint();        
}

当程序运行时,JFrame 以正确的大小显示,但没有绘制图像。知道我做错了什么吗?

BufferedImage image 可能 public 但 GraphicsPanel 从未访问过它。
无论如何,更好的做法是将 image 保持私有并使用 getter 来访问它,或者将引用传递给构造函数:

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.JPanel;

public class Spelplan extends javax.swing.JFrame {

    public static BufferedImage image;
    private String imagePath = "https://upload.wikimedia.org/wikipedia/commons/3/3f/Crystal_Project_bug.png";

    public Spelplan() {
        try {
            URL url = new URL(imagePath);
            image = ImageIO.read(url);
        }
        catch(IOException e) {
            System.out.println("Image not found");
        }

        add(new GraphicsPanel(image));
        pack();
        setVisible(true);
    }

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

class GraphicsPanel extends JPanel {

    private BufferedImage image;

    public GraphicsPanel(BufferedImage image){
        this.image = image;
        setPreferredSize(new Dimension(image.getWidth(), image.getHeight()));
    }
    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 0, 0, null);
    }
}

始终 post mcve 并使用照片 url 以便其他人可以 运行 您的代码。