将背景图像添加到面板 [英] Add an Background image to a Panel
本文介绍了将背景图像添加到面板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 JPanel
,我想添加一个图像作为它的背景.我该怎么做?
I have a JPanel
, and i want to add an image as its background. How can i do that ?
frame = new JFrame("Some frame");
panel1 = new JPanel();
panel1.setBorder(new EmptyBorder(5, 5, 5, 5));
// NEED TO ADD AN IMAGE TO THIS PANEL
panel1.setLayout(cardlayout);
frame.getContentPane().add(panel1);
frame.setLocationByPlatform(true);
frame.setVisible(true);
我需要向 panel
添加图像,我该怎么做?
I need to add an image to the panel
and how can i do it ?
更新 1
panel1 = new JPanel()
{
private static final long serialVersionUID = 1L;
@Override
public void paintComponent(Graphics g)
{
g.drawImage(Toolkit.getDefaultToolkit().createImage("1.jpg"), 0, 0, null);
}
};
推荐答案
您需要重写方法 paintComponent(Graphics g)
of JPanel 并使用 drawImage()
在 Graphics 对象 g
如这个例子.
You need to override the method paintComponent(Graphics g)
of JPanel and use drawImage()
on the Graphics object g
as in this example.
另外,通过@trashgod检查这两个示例:
Also, check these two examples by @trashgod:
这篇关于将背景图像添加到面板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文