【发布时间】:2014-02-09 15:15:30
【问题描述】:
我在 JTable 的自定义渲染器中将此图标用于 JLabel。选择表格中的行时,图标背景显示为白色。
我使用paint.net 创建了一个绿色三角形,并将其背景设置为白色,alpha 为255。这就是我在这段代码中用来为JLabel 创建IconImage 的图像;出于外部原因,我对图标使用不同的宽度。这是一个示例程序,展示了所做的工作:
package spacecheck.images;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
/**
* represents an icon used in the directory tree; handles 'expanded' and
* 'unexpanded' directories as well as indentation representing different
* levels.
* @author rcook
*
*/
public class TreeIconExample
{
public static int UNEXPANDED = 1;
public static int EXPANDED = 2;
@SuppressWarnings({"unused"})
private void say (String msg) { System.out.println(msg); }
private static ImageIcon expandedIcon = null;
private static ImageIcon unexpandedIcon = null;
private static int iconHeight = 0;
private static int iconWidth = 0;
private static ArrayList<ImageIcon> cachedExpandedIcons = new ArrayList<ImageIcon>();
private static ArrayList<ImageIcon> cachedUnexpandedIcons = new ArrayList<ImageIcon>();
static
{
expandedIcon = new ImageIcon(TreeIconExample.class.getResource("images/Expanded.GIF"));
unexpandedIcon = new ImageIcon(TreeIconExample.class.getResource("images/Unexpanded.GIF"));
iconHeight = unexpandedIcon.getIconHeight();
iconWidth = unexpandedIcon.getIconWidth();
}
public TreeIconExample() { }
public static void main(String ... arguments)
{
JFrame frame = new JFrame("icon test");
frame.setBackground(Color.blue);
JLabel label = new JLabel("background test");
label.setBackground(Color.magenta);
TreeIconExample treeIcon = new TreeIconExample();
ImageIcon icon = treeIcon.getIcon(2, false);
label.setIcon(icon);
frame.add(label);
frame.pack();
frame.setVisible(true);
}
/**
* return the icon for an expanded or unexpanded level
* @param int level of folder relative to other levels displayed;
* starts at 0 and increases with depth
* @param boolean indicates whether this level is expanded or not.
* @return ImageIcon appropriate for expansion flag and level.
*/
public ImageIcon getIcon(int level, boolean expanded)
{
ImageIcon result = null;
// generate this icon and store it in the cache before returning it.
ImageIcon baseIcon = unexpandedIcon;
if (expanded) { baseIcon = expandedIcon; }
int iconH = iconHeight;
int iconW = iconWidth*(level+1);
BufferedImage bufferedImage = new BufferedImage(iconW,iconH,BufferedImage.TYPE_INT_ARGB);
Graphics g = bufferedImage.getGraphics();
g.fillRect(0, 0, iconW, iconH);
g.drawImage(baseIcon.getImage(), iconWidth*level, 0, null);
result = new ImageIcon(bufferedImage);
return result;
}
}
这是我的结果:
我想做的是消除图标的白色部分;我希望它是透明的,所以 JLabel 的背景会显示出来。我不知道为什么这个程序中既没有出现洋红色也没有蓝色;如果有人愿意告诉我,我将不胜感激。但图像上的透明背景是我想要弄清楚的主要内容。
【问题讨论】: