1

I need to make a JButton with an image icon and regular text. This question is not duplicate of How to make JButton with transparent background and regular text?, as I need to upload an image as icon and make it transparent as well. I tried to use overriden paintComponent() method

    @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

The way I am setting the button is the following (item.getImage() returns array of bytes):

        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));
            }
Community
  • 1
  • 1
Boddha
  • 171
  • 2
  • 9

1 Answers1

2

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 = ...
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • I'm not sure that I understood properly - should I add this code just before calling the setIcon() method? If I try to do so all I get are no buttons at all. – Boddha Nov 13 '15 at 20:09
  • 1
    Yes, that's the idea - before setIcon. Since you haven't pasted any code showing how you are creating the button(s), I can't comment on the problem you are reporting – ControlAltDel Nov 13 '15 at 20:19
  • I've updated the post - added code showing how the buttons are created. Can you comment more, please, regarding the code? – Boddha Nov 15 '15 at 17:30
  • What class is menuItem? – ControlAltDel Nov 16 '15 at 12:10