問題代碼
public void paint(Graphics g) {
g.drawImage(background, 0, 20, this); // 直接在 JFrame 繪圖
}
失效原因
JFrame 是重量級容器,其 paint 繪製順序複雜,易被子組件覆蓋。- 未調用
super.paint(g) 導致邊框、標題欄異常。 - 未啟用雙緩衝,閃爍嚴重。
推薦方案:JLabel + Icon
JLabel bgLabel = new JLabel(new ImageIcon(background));
bgLabel.setBounds(0, 0, 500, 500);
getLayeredPane().add(bgLabel, JLayeredPane.FRAME_CONTENT_LAYER);
// 或
setContentPane(new JPanel() {
@Override protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(background, 0, 0, getWidth(), getHeight(), this);
}
});
關鍵點
- 在
JPanel 重寫 paintComponent 而非 paint。 - 調用
super.paintComponent(g) 保證背景清除與雙緩衝。 - 使用
JLayeredPane 分層,背景標籤置底。