Use JList component to display custom objects with ListCellRenderer : List « Swing JFC « Java






Use JList component to display custom objects with ListCellRenderer

Use JList component to display custom objects with ListCellRenderer
 
/*
Java Swing, 2nd Edition
By Marc Loy, Robert Eckstein, Dave Wood, James Elliott, Brian Cole
ISBN: 0-596-00408-7
Publisher: O'Reilly 
*/
// SwingListExample.java
//An example of the JList component in action. This program uses a custom
//renderer (BookCellRenderer.java) to show a list of books with icons of their
//covers.
//

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;

public class SwingListExample extends JPanel {

  private BookEntry books[] = {
      new BookEntry("Ant: The Definitive Guide", "1.gif"),
      new BookEntry("Database Programming with JDBC and Java",
          "2.gif"),
      new BookEntry("Developing Java Beans", "3.gif"),
      new BookEntry("Developing JSP Custom Tag Libraries",
          "4.gif"),
      new BookEntry("Java 2D Graphics", "4.gif"),
      new BookEntry("Java and XML", "5.gif"),
      new BookEntry("Java and XSLT", "1.gif"),
      new BookEntry("Java and SOAP", "2.gif"),
      new BookEntry("Learning Java", "3.gif") };

  private JList booklist = new JList(books);

  public SwingListExample() {
    setLayout(new BorderLayout());
    JButton button = new JButton("Print");
    button.addActionListener(new PrintListener());

    booklist = new JList(books);
    booklist.setCellRenderer(new BookCellRenderer());
    booklist.setVisibleRowCount(4);
    JScrollPane pane = new JScrollPane(booklist);

    add(pane, BorderLayout.NORTH);
    add(button, BorderLayout.SOUTH);
  }

  public static void main(String s[]) {
    JFrame frame = new JFrame("List Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setContentPane(new SwingListExample());
    frame.pack();
    frame.setVisible(true);
  }

  // An inner class to respond to clicks on the Print button
  class PrintListener implements ActionListener {
    public void actionPerformed(ActionEvent e) {
      int selected[] = booklist.getSelectedIndices();
      System.out.println("Selected Elements:  ");

      for (int i = 0; i < selected.length; i++) {
        BookEntry element = (BookEntry) booklist.getModel()
            .getElementAt(selected[i]);
        System.out.println("  " + element.getTitle());
      }
    }
  }
}

class BookEntry {
  private final String title;

  private final String imagePath;

  private ImageIcon image;

  public BookEntry(String title, String imagePath) {
    this.title = title;
    this.imagePath = imagePath;
  }

  public String getTitle() {
    return title;
  }

  public ImageIcon getImage() {
    if (image == null) {
      image = new ImageIcon(imagePath);
    }
    return image;
  }

  // Override standard toString method to give a useful result
  public String toString() {
    return title;
  }
}

class BookCellRenderer extends JLabel implements ListCellRenderer {
  private static final Color HIGHLIGHT_COLOR = new Color(0, 0, 128);

  public BookCellRenderer() {
    setOpaque(true);
    setIconTextGap(12);
  }

