Why my selected item background not changing? I surely know that i press list item because my System.out.println says my Current selection and showing id of selected item. No errors no nothing just not working. Why ?
Object[] tablen = sqltable.toArray();
JList list;
list = new JList(tablen);
list.addListSelectionListener(new ListSelectionListener(){
@Override
public void valueChanged(ListSelectionEvent e) {
int idx = list.getSelectedIndex();
setOpaque(true);
if (idx != -1){
//list.setSelectionBackground(Color.lightGray);
// list.setSelectionForeground(Color.lightGray);
setForeground(Color.red);
setBackground(Color.BLUE);
setBackground(list.getSelectionBackground());
setForeground(list.getSelectionForeground());
System.out.println("Current selection: " + tablen[idx]);
}else{
setForeground(Color.red);
setBackground(Color.BLUE);
setBackground(list.getBackground());
setForeground(list.getForeground());
System.out.println("Please choose a language.");
}
}
});
list.setCellRenderer(new ListCellRenderer() {
@Override
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
String[] val = (String[]) value;
return new JLabel(val[0]);
}
});
Beware in your cell renderer implementation that JLabel
is non opaque by default, and probably is the reason why the background color in the list cell renderer is not painted. (see related )
On the other hand I'd take a look to Providing a Custom Renderer for a better example on how to implement a custom cell renderer.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.