Java Tutorial/Swing/JList Renderer — различия между версиями

Материал из Java эксперт
Перейти к: навигация, поиск
м (1 версия)
 
(нет различий)

Текущая версия на 15:31, 31 мая 2010

Add your own ListCellRenderer

For performance reasons, do not create the renderer in the getListCellRendererComponent() method.



import java.awt.BorderLayout;
import java.awt.ruponent;
import javax.swing.DefaultListCellRenderer;
import javax.swing.DefaultListModel;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JScrollPane;
import javax.swing.ListCellRenderer;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.border.TitledBorder;
public class SizingSamples {
  public static void main(String args[]) {
    JFrame frame = new JFrame("Sizing Samples");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    DefaultListModel model = new DefaultListModel();
    model.ensureCapacity(100);
    for (int i = 0; i < 100; i++) {
      model.addElement(Integer.toString(i));
    }
    JList jlist2 = new JList(model);
    ListCellRenderer renderer = new FocusedTitleListCellRenderer();
    jlist2.setCellRenderer(renderer);
    JScrollPane scrollPane2 = new JScrollPane(jlist2);
    frame.add(scrollPane2, BorderLayout.CENTER);
    frame.setSize(300, 350);
    frame.setVisible(true);
    jlist2.ensureIndexIsVisible(50);
  }
}
class FocusedTitleListCellRenderer implements ListCellRenderer {
  protected static Border noFocusBorder = new EmptyBorder(15, 1, 1, 1);
  protected static TitledBorder focusBorder = new TitledBorder(LineBorder.createGrayLineBorder(),
      "title");
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);
    renderer.setBorder(cellHasFocus ? focusBorder : noFocusBorder);
    return renderer;
  }
}





Change the layout orientation so that its items are displayed top-to-bottom and left-to-right.

import javax.swing.JList;
import javax.swing.JScrollPane;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    JScrollPane scrollingList = new JScrollPane(list);
    // Change orientation to top-to-bottom, left-to-right layout
    list.setLayoutOrientation(JList.VERTICAL_WRAP);
  }
}





Creating a Complex ListCellRenderer: font, icon and color

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.ruponent;
import java.awt.Font;
import java.awt.Graphics;
import javax.swing.DefaultListCellRenderer;
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 ComplexCellRenderer implements ListCellRenderer {
  protected DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
  public Component getListCellRendererComponent(JList list, Object value, int index,
      boolean isSelected, boolean cellHasFocus) {
    Font theFont = null;
    Color theForeground = null;
    Icon theIcon = null;
    String theText = null;
    JLabel renderer = (JLabel) defaultRenderer.getListCellRendererComponent(list, value, index,
        isSelected, cellHasFocus);
    if (value instanceof Object[]) {
      Object values[] = (Object[]) value;
      theFont = (Font) values[0];
      theForeground = (Color) values[1];
      theIcon = (Icon) values[2];
      theText = (String) values[3];
    } else {
      theFont = list.getFont();
      theForeground = list.getForeground();
      theText = "";
    }
    if (!isSelected) {
      renderer.setForeground(theForeground);
    }
    if (theIcon != null) {
      renderer.setIcon(theIcon);
    }
    renderer.setText(theText);
    renderer.setFont(theFont);
    return renderer;
  }
}
public class ComplexRenderingSample {
  public static void main(String args[]) {
    Object elements[][] = {
        { new Font("Helvetica", Font.PLAIN, 20), Color.RED, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.BOLD, 14), Color.BLUE, new MyIcon(), "A" },
        { new Font("Courier", Font.ITALIC, 18), Color.GREEN, new MyIcon(), "A" },
        { new Font("Helvetica", Font.BOLD | Font.ITALIC, 12), Color.GRAY, new MyIcon(), "A" },
        { new Font("TimesRoman", Font.PLAIN, 32), Color.PINK, new MyIcon(), "A" },
        { new Font("Courier", Font.BOLD, 16), Color.YELLOW, new MyIcon(), "A" },
        { new Font("Helvetica", Font.ITALIC, 8), Color.DARK_GRAY, new MyIcon(), "A" } };
    JFrame frame = new JFrame("Complex Renderer");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    JList jlist = new JList(elements);
    ListCellRenderer renderer = new ComplexCellRenderer();
    jlist.setCellRenderer(renderer);
    JScrollPane scrollPane = new JScrollPane(jlist);
    frame.add(scrollPane, BorderLayout.CENTER);
    frame.setSize(300, 200);
    frame.setVisible(true);
  }
}
class MyIcon implements Icon {
  public MyIcon() {
  }
  public int getIconHeight() {
    return 20;
  }
  public int getIconWidth() {
    return 20;
  }
  public void paintIcon(Component c, Graphics g, int x, int y) {
    g.setColor(Color.RED);
    g.drawRect(0, 0, 25, 25);
  }
}





Install List cell renderer

import java.awt.ruponent;
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);
  }
}





Rendering JList Elements

  1. Every JList has an installed cell renderer that draws every cell.
  2. A class that implements the ListCellRenderer interface provides this renderer.
  3. When it"s time to draw each cell, the interface"s sole method is called.
  4. The JList has an installed renderer.
  5. The returned renderer provides the specific rendering for that one cell of the JList.
  6. The JList uses the rendering to draw the element, and then gets the next renderer.



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





Set the item dimensions using a sample value

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    String protoCellValue = "My Sample Item Value";
    list.setPrototypeCellValue(protoCellValue);
  }
}





Setting the Dimensions of an Item in a JList Component

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    String[] items = { "A", "B", "C", "D" };
    JList list = new JList(items);
    // Set the item width
    int cellWidth = 200;
    list.setFixedCellWidth(cellWidth);
    // Set the item height
    int cellHeight = 18;
    list.setFixedCellHeight(cellHeight);
  }
}





The items can be arbitrary objects. The toString() method of the objects is displayed in the list component.

import javax.swing.JList;
public class Main {
  public static void main(String[] argv) throws Exception {
    Object[] items2 = { new Integer(123), new java.util.Date() };
    JList list = new JList(items2);
    
    
  }
}