开发者

List selection is not happening in swing

开发者 https://www.devze.com 2023-02-06 19:45 出处:网络
HI, I\'ve a JLIST and assigned it a cellRenderer. but i was not able select element in list. Actually it is selected but visually we can not see that it is selected means i was not able to see which i

HI, I've a JLIST and assigned it a cellRenderer. but i was not able select element in list. Actually it is selected but visually we can not see that it is selected means i was not able to see which item is selected in list.

Screen shot of my list:

List selection is not happening in swing

and what is expected is

List selection is not happening in swing

The second screen shot is without CellRenderer. But when i add CellRenderer i was not able to see the selected item in list.

is it normal behaviour that when you add CellRenderer to list.

what am i doing wrong ???

EDIT:-

this is my CellRenderer class:

public class ContactsRender extends JLabel implements ListCellRenderer {

    private static final long serialVersionUID = 1L;

    ImageIcon img;

    public ContactsRender(){
        setOpaque(true);
        setIconTextGap(12);
        setBackground(Color.WHITE);
        setForeground(Color.black);
    }

    @Override
    public Component getListCellRendererComponent(JList list,
            Object value, int index, boolean isSelected,
            boolean cellHasFocus) {
        if(value != null){
            User user = (User) value;
            String pres = user.getPresence().toLowerCase();
            if(pres.contains("unavailable")){
                img = new ImageIcon("res/offline.jpg");
            } else {
            img = new ImageIcon开发者_高级运维("res/online.jpg");
            }
            setText(user.getName());
            setIcon(img);

            return this;
        }
        return null;
    }


You implemented your cell renderer incorrectly. The renderer is responsible for setting the renderer background to the selection color.

Read the JList API and follow the link to the Swing tutorial on "How to Use Lists" where you will find working examples that use a JList. You will also find a section on writing a renderer and an example.

Edit: Also, I just noticed you are reading your icon in the renderer code. You should never do this. The icon should only be read once when the renderer is created and then you cache the Icon. Every time a cell needs to be repainted the renderer is called so it is not efficient to keep reading the icon.


On your cell renderer, you have to implement the case for isSelected is true. For your ListCellRenderer :

Component getListCellRendererComponent(JList<? extends E> list,
                                       E value,
                                       int index,
                                       boolean isSelected,
                                       boolean cellHasFocus)
{
 if (!isSelected) doThis(index);
 else doThatForSelectedItem(index);
}
0

精彩评论

暂无评论...
验证码 换一张
取 消