代碼:
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
public class JFrameBackground {
private JFrame frame = new JFrame("背景圖片測試");
private JPanel imagePanel;
private ImageIcon background;
public static void main(String[] args) {
new JFrameBackground();
}
public JFrameBackground() {
background = new ImageIcon("003.jpg");// 背景圖片
JLabel label = new JLabel(background);// 把背景圖片顯示在一個標簽里面
// 把標簽的大小位置設置為圖片剛好填充整個面板
label.setBounds(0, 0, background.getIconWidth(),
background.getIconHeight());
// 把內容窗格轉化為JPanel,否則不能用方法setOpaque()來使內容窗格透明
imagePanel = (JPanel) frame.getContentPane();
imagePanel.setOpaque(false);
// 內容窗格默認的布局管理器為BorderLayout
imagePanel.setLayout(new FlowLayout());
imagePanel.add(new JButton("測試按鈕"));
frame.getLayeredPane().setLayout(null);
// 把背景圖片添加到分層窗格的最底層作為背景
frame.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE));
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(background.getIconWidth(), background.getIconHeight());
frame.setResizable(false);
frame.setVisible(true);
}
}