List 怎么让指定行选中状态 或者 设置 某行的颜色(在线等待)!!!!

解决方案 »

  1.   

    实现ListCellRenderer,或者从DefaultListCellRenderer继承,在getListCellRendererComponent方法中可以设置某行的颜色
    下面是DefaultListCellRenderer的源代码,修改一下就行,可以设置选中的颜色,也可以设置有焦点的border:public Component getListCellRendererComponent(
            JList list,
    Object value,
            int index,
            boolean isSelected,
            boolean cellHasFocus)
        {
            setComponentOrientation(list.getComponentOrientation());        Color bg = null;
            Color fg = null;        JList.DropLocation dropLocation = list.getDropLocation();
            if (dropLocation != null
                    && !dropLocation.isInsert()
                    && dropLocation.getIndex() == index) {            bg = UIManager.getColor("List.dropCellBackground");
                fg = UIManager.getColor("List.dropCellForeground");            isSelected = true;
            } if (isSelected) {
                setBackground(bg == null ? list.getSelectionBackground() : bg);
        setForeground(fg == null ? list.getSelectionForeground() : fg);
    }
    else {
        setBackground(list.getBackground());
        setForeground(list.getForeground());
    } if (value instanceof Icon) {
        setIcon((Icon)value);
        setText("");
    }
    else {
        setIcon(null);
        setText((value == null) ? "" : value.toString());
    } setEnabled(list.isEnabled());
    setFont(list.getFont());        Border border = null;
            if (cellHasFocus) {
                if (isSelected) {
                    border = UIManager.getBorder("List.focusSelectedCellHighlightBorder");
                }
                if (border == null) {
                    border = UIManager.getBorder("List.focusCellHighlightBorder");
                }
            } else {
                border = getNoFocusBorder();
            }
    setBorder(border); return this;
        }