在JList中渲染图标和文本的最佳方法

时间:2013-03-29 14:39:03

标签: java swing jbutton jlist

我创建了一个用我自己的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)
            );
        }

现在只输出按钮的属性而不是

1 个答案:

答案 0 :(得分:1)

毫不犹豫地阅读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());

它有效。