  public Component getListCellRendererComponent(JList list, Object value,
      int index, boolean isSelected, boolean cellHasFocus) {
    BookEntry entry = (BookEntry) value;
    setText(entry.getTitle());
    setIcon(entry.getImage());
    if (isSelected) {
      setBackground(HIGHLIGHT_COLOR);
      setForeground(Color.white);
    } else {
      setBackground(Color.white);
      setForeground(Color.black);
    }
    return this;
  }
}

           
         
  








Related examples in the same category

1.An example of JList with a DefaultListModelAn example of JList with a DefaultListModel
2.Create JList from array of string valueCreate JList from array of string value
3.A graphical list selection monitorA graphical list selection monitor
4.Test of the DragGesture classes and JList to see if we can recognize a simple drag gestureTest of the DragGesture classes and JList to see if we can recognize a simple drag gesture
5.Dual JList with buttons in betweenDual JList with buttons in between
6.extends ListCellRenderer to display iconsextends ListCellRenderer to display icons
7.Add JList to Scroll paneAdd JList to Scroll pane
8.Dual Sample: JList and ComboBoxDual Sample: JList and ComboBox
9.JList selection changed listenerJList selection changed listener
10.Triple List from same data arrayTriple List from same data array
11.List with and without ScrollPane List with and without ScrollPane
12.Set visible row count and fixed cell height and widthSet visible row count and fixed cell height and width
13.List: Shared Data SampleList: Shared Data Sample
14.List Data Event DemoList Data Event Demo
15.How to use the list componentHow to use the list component
16.Create list from list modelCreate list from list model
17.How to create list cell rendererHow to create list cell renderer
18.React to list selection actionReact to list selection action
19.Construct the list componentConstruct the list component
20.Tab list rendererTab list renderer
21.List with textfield inputList with textfield input
22.Sharing a Model between a JList and JComboBoxSharing a Model between a JList and JComboBox
23.Demonstrate Swing ScrollingListDemonstrate Swing ScrollingList
24.Demonstrate Swing JList ListModelDemonstrate Swing JList ListModel
25.Weak ListModel
26.ListModel DemoListModel Demo
27.ModifyModelSample: ListModel DemoModifyModelSample: ListModel Demo
28.ArrayList with a ListModel for ease of use
29.Drag and Drop:JList and ListDrag and Drop:JList and List
30.List selection event
31.JList is a component that displays a list of objects: It allows the user to select one or more items.JList is a component that displays a list of objects: It allows the user to select one or more items.
32.A JTextArea is a multi-line text area that displays plain text.
33.JTextPane component is an advanced component for working with text.
34.Model for a JButton: manage only the state of the button
35.A default button model
36.JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.JList: ListModel and ListSelectionModel. The ListModel handles data. ListSelectionModel works with the GUI.
37.A single-selection JList.
38.Listening for Changes to the Items in a JList Component
39.Listening for Changes to the Selection in a JList Component
40.Detecting Double and Triple Clicks on an Item in a JList Component
41.Arranging Items in a JList Component
42.changes the layout orientation so that its items are displayed top-to-bottom and left-to-right.
43.Make the number of visible rows dependent on the height of the list, the visibleRowCount property must be set to 0:
44.Setting the Selection Mode of a JList Component
45.The selected items must be in a contiguous range
46.Multiple ranges of selected items are allowed
47.Setting the Selected Items in a JList Component
48.import javax.swing.JList;
49.Select all the items
50.Clear all selections
51.Select the first item
52.Add another selection - the third item
53.Deselect the first item
54.Select a single item
55.Getting the Selected Items in a JList Component
56.Get the index of the last selected item
57.Determine if the third item is selected
58.Determine if there are any selected items
59.Return the selected item objects:
60.Adding and Removing an Item in a JList Component
61.Append an item
62.Insert an item at the beginning
63.Create a list that allows adds and removes
64.Set method replaces an item
65.Methods are used to remove items
66.Getting the Items in a JList Component
67.Methods are used to find an item:
68.These methods can be used to find the range of visible items:
69.Get index of first visible item
70.Get index of last visible item
71.Setting a Tool Tip for an Item in a JList Component
72.Setting the Dimensions of an Item in a JList Component
73.It is also possible to set the item dimensions using a sample value:
74.Creating a JList Component
75.The items can be arbitrary objects. The toString() method of the objects is displayed in the list component.
76.Determining the Selected JRadioButton in a Button Group
77.A spinner that rolls from the end of a list to beginning
78.This program demonstrates the use of cell renderers in a list box
79.This program demonstrates a simple fixed list of stringsThis program demonstrates a simple fixed list of strings
80.This program demonstrates a list that dynamically computes list entriesThis program demonstrates a list that dynamically computes list entries