由於在網上查詢的方法眾多,而且方法有的地方復雜化,其實不用特別復雜編寫代碼,只要關鍵點的地方寫對了,就可以運行。
此寫法本人整理了網上思路編寫,簡單明了~~~!
/**
* 自定義背景圖片,重繪JPanel面板的paintComponent(Graphics g)類
*/
class BackgroundPanel extends JPanel {
private static final long serialVersionUID = 1L;
String name = "01.JPG"; // 將圖片放在class類的同級文件夾里
protected void paintComponent(Graphics g) { //關鍵代碼:重寫繪制組件外觀
super.paintComponent(g);
ImageIcon image = new ImageIcon(getClass().getResource(name)); // 獲取圖片路徑
g.drawImage(image.getImage(), 0, 0, 350, 350, null);// 繪制圖片與組件大小相同
}
}
public class BackgroundPanelClass extends JFrame {
private static final long serialVersionUID = 1L;
JPanel contentPan; // 放背景面板的面板
public BackgroundPanelClass() {
this.setTitle("自定義背景圖片");
this.setVisible(true);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setBounds(400, 250, 350, 350);
contentPan = new JPanel();
contentPan.setLayout(new BorderLayout(0, 0));// 設置邊界布局
BackgroundPanel backgroundPanel = new BackgroundPanel(); // 創建背景面板
contentPan.add(backgroundPanel);// 添加背景面板
this.setContentPane(contentPan);
}
public static void main(String[] args) {
new BackgroundPanelClass();
}
}
效果圖:
一張養眼的背景面板就被添加進去啦~如果要在背景面板上添加組件,要在BackgroundPanel類里寫入構造方法進行添加。
圖片存放路徑:
需要放在類同級文件夾下面