Java Swing 中插入图片背景

来源:互联网 发布:下载软件管家360 编辑:程序博客网 时间:2024/05/20 13:03

首先 度娘出了一段代码

package com.tntxia.commonswing.panel;  import java.awt.*;  import javax.swing.JPanel;  public class BackgroundPanel extends JPanel {      private static final long serialVersionUID = -6352788025440244338L;      private Image image = null;      public BackgroundPanel(Image image) {          this.image = image;      }      // 固定背景图片,允许这个JPanel可以在图片上添加其他组件      protected void paintComponent(Graphics g) {          g.drawImage(image, 0, 0, this.getWidth(), this.getHeight(), this);      }  }  

调用的方法:

   //自己的主类Image image=new ImageIcon("images/bg.gif").getImage();  //直接插入绝对路径或者在eclipse下建一个文件包把图片放在里面JPanel panel = new BackgroundPanel(image);  //如果在构造方法中则可以设置全局变量然后在局部变量也可以使用了 但是那个样子JPanel 应该省去 不然会造成在内存中新建一个Panel 而不指向同一引用add(pannel);setSize(500500;//这样设置了大小  就不会出现一run就只是很小的一部分了

这个方法很好用 还有newicon 的那种 还有paint()的方法 现在没时间 等有时间在整理吧

0 0