Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting foreground for JList elements which fulfill certain statement

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;
        }        
    }
like image 504
Yoda Avatar asked Feb 07 '26 21:02

Yoda


1 Answers

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.

enter image description here

like image 174
alex2410 Avatar answered Feb 09 '26 11:02

alex2410