我创建了一个用我自己的 AbstractListModel 子类构造的 JList,模型存储 Action 类的实例,并且我将 getElementAt() 定义为
public final Object getElementAt(final int index)
{
return ((Action) actionList.get(index)).getValue(Action.NAME);
}
我的 JList 显示操作名称列表,这没关系。
但是这些操作也定义了一个图标,所以如果我这样做
public final Object getElementAt(final int index)
{
return ((Action) actionList.get(index)).getValue(Action.SMALL_ICON)
);
}
现在改为显示图标。
但我两者都想要,所以我尝试了
public final Object getElementAt(final int index)
{
return new JButton(
(String)((Action) actionList.get(index)).getValue(Action.NAME),
(Icon)((Action) actionList.get(index)).getValue(Action.SMALL_ICON)
);
}
现在它只输出按钮的属性,而不是为什么
最佳答案
没关系,阅读 javadoc 有帮助!
getElementAt() 应该是
public final Object getElementAt(final int index)
{
return actionList.get(index);
}
然后我查看 javadoc 中的渲染并修改如下:
class MyCellRenderer extends JLabel implements ListCellRenderer {
ImageIcon longIcon = new ImageIcon("long.gif");
ImageIcon shortIcon = new ImageIcon("short.gif");
// This is the only method defined by ListCellRenderer.
// We just reconfigure the JLabel each time we're called.
public Component getListCellRendererComponent(
JList list, // the list
Object value, // value to display
int index, // cell index
boolean isSelected, // is the cell selected
boolean cellHasFocus) // does the cell have focus
{
Action action = (Action)value;
setText((String)action.getValue(Action.NAME));
setIcon((Icon)action.getValue(Action.SMALL_ICON));
if (isSelected) {
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
} else {
setBackground(list.getBackground());
setForeground(list.getForeground());
}
setEnabled(list.isEnabled());
setFont(list.getFont());
setOpaque(true);
return this;
}
}
然后设置为Jlists渲染器
availableList.setCellRenderer(new MyCellRenderer());
并且它有效。
关于java - 在 JList 中渲染图标和文本的最佳方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15705462/