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 に答える