图像未在JPanel中绘制

时间:2014-03-20 06:23:39

标签: java paintcomponent

这是我试图用来在屏幕上绘制图像的代码(图像的位置是正确的),代码运行但屏幕上没有绘制任何内容。我的程序的getFile()和paintComponent()方法:

BufferedImage image;    
public void getFile() throws IOException{
    image = ImageIO.read(new File("grass.png"));
}
protected void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    g.drawImage(image, 0, 0, null);
}
}

3 个答案:

答案 0 :(得分:3)

您确实意识到您从未创建DrawImage的实例,也没有将其实际添加到可显示它的任何内容

public class DrawImage extends JPanel
{

    BufferedImage image;

    public DrawImage() throws IOException {
        getFile();
    }

    public void getFile() throws IOException
    {
        image = ImageIO.read(new File("grass.png"));
    }

//...

    public static void main(String[] args)
    {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    DrawImage pane = new DrawImage();
                    JFrame frame = new JFrame();
                    frame.add(pane);
                    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
                    frame.setSize(400, 400);
                    frame.setVisible(true);    
                } catch (IOException exp) {
                    exp.printStackTrace();
                }
            }
        });
    }

答案 1 :(得分:1)

而不是JPanel pane = new JPanel(),您应该DrawImage pane = new DrawImage()frame.add(pane)致电pane.getFile()

由于您总是需要在绘制DrawImage之前调用getFile(),为什么不将它放入DrawImage类的构造函数中?

答案 2 :(得分:1)

首先,你没有使用绘制图像的类(DrawImage) 在这一行JPanel pane = new JPanel();所以你必须将它改为DrawImage pane = new DrawImage(); 第二个问题,你没有调用getFile()方法来初始化图像对象,所以要么像我下面提到的那样使用,要么在类drawImage构造函数中调用此方法。

public class DrawImage extends JPanel{

BufferedImage image;

public Image getFile() 
{
    try {
        image = ImageIO.read(new File("grass.png"));
        return image;
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}


protected void paintComponent(Graphics g) 
{
    super.paintComponent(g);
    System.out.println(image);
    g.drawImage(getFile(), 0, 100, null);
}

public static void main(String[] args)
{
    DrawImage pane = new DrawImage();
    JFrame frame = new JFrame();
    frame.add(pane);
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(400, 400);
    frame.setVisible(true);    
}
}