尝试在JFrame上绘制图像

时间:2018-05-28 11:32:41

标签: java swing jframe paintcomponent

我试图在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显示的大小正确但没有绘制图像。知道我做错了吗?

1 个答案:

答案 0 :(得分:1)

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并使用照片网址,以便其他人可以运行您的代码。