简体   繁体   English

如何使JButton具有透明图标和非透明文本?

[英]How to make JButton with transparent icon and non-transparent text?

I need to make a JButton with an image icon and regular text. 我需要制作一个带有图像图标和常规文本的JButton。 This question is not duplicate of How to make JButton with transparent background and regular text? 这个问题不是如何使JButton具有透明背景和常规文本的重复吗? , as I need to upload an image as icon and make it transparent as well. ,因为我需要将图像上传为图标并使其透明。 I tried to use overriden paintComponent() method 我试图使用重写的paintComponent()方法

    @Override
    public void paintComponent(java.awt.Graphics g) {
        java.awt.Graphics2D g2 = (java.awt.Graphics2D) g;
        g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
        super.paintComponent(g2);
    }

But all it does is paints icon and text both transparent, also button does not refresh properly. 但是它所做的只是将图标和文本都绘制为透明,并且按钮也无法正确刷新。 Are there any possible workarounds? 有没有可能的解决方法?

UPDATE UPDATE

The way I am setting the button is the following (item.getImage() returns array of bytes): 我设置按钮的方式如下(item.getImage()返回字节数组):

        setFocusable(true);
        setFocusPainted(true);
        setVerticalTextPosition(SwingConstants.CENTER);
        setHorizontalTextPosition(SwingConstants.CENTER);

        if(item.getImage() != null) {
            int w = BUTTON_SIZE - 10;
            int h = BUTTON_SIZE - 10;

            if(menuItem.isShowImageOnly()) {
                setIcon(menuItem.getScaledImage(w, h));
            }
            else {
                w = 80;
                h = 40;

                setIcon(menuItem.getScaledImage(w, h));
            }

Just draw the transparency on the Image first 只需先在图像上绘制透明度

    Image im = ...;
    java.awt.Graphics2D g2 = (java.awt.Graphics2D) im.getGraphics();
    g2.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, alpha));
    g2.drawImage(0,0, im, null);
    g2.dispose();
    ImageIcon icon = ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM