1

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

现在它只输出按钮的属性而不是怎么来

4

1 回答 1

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());

它有效。

于 2013-03-29T14:53:38.140 回答