Randy_E Randy_E - 1 year ago 133
Java Question

How to keep transparent background in a png image

I have been working on a project for a while. I am building a playing card deck class that I will eventually use in making my own solitaire game. I decided to use images for the indexes of the card rather than having java draw them. I have drawn my own suits in Illustrator and saved them as PNG's with a transparent background. I am able to get the image to show up in my program when I rum it, however when I add the image to my JFrame the background color disappears leading me to believe that for some reason the transparency is not being kept. I have tried two different methods of adding the image to my GUI and have the same result both times. One method I have tried is the method suggested here How to add an image to a JPanel?
and the other method I have tried is the one suggested here How can I display a BufferedImage in a JFrame?
Both of these methods are not what I am looking for. I want my suit to display on screen and be able to see the background still.

Here is the current code I would like to get working properly, I do realize that it compiles and runs just fine, but I want to be able to still see the background.

import java.io.File;
import java.io.IOException;

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

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;

import javax.imageio.ImageIO;

public class ImageReadTest extends JPanel{
public static void main(String[] args){
//Just a simple test on reading pictures into a java file and drawing them
//onto a JFrame
System.out.println("Java Image Read Test");
JFrame frame = new JFrame("Image Reader");

frame.add(new ImageReadTest());

private BufferedImage image;
public ImageReadTest(){
image = ImageIO.read(new File("Club.png"));
} catch(IOException e){
protected void paintComponent(Graphics g){
g.drawImage(image, 90, 90, null);
}//end class ImageReadTest

Here is my image for testing my code, thanks for taking the time to read and help!

Answer Source

The problem is not in fetching image. The program is giving you correct result i.e. image's background is transparent. But the color of your ImageReadTest JPanel and the ContentPane of your jFrame is same. Because of which you are unable to detect the difference.

Just replace following line


With this


Thing to understand here is that there is one more layer between your jPanel and jFrame, which is ContentPane.

Edit : Because you want to make your own pane transparent, you will have to make its opacity as false. To do this add following line in your constructor.

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