Use an image with no transparency and the 'background' will be whatever color is in the BG of the image.
The icons are jpg files (with no transparency) but only fill a part of the whole button..
See this question for tips on how to get buttons that are the exact size of the icon. The image below is formed from 4 buttons and 5 labels with the icons cut from a single image.
..the text below the icon would still show the button background color..
Oh right. Text as well.
In that case, the best strategy is to create an image with a transparent BG from the existing image, then use it in whatever button (with whatever GB color) it comes.
To do that, get a PNG of the image (PNG is not lossy like JPG), and use a dedicated image editor to save it with a transparent BG. But if we are forced to do it at run-time, consider using something like this:
This image actually demonstrates the lossy nature of JPG. We have to go more & more 'distant' from the base BG color to try and pick up all pixels that are outside the original icon. Even at its loosest interpretation of similar color, I still see some spots I would prefer removed.
import java.awt.*;
import java.awt.image.BufferedImage;
import javax.swing.*;
import javax.imageio.ImageIO;
import java.net.URL;
class ImageBackgroundCleaner {
public static BufferedImage clearImageBackground(BufferedImage solidBG, int distance) {
int w = solidBG.getWidth();
int h = solidBG.getHeight();
BufferedImage transparentBG = new BufferedImage(
w,
h,
BufferedImage.TYPE_INT_ARGB);
int c = solidBG.getRGB(0, 0);
for (int xx=0; xx<w; xx++) {
for(int yy=0; yy<h; yy++) {
int s = solidBG.getRGB(xx, yy);
if (getColorDistance(s,c)>=distance) {
transparentBG.setRGB(xx, yy, s);
}
}
}
return transparentBG;
}
public static int getColorDistance(int color1, int color2) {
Color c1 = new Color(color1);
Color c2 = new Color(color2);
int r1 = c1.getRed();
int g1 = c1.getGreen();
int b1 = c1.getBlue();
int r2 = c2.getRed();
int g2 = c2.getGreen();
int b2 = c2.getBlue();
return Math.abs(r1-r2) + Math.abs(g1-g2) + Math.abs(b1-b2);
}
public static void main(String[] args) throws Exception {
URL url = new URL("http://i.stack.imgur.com/Yzfbk.png");
BufferedImage bi = ImageIO.read(url);
final BufferedImage img = bi.getSubimage(39, 21, 40, 40);
Runnable r = new Runnable() {
@Override
public void run() {
JPanel gui = new JPanel(new GridLayout(3,0,5,5));
gui.setBackground(Color.RED);
JLabel original = new JLabel(new ImageIcon(img));
gui.add(original);
int start = 12;
int inc = 3;
for (int ii=start; ii<start+(8*inc); ii+=inc) {
gui.add(new JLabel(new ImageIcon(clearImageBackground(img, ii))));
}
JOptionPane.showMessageDialog(null, gui);
}
};
// Swing GUIs should be created and updated on the EDT
// http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html
SwingUtilities.invokeLater(r);
}
}