大神们请帮忙看看,谢谢啦!
class ImageCellRenderer extends JPanel
implements ListCellRenderer<String>
{
private ImageIcon icon;
private String name;
// 定义绘制单元格时的背景色
private Color background;
// 定义绘制单元格时的前景色
private Color foreground;
public Component getListCellRendererComponent(JList list
, String value , int index
, boolean isSelected , boolean cellHasFocus)
{
icon = new ImageIcon("ico/" + value + ".gif");
name = value;
background = isSelected ? list.getSelectionBackground()
: list.getBackground();
foreground = isSelected ? list.getSelectionForeground()
: list.getForeground();
// 返回该JPanel对象作为列表项绘制器
return this;
}
// 重写paintComponent方法,改变JPanel的外观
public void paintComponent(Graphics g)
{
int imageWidth = icon.getImage().getWidth(null);
int imageHeight = icon.getImage().getHeight(null);
g.setColor(background);
g.fillRect(0, 0, getWidth(), getHeight());
g.setColor(foreground);
// 绘制好友图标
g.drawImage(icon.getImage() , getWidth() / 2
- imageWidth / 2 , 10 , null);
g.setFont(new Font("SansSerif" , Font.BOLD , 18));
// 绘制好友用户名
g.drawString(name, getWidth() / 2
- name.length() * 10 , imageHeight + 30 );
}
这里重写paintComponent方法,但我不是很明白:
1.为什么这里不用super(g),或者 getListCellRendererComponent()也没有用super;,下面这个则用了super。
class MyRenderer extends DefaultTreeCellRenderer
{
// 初始化5个图标
……
public Component getTreeCellRendererComponent(JTree tree
, Object value , boolean sel , boolean expanded
, boolean leaf , int row , boolean hasFocus)
{
// 执行父类默认的节点绘制操作
super.getTreeCellRendererComponent(tree , value
, sel, expanded , leaf , row , hasFocus);
DefaultMutableTreeNode node = (DefaultMutableTreeNode)value;
NodeData data = (NodeData)node.getUserObject();
// 根据数据节点里的nodeType数据决定节点图标
2.g.fillRect(0, 0, getWidth(), getHeight());的效果应该是点击时出现背景颜色,但为什么不用事件机制就可以产生这种效果