【Java开源代码栏目提醒】:本文主要为网学会员提供BeanListCellRenderer.java,希望对需要BeanListCellRenderer.java网友有所帮助,学习一下!
package com.cownew.ctk.ui.swing;
import java.awt.Component;
import java.io.Serializable;
import java.lang.reflect.InvocationTargetException;
import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.UIManager;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import org.apache.commons.beanutils.BeanUtils;
import com.cownew.ctk.common.ExceptionUtils;
public class BeanListCellRenderer implements ListCellRenderer, Serializable
{
private JLabel label;
private String displayProperty;
public BeanListCellRenderer(String displayProperty)
{
super();
this.displayProperty = displayProperty;
label = new JLabel();
}
public Component getListCellRendererComponent(JList list, Object value,
int index, boolean isSelected, boolean cellHasFocus)
{
label.setComponentOrientation(list.getComponentOrientation());
if (isSelected)
{
label.setBackground(list.getSelectionBackground());
label.setForeground(list.getSelectionForeground());
} else
{
label.setBackground(list.getBackground());
label.setForeground(list.getForeground());
}
if (value instanceof Icon)
{
label.setIcon((Icon) value);
label.setText("");
} else
{
label.setIcon(null);
String displayValue = null;
try
{
displayValue = BeanUtils.getProperty(value, displayProperty);
} catch (IllegalAccessException e)
{
throw ExceptionUtils.toRuntimeException(e);
} catch (InvocationTargetException e)
{
throw ExceptionUtils.toRuntimeException(e);
} catch (NoSuchMethodException e)
{
throw ExceptionUtils.toRuntimeException(e);
}
label.setText((value == null) ? "" : displayValue);
}
label.setEnabled(list.isEnabled());
label.setFont(list.getFont());
//获得焦点时高亮显示
Border focusBorder = UIManager
.getBorder("List.focusCellHighlightBorder");
//失去焦点时普通显示
EmptyBorder emptyBorder = new EmptyBorder(1, 1, 1, 1);
label.setBorder((cellHasFocus) ? focusBorder : emptyBorder);
return label;
}
}