图像不显示在java框架中
试图用java学习windows编程,想要在框架上显示图像。这是问题代码:
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("hello world");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
Graphics graph = frame.getGraphics();
BufferedImage image = ImageIO.read(new File("data/image.jpg"));
graph.drawImage(image, 0,0,frame);
frame.pack();
frame.setVisible(true);
}
我见过一些成功的例子子类化Component类并在paint方法中调用Graphics.DrawImage方法。为什么你必须这样做,你不能直接抓取与框架关联的 Graphics 对象并直接绘制图像吗?
trying to learn windows programming in java, want to display a image to a frame.here is the problem code:
public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("hello world");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(200,200);
Graphics graph = frame.getGraphics();
BufferedImage image = ImageIO.read(new File("data/image.jpg"));
graph.drawImage(image, 0,0,frame);
frame.pack();
frame.setVisible(true);
}
i have seen some successful examples subclass the Component class and call the Graphics.DrawImage method in the paint method. why do you have to do that, can't you just grab the Graphics object associated with the frame and draw the image directly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你不能,因为这不是 Swing 绘画的工作方式。一方面,绘画必须在 EDT 上进行,并且实现此目的的首选方法是重写
paintComponent(..)
方法。如果您使用全屏模式,不过。You can't because that's not the way Swing painting works. For one thing, painting has to happen on the EDT, and the preferred way to achieve this is overriding the
paintComponent(..)
method. Direct painting in the way you imagine is possible if you use full screen mode, though.无需定制绘画即可显示图像。请参阅如何使用图标。
本教程还有一个关于“自定义绘画”的部分。
No need for custom painting to show an image. See How to Use Icons.
The tutorial also has a section on "Custom Painting".