How to change a cell icon of JList in run time

戏子无情 提交于 2019-12-02 09:59:07

You're doing it backwards. The cell renderer should simply use the isSelected argument and set the icon you want if this argument is true, and no icon if it's false.

No need for a selection listener. The renderer will automatically be invoked when the selection changes.

  • I think that there is easier method as public void valueChanged(ListSelectionEvent e) { from ListSelectionListener

  • see getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { there you can to override isSelected, for multisleection in SelectionModel is better cellHasFocus

trashgod

Is there any way to change the icons after rendered?

You can dynamically choose the icon based on criteria such as index or value at the time of rendering. Using the example cited here, the following renderer produces the image shown. You can always update an icon and repaint().

private class ListRenderer extends DefaultListCellRenderer {

    Icon icon1 = UIManager.getIcon("html.pendingImage");
    Icon icon2 = UIManager.getIcon("html.missingImage");

    public ListRenderer() {
        this.setBorder(BorderFactory.createLineBorder(Color.red));
    }

    @Override
    public Component getListCellRendererComponent(JList list, Object
            value, int index, boolean isSelected, boolean cellHasFocus) {
        JLabel label = (JLabel) super.getListCellRendererComponent(
            list, value, index, isSelected, cellHasFocus);
        label.setBorder(BorderFactory.createEmptyBorder(N, N, N, N));
        label.setIcon(icon1);
        if (index % 2 == 0) {
            label.setIcon(icon2);
        }
        label.setHorizontalTextPosition(JLabel.CENTER);
        label.setVerticalTextPosition(JLabel.BOTTOM);
        return label;
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!