JFrame 图像在帧调整大小时显示
我有这个 JFrame 包含 JPanel 的子级,其中它显示以这种方式声明的图像。
BufferedImage image = ImageIO.read(filename);
程序正确显示图像。但唯一的问题是,它需要调整框架大小才能显示图像。
有没有办法在框架出现后显示图像?
I have this JFrame containing a children of JPanel wherein it displays the image which is declared in this manner.
BufferedImage image = ImageIO.read(filename);
The program displays the image properly. But the only thing is, it requires to resize the frame to display the image.
Is there a possible way to display the image once the frame appears?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该覆盖
paintComponent(Graphics g)
并在其中绘制图像。在这种情况下,您应该对JPanel
组件执行此操作(我认为?如果没有,请对您所引用的JComponent
执行此操作)。另外,由于 Swing 不是线程安全的,因此请确保这些修改是在EDT
中执行的。示例
输出
记住这一点很重要该示例忽略渲染提示,因此当您最大化 JFrame 时,图像质量会很差。 :)
编辑
在回答这个问题时,我假设您对 Swing 有基本的了解。我想我假设太多了。值得一提的是,所有组件都应该在实现(即变得可见)之前添加到顶级容器中。这将确保渲染所有内容而无需调整框架大小。正如其他人所建议的,您可以简单地使用
JLabel
来渲染图像,然后将其添加到您的JPanel
中。相反,我提倡定制绘画,这是完全可以接受的,而且对我来说,更干净。You should override
paintComponent(Graphics g)
and draw the image therein. In this case, you should do this for theJPanel
component (I think? If not, do this for theJComponent
(s) you're referring to). Also, since Swing is not thread-safe, ensure these modifications are performed in theEDT
.EXAMPLE
OUTPUT
It's important to keep in mind that this example ignores rendering hints, so when you maximize the
JFrame
, the image quality will be very poor. :)EDIT
When answering this question, I assumed you had a basic understanding of Swing. I suppose I assumed too much. It is important to mention that all components should be added to the top-level container before it's been realized (i.e. made visible). This will ensure that everything is rendered without having to resize your frame. As others have suggested, you could have simply used a
JLabel
to render the image, and then added it to yourJPanel
. Instead, I promoted custom painting, which is perfectly acceptable, and to me, cleaner.用于显示 图像 或 ImageIcon 看起来更好 JLabel (基本内容)
for dispaly Image or ImageIcon is better look for JLabel (basic stuff)