使用 PaintComponent Java 绘制图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20123633/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:19:55  来源:igfitidea点击:

Image drawing with PaintComponent Java

javaimageswingpaintcomponent

提问by Igor Meszaros

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

我目前正在学习 Java,但我又一次遇到了书中的一段代码,该代码不想工作,我不知道为什么。此代码片段来自 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?

该图像位于我的类文件所在的同一目录中,并且该图像未显示。我在这里缺少什么?

采纳答案by alex2410

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

1) 在paintComponent()你必须调用super.paintComponent(g);. 阅读更多关于定制绘画的信息

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

2) 而不是Imageuse BufferedImage,因为 Image 是它的抽象包装器。

3)use ImageIOinstead of creating Imagelike this new ImageIcon("cat2.jpg").getImage();

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

4)Use URLfor resources inside your project.

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

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);
    }
}