我有一個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);
我需要將圖像添加到panel
,我該怎麼做?
更新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);
}
};
在更新我看你是忘了叫'super.paintComponent方法(G),在''重載方法paintComponent',這可能是一個大問題(甚至除了提取圖像問題在'paintComponent'中)。重寫方法應該優化地首先調用他們的'超' –
看到這些答案[這裏](http://stackoverflow.com/questions/13237908/loading-image-in-java-code-from-c-drive/13238468#13238468)或[this one](http://stackoverflow.com/questions/12660122/image-resizing-and-displaying-in-a-jpanel-or-a-jlabel-without-loss-of-quality/12660146#12660146)對於一些例子 –
@DavidKroukamp我試圖添加'super.paintComponent(g);'但它仍然不會添加圖像到Jpanel –