Drawing an Image to a JPanel within a JFrame(在 JFrame 中将图像绘制到 JPanel)
问题描述
我正在设计一个在 JFrame 中包含两个 JPanel 的程序,一个用于保存图像,另一个用于保存 GUI 组件(搜索字段等).我想知道如何将图像绘制到 JFrame 中的第一个 JPanel?
I am designing a program that contains two JPanels within a JFrame, one is for holding an image, the other for holding GUI components(Searchfields etc). I am wondering how do I draw the Image to the first JPanel within the JFrame?
这是我的构造函数的示例代码:
Here is a sample code from my constructor :
public UITester() {
this.setTitle("Airplane");
Container container = getContentPane();
container.setLayout(new FlowLayout());
searchText = new JLabel("Enter Search Text Here");
container.add(searchText);
imagepanel = new JPanel(new FlowLayout());
imagepanel.paintComponents(null);
//other constructor code
}
public void paintComponent(Graphics g){
super.paintComponents(g);
g.drawImage(img[0], -50, 100, null);
}
我试图重写 JPanel 的 paintComponent 方法来绘制图像,但是当我尝试编写时,这会导致我的构造函数出现问题:
I was trying to override the paintComponent method of JPanel to paint the image, but this causes a problem in my constructor when I try to write :
imagepanel.paintComponents(null);
因为它只允许我传递 null 方法,而不是 Graphics g,所以有人知道此方法的修复方法或我可以用来在 JPanel 中绘制图像的其他方法吗?帮助表示赞赏!:)
As it will only allow me to pass the method null, and not Graphics g, anybody know of a fix to this method or another method i can use to draw the image in the JPanel? Help is appreciated! :)
一切顺利,并在此先感谢!马特
All the best and thanks in advance! Matt
推荐答案
我想建议一个更简单的方法,
I'd like to suggest a more simple way,
image = ImageIO.read(new File(path));
JLabel picLabel = new JLabel(new ImageIcon(image));
耶耶!现在您的图像是一个摆动组件!将它添加到框架或面板或您通常做的任何东西!可能也需要重新粉刷,比如
Yayy! Now your image is a swing component ! add it to a frame or panel or anything like you usually do! Probably need a repainting too , like
jpanel.add(picLabel);
jpanel.repaint();
这篇关于在 JFrame 中将图像绘制到 JPanel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 JFrame 中将图像绘制到 JPanel
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01