TheMatrixRecoder TheMatrixRecoder - 9 months ago 87
Java Question

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.stack.imgur.com/hen6K.png

Another Screenshot, where you see the gradient better

https://i.stack.imgur.com/k8eFl.png

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download