将图像绘制到 JFrame 内的 JPanel
我正在设计一个程序,在 JFrame 中包含两个 JPanel,一个用于保存图像,另一个用于保存 GUI 组件(搜索字段等)。我想知道如何将图像绘制到 JFrame 中的第一个 JPanel 上?
以下是我的构造函数中的示例代码:
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 方法来绘制图像,但是当我尝试编写时,这会导致我的构造函数出现问题:
imagepanel.paintComponents(null);
因为它只允许我传递方法 null ,而不是 Graphics g,有人知道对此方法的修复或我可以用来在 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);
}
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);
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我想建议一个更简单的方法,
Yayy!现在你的图像是一个 swing 组件!将其添加到框架或面板或任何像平常一样的东西!可能也需要重新粉刷,比如
I'd like to suggest a more simple way,
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
您可以使用
JLabel .setIcon()
将图像放置在 JPanel 上,如下所示此处。另一方面,如果你想要一个带有背景的面板,你可以看看 这个教程。
You can use the
JLabel.setIcon()
to place an image on the JPanel as shown here.On the other hand, if you want to have a panel with a background, you can take a look at this tutorial.
无需从构造函数中手动调用
paintComponent()
。问题是您为Graphics
对象传递 null。相反,重写paintComponent()
并使用传入将用于绘画的方法的Graphics
对象。查看此教程。以下是带有图像的JPanel
示例:There is no need to manually invoke
paintComponent()
from a constructor. The problem is that you passing null for aGraphics
object. Instead, overridepaintComponent()
and you use theGraphics
object passed in to the method you will be using for painting. Check this tutorial. Here is an example ofJPanel
with image: