Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/typo3/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
基于组件Java的图像绘制_Java_Image_Swing_Paintcomponent - Fatal编程技术网

基于组件Java的图像绘制

基于组件Java的图像绘制,java,image,swing,paintcomponent,Java,Image,Swing,Paintcomponent,我目前正在学习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 DrawPan

我目前正在学习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);
    }
}
该图像与我的类文件位于同一目录中,并且未显示该图像。我在这里遗漏了什么?

1)在您的
paintComponent()
中,您必须调用
super.paintComponent(g)。阅读更多关于

2) 不要使用
Image
而使用
buffereImage
,因为Image是抽象的包装

3) 使用
ImageIO
而不是像这样创建
Image
新图像图标(“cat2.jpg”).getImage()

4) 对项目中的资源使用
URL

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

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

嗨,调用super.paintComponent是不必要的,没有它也可以工作。谢谢你的帮助!