Swing 控件JPanel等设置背景图片

本文介绍了一种在Swing中自定义组件背景图片的方法。通过重写paintComponent方法并使用setBackground方法来更新显示的图像,实现了对Swing组件背景的有效控制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Swing控件有直接设置背景颜色的方法,但没有直接设置背景图片的方法。这里不解的是为什么Swing默认不提供这个方法呢?既然它不提供我们就自己写一个吧,也不难,你要你知道Swing容器的图片都是用protected void paintComponent(Graphics g) 画上去的就可以了。 

我们写一个类提供一个public void setBackground(Icon wallpaper) 方法,然后在这个方法里,我们保存传入的图片,然后利用repaint()方法去重绘控件,这是系统会自动调用控件的protected void paintComponent(Graphics g) 方法。 于是我们就达到了设置背景的目的。下面是完整的代码。

import java.awt.Graphics;  
import java.awt.Image;  
  
import javax.swing.Icon;  
import javax.swing.ImageIcon;  
import javax.swing.JPanel;  
  
public class ZPanel extends JPanel {  
    private static final long serialVersionUID = 6702278957072713279L;  
    private Icon wallpaper;  
  
    public ZPanel() {  
    }  
    protected void paintComponent(Graphics g) {  
        if (null != wallpaper) {  
            processBackground(g);  
        }  
        System.out.println("f:paintComponent(Graphics g)");  
    }  
    public void setBackground(Icon wallpaper) {  
        this.wallpaper = wallpaper;  
        this.repaint();  
    }  
    private void processBackground(Graphics g) {  
        ImageIcon icon = (ImageIcon) wallpaper;  
        Image image = icon.getImage();  
        int cw = getWidth();  
        int ch = getHeight();  
        int iw = image.getWidth(this);  
        int ih = image.getHeight(this);  
        int x = 0;  
        int y = 0;  
        while (y <= ch) {  
            g.drawImage(image, x, y, this);  
            x += iw;  
            if (x >= cw) {  
                x = 0;  
                y += ih;  
            }  
        }  
    }  
}  


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值