Install List cell renderer : JList Renderer « Swing « Java Tutorial






Install List cell renderer
import java.awt.Component;

import javax.swing.Icon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;

class MyCellRenderer extends JLabel implements ListCellRenderer {

  public MyCellRenderer() {
    setOpaque(true);
  }

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

    if (isSelected) {
      setBackground(list.getSelectionBackground());
      setForeground(list.getSelectionForeground());
    } else {
      setBackground(list.getBackground());
      setForeground(list.getForeground());
    }
    return this;
  }
}

public class JListRenderer {

  public static void main(String[] a) {
    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    
    JList list = new JList(new String[]{"A","B","C"});  
    list.setCellRenderer(new MyCellRenderer());  
    frame.add(new JScrollPane(list));   


    frame.setSize(300, 200);
    frame.setVisible(true);
  }

}








14.41.JList Renderer
14.41.1.Rendering JList Elements
14.41.2.Install List cell rendererInstall List cell renderer
14.41.3.Add your own ListCellRendererAdd your own ListCellRenderer
14.41.4.Creating a Complex ListCellRenderer: font, icon and colorCreating a Complex ListCellRenderer: font, icon and color
14.41.5.The items can be arbitrary objects. The toString() method of the objects is displayed in the list component.
14.41.6.Setting the Dimensions of an Item in a JList Component
14.41.7.Set the item dimensions using a sample value
14.41.8.Change the layout orientation so that its items are displayed top-to-bottom and left-to-right.