JPanel可以像網頁控件一樣設置背景圖片,主要是通過覆寫JPanel的
paint(Graphics g)方法和paintComponent(Graphics g)方法;
但是二者有區別:
“
JLabel類同其它的Swing組件一樣,繼承至javax.swing.Jcomponent.Swing。它們都是通過調用JComponent組件的paint方法來畫界面。我們可以通過重載JComponent的公開方法paint來修改一個組件畫界面的行爲。下面是一個JComponent的paint方法的定義。
public void paint(Graphicsg)
作爲paint方法的參數傳進來的對象Graphics是一個繪圖面板。爲了優化繪圖這個操作,paint方法被分割成三個具有保護(protected)屬性的方法:paintComponent, paintBorder, paintChildren。paint方法調用這三個方法同時將它接受到的Graphics實例傳遞給這三個方法。
根據以上所說的,如果你想重畫SWING的外觀話就應該根據你要畫的內容選擇到底是重寫paintComponent或paintBorder或paintChildren方法。如果同時重寫了paint與paintComponent方法的話,則只會調用paint方法,而不執行paintComponent了。
”
所以:
通用的添加背景的方法可以是:
protected void paint(Graphics g) {
try {
BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
和:
protected void paintComponent(Graphics g) {
try {
BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
} catch (IOException e) {
e.printStackTrace();
}
}
//但是推薦第二種方法;否則第一種方法可能導致背景圖片遮蓋住面板的其他控件。
//第二種覆寫 paintComponent(Graphics g)則不會!