JAVA父类多态指向子类对象,然后用一个子类对象来恢复原子类对象,为什么会失败?
/* 可以显示图标的ListCell绘制器 */
public class IconListItemRenderer extends JLabel implements ListCellRenderer
{
private Border
selectedBorder = BorderFactory.createLineBorder(Color.blue,1),
emptyBorder = BorderFactory.createEmptyBorder(1,1,1,1);
IconListItem item ;
public Component getListCellRendererComponent(
JList list,
Object value,
int index,
boolean isSelected,
boolean cellHasFocus)
{
try
{
if(value instanceof IconListItem){
item = (IconListItem)value;
}
}catch(Exception e){System.out.println("转换失败!");}
this.setIcon(item.getIcon());
this.setText(item.getText());
if ( isSelected ) setBorder (selectedBorder);
else setBorder(emptyBorder);
return this;
}
}
this.setIcon(item.getIcon());this.setText(item.getText());导致运行时失败,知道错什么的告诉下,谢谢!