关于JPanel设置背景图片的Bug说明

JPanel可以像网页控件一样设置背景图片,主要是通过覆写JPanel的

paint(Graphics g)方法和paintComponent(Graphics g)方法;

 

但是二者有区别:

  JLabel类同其它的Swing组件一样,继承至javax.swing.Jcomponent.Swing。它们都是通过调用JComponent组件的paint方法来画界面。我们可以通过重载JComponent的公开方法paint来修改一个组件画界面的行为。下面是一个JComponent的paint方法的定义。    
   
  public   void   paint(Graphicsg)    
   
  作为paint方法的参数传进来的对象Graphics是一个绘图面板。为了优化绘图这个操作,paint方法被分割成三个具有保护(protected)属性的方法:paintComponent,   paintBorder,   paintChildren。paint方法调用这三个方法同时将它接受到的Graphics实例传递给这三个方法。  
   
  根据以上所说的,如果你想重画SWING的外观话就应该根据你要画的内容选择到底是重写paintComponent或paintBorder或paintChildren方法。如果同时重写了paint与paintComponent方法的话,则只会调用paint方法,而不执行paintComponent了。

 

所以:

通用的添加背景的方法可以是:

protected void paint(Graphics g) {
  try {
   BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
   g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

和:

 

protected void paintComponent(Graphics g) {
  try {
    BufferedImage img = ImageIO.read(My_Auditor_JPanel.class.getResource("/images/aa.jpg"));
   g.drawImage(img, 0, 0, this.getWidth(), this.getHeight(), null);
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

//但是推荐第二种方法;否则第一种方法可能导致背景图片遮盖住面板的其他控件。

//第二种覆写 paintComponent(Graphics g)则不会!

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值