The javax.swing.JList setCellRenderer() method sets a custom renderer for the cells of a JList. This method takes an argument of type ListCellRenderer which determines how each cell in the list should be displayed.
Package Library: javax.swing
Example 1: Using a Default List Cell Renderer
import javax.swing.*;
public class JListExample extends JFrame { public JListExample() { String names[] = { "Alice", "Bob", "Charlie", "David" }; JList list = new JList<>(names); add(list); setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
public static void main(String[] args) { new JListExample(); } }
Output: Alice Bob Charlie David
Example 2: Using a Custom List Cell Renderer
import javax.swing.*; import java.awt.*;
class NameRenderer extends JLabel implements ListCellRenderer { public NameRenderer() { setOpaque(true); }
public class JListExample2 extends JFrame { public JListExample2() { String names[] = { "Alice", "Bob", "Charlie", "David" }; JList list = new JList<>(names); list.setCellRenderer(new NameRenderer()); add(list); setSize(200, 200); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setVisible(true); }
public static void main(String[] args) { new JListExample2(); } }
Output: Alice Bob Charlie David
In this example, we've created a custom list cell renderer by creating a new class that extends JLabel and implements ListCellRenderer interface. The getListCellRendererComponent() method is overriden and customized to set the text, background color and foreground color of each cell in the list. The setCellRenderer() method is used to set this custom renderer for the JList.
Java JList.setCellRenderer - 30 examples found. These are the top rated real world Java examples of javax.swing.JList.setCellRenderer extracted from open source projects. You can rate examples to help us improve the quality of examples.