JList - Highlight specific cells in red

最后都变了- 提交于 2019-12-25 05:16:20

问题


I have a JList on a form. When the form loads, the JList is populated with items from my array. The items are products and have a "quantity in stock" number next to the product details. In the code below I find the stock number and if it is less than 5 I want that line to be highlighted in red.

At the moment my WHOLE Jlist is being highlighted in red if there is any quantity which is less than 5. Help!! I'm pretty new to Java so please explain as simply as possible! If someone could explain why my code isn't working properly as well that would be great - I really don't understand quite a lot of the "Cell Rendering" stuff - I only came across it yesterday.

public void lowStock(){
    DefaultListModel<String> list = new DefaultListModel<String>();
    list = (DefaultListModel) lstProducts.getModel();
    int listSize = list.getSize();

    for (int i=0; i<listSize; i++){
        String element = list.get(i);
        int blankSpace = element.lastIndexOf("  ");
        String quantity = element.substring(blankSpace).trim();
        final int intQuantity = Integer.parseInt(quantity);

        if (intQuantity < 5){
            ListCellRenderer lstclrnd;
            lstProducts.setCellRenderer(new DefaultListCellRenderer(){  

            //element.setBackGround(Color.red);
        });
    }
}

class MyListRenderer extends DefaultListCellRenderer  
{  
    private HashMap theChosen = new HashMap();  

    public Component getListCellRendererComponent(JList list,  
            Object value, int index, boolean isSelected,  
            boolean cellHasFocus)  
    {  
        super.getListCellRendererComponent(list, value, index,  
                isSelected, cellHasFocus );  

            theChosen.put( value, "chosen" );  
            setBackground( Color.red ); 
           if( theChosen.containsKey( value ) )  
        {  
            setBackground( Color.red );  
        } 

回答1:


Your problem lies in the following piece of code:

public Component getListCellRendererComponent(JList list,  
        Object value, int index, boolean isSelected,  
        boolean cellHasFocus)  {  

    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);  

    theChosen.put(value, "chosen");  
    setBackground( Color.red ); //MOST LIKELY THIS LINE RIGHT HERE
    if( theChosen.containsKey( value )) {  
        setBackground( Color.red );  
    }
    ...

Without that line setBackground( Color.red );, no color should be set.

It is kind of hard to see exactly what is going on- you should submit an SSCCE. This is just a couple of code snippets.

Honestly, I think what you are trying to do is set a ListCellRenderer for your JList. Something like the following should suffice.

 class MyCellRenderer extends JLabel implements ListCellRenderer<Object> {
     public MyCellRenderer() {
         setOpaque(true);
     }

     public Component getListCellRendererComponent(JList<?> list,
                                                   Object value,
                                                   int index,
                                                   boolean isSelected,
                                                   boolean cellHasFocus) {

         //I don't know why you would have leading whitespace here... but w/e
         //This probably needs modification depending on your data
         String quantity = value.toString().substring(blankSpace).trim();
         setText(quantity);
         int intQuantity = Integer.parseInt(quantity);

         Color background;
         Color foreground;

         if (intQuantity < 5) {
             background = Color.RED;
             foreground = Color.WHITE;

         } else {
             background = Color.WHITE;
             foreground = Color.BLACK;
         }

         setBackground(background);
         setForeground(foreground);

         return this;
     }
 }

Then, your JList, probably right after you initialize it, needs to do the following:

myJList.setCellRenderer(new MyCellRenderer());



回答2:


You're trying to do way to much. You don't need the Map at all. See below, very simple.

The reason you currently getting all colored red is because you have setBackground outside of the if. So no matter what happens, it will be red. You can see more here on how to use a render for a list

import java.awt.Color;
import java.awt.Component;
import javax.swing.DefaultListCellRenderer;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.SwingUtilities;

public class ListColorRed {

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Integer[] nums = {10, 2, 5, 8, 2, 9, 2, 8, 10, 4, 6};
                JList list = new JList(nums);
                list.setCellRenderer(new DefaultListCellRenderer() {

                    @Override
                    public Component getListCellRendererComponent(JList list,
                            Object value, int index, boolean isSelected,
                            boolean cellHasFocus) {

                        super.getListCellRendererComponent(list, value, index,
                                isSelected, cellHasFocus);

                        Integer num = (Integer) value;

                        if (num < 5) {
                            setBackground(Color.RED);
                        }

                        return this;
                    }
                });

                JOptionPane.showMessageDialog(null, new JScrollPane(list));
            }
        });
    }
}



来源:https://stackoverflow.com/questions/22180574/jlist-highlight-specific-cells-in-red

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!