標籤:main jpg jpanel jpa 可見 vax path val visible
1 1.import javax.swing.ImageIcon; 2 2.import javax.swing.JFrame; 3 3.import javax.swing.JLabel; 4 4.import javax.swing.JPanel; 5 5.public class MainJFrame extends JFrame { 6 6. 7 7. public MainJFrame() { 8 8. //設定標題 9 9. super("JFram設定背景圖片(Cannel_2020)"); 10 10. //設定大小 11 11. setSize(500, 400); 12 12. //設定位置 13 13. setLocation(200, 50); 14 14. //背景圖片的路徑。(相對路徑或者絕對路徑。本例圖片放於"java項目名"的檔案下) 15 15. String path = "background.jpg"; 16 16. // 背景圖片 17 17. ImageIcon background = new ImageIcon(path); 18 18. // 把背景圖片顯示在一個標籤裡面 19 19. JLabel label = new JLabel(background); 20 20. // 把標籤的大小位置設定為圖片剛好填充整個面板 21 21. label.setBounds(0, 0, this.getWidth(), this.getHeight()); 22 22. // 把內容窗格轉化為JPanel,否則不能用方法setOpaque()來使內容窗格透明 23 23. JPanel imagePanel = (JPanel) this.getContentPane(); 24 24. imagePanel.setOpaque(false); 25 25. // 把背景圖片添加到分層窗格的最底層作為背景 26 26. this.getLayeredPane().add(label, new Integer(Integer.MIN_VALUE)); 27 27. //設定可見 28 28. setVisible(true); 29 29. //點關閉按鈕時退出 30 30. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 31 31. } 32 32. 33 33. public static void main(String[] args) { 34 34. new MainJFrame(); 35 35. } 36 36.}
java視窗添加背景