设置JLabel或其他组件透明度

时间:2021-03-30 22:06:51

在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%;其他的组件也可以用类似的方法进行调整。