我有一个JPanel
,我想添加一个图像作为它的背景。我该怎么做?
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);
我需要将图像添加到面板
,我该怎么做?
更新 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)
的 JPanel并使用 drawImage()
在 Graphics 上对象 g
如 this example .
此外,通过 @trashgod 检查这两个示例:
关于java - 将背景图像添加到面板,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13791984/