我正在尝试在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可能是公共的,但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);
    }
}


始终发布mcve并使用照片网址,以便其他人可以运行您的代码。

09-26 15:27