TheMatrixRecoder
TheMatrixRecoder

Reputation: 31

JPanel remove color gradient

I have the following problem:

I have my own instance of JPanel to create an ImageButton. When I set a background, it automatically adds a color gradient, which causes the transparent image to have a background that doesn't fit the color of my JFrame.

How can I remove this gradient?

public ImageButton(Runnable exec, boolean on) {
        super();

        setBackground(new Color(238,238,238));
        setVisible(false);
        switched_on = on;
        setSize(new Dimension(64, 64));
        setPreferredSize(new Dimension(64, 64));
        if(on) {
            img = ImageButton.on;
        }else{
            img = ImageButton.off;
        }
}

@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    g.drawImage(img, 0, 0, null);
}

Screenshot: ImageButton

https://i.sstatic.net/hen6K.png

Another Screenshot, where you see the gradient better

https://i.sstatic.net/k8eFl.png

Upvotes: 0

Views: 467

Answers (2)

TheMatrixRecoder
TheMatrixRecoder

Reputation: 31

I finally found the problem. I tried to find this error inside my source, but instead, the image itself has a whitish background in the upper left corner.

Upvotes: 0

camickr
camickr

Reputation: 324118

When I set a background, it automatically adds a color gradient, which causes the transparent image to have a background that doesn't fit the color of my JFrame.

Make the panel transparent:

setOpaque( false );

Now both the image and the panel will be transparent so the background color will be the background of the parent component of your ImagePanel.

Although an easier approach is to just use a JLabel. A JLabel is transparent by default. Then you can just use the setIcon(...) method to change the image. So there is no need for custom painting or a custom component.

Upvotes: 2

Related Questions