JPanel的背景图片设置方法

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class MyPanel {

 public MyPanel() {
  drawAndShow();
 }

 public void drawAndShow() {
  
  JFrame frame = new JFrame("ImagePanel test");
  frame.setSize(300, 200);
  JPanel panel = new JPanel() {
   ImageIcon icon = new ImageIcon("D:/logo2.jpg");
   Image img = icon.getImage();
   protected void paintComponent(Graphics g) { // 重写此方法,可加入自己的图片
    super.paintComponent(g);
    Dimension size = new Dimension(super.getWidth(), super
      .getHeight());
    g.drawImage(img, 0, 0, img.getWidth(this), img.getHeight(this),
      this);
   }
  };

  frame.add(panel);
  frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
  frame.setVisible(true);
 }

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

}

你可能感兴趣的:(JPanel的背景图片设置方法)