I have this tiny flag that I am using for an icon on the default JButton. But when I load it it keeps the white box that is around it which shows up on the JButton's blue background (at least that's the color for me). I was wondering how I remove this white color.
Asked
Active
Viewed 997 times
1
-
4You need to create a "transparent" icon. – eternaln00b Feb 09 '12 at 04:36
-
@SiddharthaShankar You should post that as an answer. – Andrew Thompson Feb 09 '12 at 06:29
-
@AndrewThompson It was late at night, and I was lazy. :) Thanks for posting a full and comprehensive answer. *thumbs up* – eternaln00b Feb 09 '12 at 12:27
2 Answers
4
Of course, Siddhartha Shankar provided the correct answer, and mKorbel suggested a good (lateral thinking) alternative, but I was compelled to post this simply because 'we have the technology'. ;)
import java.awt.image.BufferedImage;
import java.awt.*;
import javax.swing.*;
import java.net.URL;
import javax.imageio.ImageIO;
class TransparentIcon {
public static void main(String[] args) throws Exception {
URL url = new URL("https://i.stack.imgur.com/DD7gI.gif");
final BufferedImage bi = ImageIO.read(url);
final BufferedImage tr = new BufferedImage(
bi.getWidth(),
bi.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Color cTrans = new Color(255,255,255,0);
for (int x=0; x<bi.getWidth(); x++) {
for (int y=0; y<bi.getHeight(); y++) {
Color c = new Color( bi.getRGB(x,y) );
Color cNew = (c.equals(Color.WHITE) ? cTrans : c);
tr.setRGB(x,y,cNew.getRGB());
}
}
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JPanel p = new JPanel(new GridLayout(1,0,5,5));
p.add(new JButton(new ImageIcon(bi)));
p.add(new JButton(new ImageIcon(tr)));
JOptionPane.showMessageDialog(null, p);
}
});
}
}
BTW - you can combine my suggestion with that of Siddhartha by using ImageIO.write()
, using the image formed from these shenanigans.

Andrew Thompson
- 168,117
- 40
- 217
- 433