I have always had problems with JLists and theirs' renderers. I have class Result which has field: private double sum;
I also created aJList containing instances of Result class:
model = new DefaultListModel<Result>();
list = new JList<>(model);
I would like to set foreground or background(whichever) to red for those elements in the list that fulfill this statement: result.sum > 10.
I have tried to write a class that extends ListCellRenderer but it ended with disaster not worth mentioning. Please help.
import java.awt.Component;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class MyCellRenderer implements ListCellRenderer<Result> {
@Override
public Component getListCellRendererComponent(JList<? extends Result> arg0, Result arg1, int arg2, boolean arg3, boolean arg4) {
if(result.getSuma() > 10)
setForeground(Color.red);
return arg0;
}
}
I recommend you to use DefaultListCellRenderer and override its getListCellRendererComponent method for your porpuses, in that return super.getListCellRendererComponent() with your customiztion. I give you an example of Renderer for String, modify it for your porpuses :
private static ListCellRenderer<? super String> getCellRenderer() {
return new DefaultListCellRenderer(){
@Override
public Component getListCellRendererComponent(JList<?> list,Object value, int index, boolean isSelected,boolean cellHasFocus) {
Component listCellRendererComponent = super.getListCellRendererComponent(list, value, index, isSelected,cellHasFocus);
if(value.toString().length()>1){
listCellRendererComponent.setBackground(Color.RED);
} else {
listCellRendererComponent.setBackground(list.getBackground());
}
return listCellRendererComponent;
}
};
}
this method set background color for text, length of which more than 1.

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With