Question

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;
        }        
    }
Was it helpful?

Solution 2

Recommendations:

  • Have your renderer extend DefaultListCellRenderer.
  • Override the getListCellRendererComponent method.
  • Return the super.getListCellRendererComponent(...) after you've made your changes.

For example, in one of my projects, I have:

@SuppressWarnings("serial")
class MyLabPanelListCellRenderer extends DefaultListCellRenderer {
   @Override
   public Component getListCellRendererComponent(JList list, Object value,
         int index, boolean isSelected, boolean cellHasFocus) {
      if (value == null) {
         value = "";
      } else {
         value = ((LabPanel) value).getLabPanelDisplayName();
      }
      return super.getListCellRendererComponent(list, value, index, isSelected,
            cellHasFocus);
   }
}

Or for a more complete example:

import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.util.Random;
import javax.swing.*;

@SuppressWarnings("serial")
public class TestListRenderer extends JPanel {
   private static final int TOTAL_ITEMS = 100;
   private static final int MAX_VALUE = 15;
   private static final int VISIBLE_ROW_COUNT = 15;
   private DefaultListModel<Integer> listModel = new DefaultListModel<>();
   private JList<Integer> myList = new JList<>(listModel);
   private Random random = new Random();

   public TestListRenderer() {
      for (int i = 0; i < TOTAL_ITEMS; i++) {
         listModel.addElement(random.nextInt(MAX_VALUE));
      }

      myList.setCellRenderer(new MyListCellRenderer());

      myList.setVisibleRowCount(VISIBLE_ROW_COUNT);
      add(new JScrollPane(myList));
   }

   private class MyListCellRenderer extends DefaultListCellRenderer {
      private static final int PREF_W = 50;
      private static final int MAX_INT_VALUE = 10;
      private final Color HIGH_VALUE_FG = Color.white;
      private final Color HIGH_VALUE_BG = Color.red;

      @Override
      public Dimension getPreferredSize() {
         Dimension superSize = super.getPreferredSize();
         return new Dimension(PREF_W, superSize.height);
      }

      @Override
      public Component getListCellRendererComponent(JList<?> list,
            Object value, int index, boolean isSelected, boolean cellHasFocus) {
         Component superRenderer = super.getListCellRendererComponent(list, value, index, isSelected,
               cellHasFocus);

         setBackground(null);
         setForeground(null);
         if (value != null && ((Integer) value).intValue() > MAX_INT_VALUE) {
            setBackground(HIGH_VALUE_BG);
            setForeground(HIGH_VALUE_FG);
         }

         return superRenderer;
      }
   }

   private static void createAndShowGui() {
      TestListRenderer mainPanel = new TestListRenderer();

      JFrame frame = new JFrame("TestListRenderer");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

Which displays numbers in a JList with a red background if > 10.

enter image description here

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top