Reputation: 361
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.
Upvotes: 1
Views: 1032
Reputation: 168825
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.sstatic.net/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.
Upvotes: 4
Reputation: 109813
Maybe you want to show only Icon and remove rest from JButton by set myButton.setContentAreaFilled(false), for example
Upvotes: 3