JList jlistSpec = new JList(this.getListItemSpecs());
jlistSpec.setFont(new java.awt.Font("宋体",java.awt.Font.PLAIN,12));
jlistSpec.setBackground(Color.yellow);//以上设置字体和颜色是针对整个jlistSpec ,
有没有办法可以只设置某些项的字体和背景颜色的????

解决方案 »

  1.   

    setCellRenderer(ListCellRenderer cellRenderer)
    class SpecCellRenderer
        implements ListCellRenderer {
      int i = 0;
      public Component getListCellRendererComponent(final JList list,
                                                    final Object value,
                                                    final int index,
                                                    final boolean isSelected,
                                                    final boolean cellHasFocus) {
        return new JPanel() {
          public void paintComponent(Graphics g) {
            FontMetrics fm = g.getFontMetrics();        
            g.setColor(isSelected
                       ? list.getSelectionBackground()
                       : list.getBackground()
                       );        
            g.fillRect(0, 0, getWidth(), getHeight());
    //        g.setColor(isSelected
    //                   ? list.getSelectionForeground()
    //                   : list.getForeground()
    //                   );//        g.setColor(i==0
    //                   ? Color.blue
    //                   : Color.orange
    //                   );
            i = i==0?1:0;
          }      public Dimension getPreferredSize() {
            Font font = (Font) value;
            String text = font.getFamily();
            Graphics g = getGraphics();
            FontMetrics fm = g.getFontMetrics(font);
            return new Dimension(fm.stringWidth(text), fm.getHeight());
          }    };
      }
    }
      

  2.   

    import java.awt.*;import javax.swing.*;public class ListCellRendererTest
    { public static void main(String[] args)
    {
    JList list = new JList(new String[] {"Item-1", "Item2", "Item3"});
    list.setCellRenderer(new MyRenderer());
    JScrollPane sp = new JScrollPane(list);
    JFrame f = new JFrame();
    f.getContentPane().add(sp, BorderLayout.CENTER);
    f.pack();
    f.setLocationRelativeTo(null);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.show();
    }

    private static class MyRenderer extends DefaultListCellRenderer
    {
    private Font font1;
    private Font font2; public MyRenderer()
    {
    this.font1 = getFont();
    this.font2 = font1.deriveFont((float)(font1.getSize() + 10));
    }

    public Component getListCellRendererComponent(JList list, Object value, 
    int index, boolean isSelected, boolean cellHasFocus)
    {
    super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
    if (index == 1) {
    setBackground(Color.lightGray);
    }
    setFont(index == 2 ? font2 : font1); return this;
    }
    }
    }