本文介绍了使用PaintComponent Java绘制图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在学习java,但我再次遇到了一本不想工作的代码,我无法弄明白为什么。此代码段来自Head First Java

I'm studying java currently, and yet again I ran into a code in the book which doesn't wanna work and i can't figure out why. This code snippet is from Head First Java

import javax.swing.*;
import java.awt.*;

public class SimpleGui {

    public static void main (String[] args){
        JFrame frame = new JFrame();
        DrawPanel button = new DrawPanel();

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.getContentPane().add(button);

        frame.setSize(300,300);

        frame.setVisible(true);
    }
}


import java.awt.*;
import java.lang.*;

public class DrawPanel extends JPanel {
private Image image;

public DrawPanel(){
    image = new ImageIcon("cat2.jpg").getImage();
}
public void paintComponent(Graphics g){

    g.drawImage(image,3,4,this);
    }
}

图像位于我的类文件所在的目录中是,并且图像没有显示。我在这里缺少什么?

the image is in the same directory where my class files are, and the image is not showing. What am i missing here?

推荐答案

1)在你的 paintComponent()你必须调用 super.paintComponent(g); 。了解有关的更多信息。

1) In your paintComponent() you must to call super.paintComponent(g);. Read more about custom paintings.

2)而不是 Image 使用 BufferedImage ,因为Image是它的abstrat包装器。

2) instead of Image use BufferedImage, because Image its abstrat wrapper.

3)使用 ImageIO 而不是像这样创建 Image c> new ImageIcon(cat2.jpg)。getImage();

3)use ImageIO instead of creating Image like this new ImageIcon("cat2.jpg").getImage();

4)使用 URL 用于项目内的资源。

4)Use URL for resources inside your project.

我更改了您的代码,它可以帮助您:

I changed your code and it helps you:

class DrawPanel extends JPanel {
    private BufferedImage image;

    public DrawPanel() {
        URL resource = getClass().getResource("cat2.jpg");
        try {
            image = ImageIO.read(resource);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        g.drawImage(image, 3, 4, this);
    }
}

这篇关于使用PaintComponent Java绘制图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 17:34