我正在设计一个程序,在JFrame中包含两个JPanel,一个用于保存图像,另一个用于保存GUI组件(Searchfields等) . 我想知道如何将图像绘制到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中绘制图像?感谢帮助! :)
一切顺利,并提前感谢!马特
3 回答
我想建议一个更简单的方法,
Yayy!现在你的形象是摆动组件!将它添加到框架或面板或您通常做的任何事情!可能也需要重新粉刷,比如
您可以使用JLabel.setIcon()在JPanel上放置图像,如图所示here .
另一方面,如果您想要一个带背景的面板,您可以查看this教程 .
无需从构造函数手动调用
paintComponent()
. 问题是您为Graphics
对象传递null . 相反,覆盖paintComponent()
并使用传递给将用于绘制的方法的Graphics
对象 . 检查这个tutorial . 以下是JPanel
带图像的示例: