JFrame如何設置背景圖片


代碼:

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);
 }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM