设置JLabel或其他组件透明度

在Java swing中编程中可以通过重写组件的paintComponent(Graphics g)方法来达成调节组件透明度的效果,下面是我写的一个demo:

import java.awt.AlphaComposite;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

public class MainFrame extends JFrame{
    JPanel cp = (JPanel)this.getContentPane();
    ImageLabel label;
    ImageIcon icon;
    JButton button;
    public MainFrame(){
        init();
    }

    public void init(){
        this.setSize(500, 300);
        this.setLocation(200, 100);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLayout(null);
        //设置图片并调整图片的尺寸
        icon = new ImageIcon(new  ImageIcon("mq.jpg").getImage()
                .getScaledInstance(180, 180, Image.SCALE_DEFAULT));
        label = new ImageLabel(icon);
        label.setBounds(10,10,200,200);
        label.setAlpha(0.5f);
        cp.add(label);
        this.setVisible(true);  
    }


    public static void main(String[] args) {
        new MainFrame();
    }
}
class ImageLabel extends JLabel{
    public ImageLabel(ImageIcon icon){
        super.setIcon(icon);
    }
    private AlphaComposite cmp = AlphaComposite.getInstance(AlphaComposite.SRC_OVER,1);
    private float alpha;

    public void setAlpha(float alpha) {
        this.alpha = alpha;
        if (isVisible())   paintImmediately(getBounds());
    }

    @Override
    protected void paintComponent(Graphics g) {
        // TODO Auto-generated method stub
        Graphics2D g2d = (Graphics2D)g;
        g2d.setComposite(cmp.derive(alpha));
        super.paintComponent(g2d);

    }
}

上面的例子是对一个图片的JLabel的透明度调整为50%;其他的组件也可以用类似的方法进行调整。

  • 3
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值