JPanel如何設置背景圖片


import java.awt.*;
import javax.swing.*;

public class Demo extends JFrame {
 public Demo() {
  super("Title");
  NewPanel p = new NewPanel();
  this.getContentPane().add(p); // 將面板添加到JFrame上
  this.setSize(596, 298); // 初始窗口的大小
  this.setLocationRelativeTo(null); // 設置窗口居中
  this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  this.setVisible(true);
 }

 public static void main(String[] args) {
  new Demo();
 }

 class NewPanel extends JPanel {
  public NewPanel() {

  }

  public void paintComponent(Graphics g) {
   int x = 0, y = 0;
   ImageIcon icon = new ImageIcon("003.jpg");// 003.jpg是測試圖片在項目的根目錄下
   g.drawImage(icon.getImage(), x, y, getSize().width,
     getSize().height, this);// 圖片會自動縮放
//    g.drawImage(icon.getImage(), x, y,this);//圖片不會自動縮放
  }
 }

}


免責聲明!

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



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