Caders117
Caders117

Reputation: 317

See JButton through image transparency Java

I am trying to add an image to a JButton such that the user can see the JButton surface and click animation through the transparent parts of a png.

Here is the code for that button:

grid.add(new JPanel(){{
    setLayout(new BorderLayout());
    add(new JButton() {{
        setLayout(new BorderLayout());
        setBorder(new EmptyBorder(0, 0, 0, 0));
        add(new JImageComponent(new ImageIcon(this.getClass().getResource("/Center.png"))));
    }});
}});

The JImageComponent is just my own hacked together swing image component. Here is its code:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.MediaTracker;
import java.awt.image.BufferedImage;

import javax.swing.BorderFactory;
import javax.swing.ImageIcon;
import javax.swing.JPanel;

public class JImageComponent extends JPanel {

    Image image;

    public JImageComponent(ImageIcon img) {
        BufferedImage imgs;
        setBorder(BorderFactory.createLineBorder(Color.black));
        setPreferredSize(new Dimension(1000, 1000));
        image = img.getImage();
        repaint();
    }

    @Override
    public void paintComponent(Graphics g) {
        super.paintComponent(g);
        //Container parent = getParent();
        Image scaledImage = image.getScaledInstance(getWidth(), getHeight(), Image.SCALE_DEFAULT);
        MediaTracker tracker = new MediaTracker(new java.awt.Container());
        tracker.addImage(scaledImage, 0);
        try {
            tracker.waitForAll();
        } catch (InterruptedException ex) {
            throw new RuntimeException("Image loading interrupted", ex);
        }
        g.drawImage(scaledImage, 0, 0, this);
    }
}

This yields the result shown below:

enter image description here

I would like the "metal" blue of the JButton to show through the center of the black square in the far left of the center row.

Is that possible?

Upvotes: 1

Views: 38

Answers (1)

Devon_C_Miller
Devon_C_Miller

Reputation: 16518

Call setOpaque(false) on JImageComponent.

By default, Swing sees that you're rendering over the button, so it skips painting it. Setting opaque false tells Swing that what you're painting is not opaque, and it cannot skip rendering the object behind it.

Upvotes: 1

Related Questions