[英]Image drawing with PaintComponent 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. 我目前正在学习Java,但又在书中遇到了无法使用的代码,我不知道为什么。 This code snippet is from Head First 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?
我在这里想念什么?
1) In your paintComponent()
you must to call super.paintComponent(g);
1)在
paintComponent()
您必须调用super.paintComponent(g);
. 。 Read more about custom paintings .
阅读有关定制绘画的更多信息。
2) instead of Image
use BufferedImage
, because Image its abstrat wrapper. 2)代替
Image
使用BufferedImage
,因为Image的抽象包装器。
3)use ImageIO
instead of creating Image
like this new ImageIcon("cat2.jpg").getImage();
3)使用
ImageIO
代替创建Image
这样new ImageIcon("cat2.jpg").getImage();
4)Use URL
for 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);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.