package edu.princeton.swing; import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.border.*; /** * PWrappedList is a JList which word-wraps its cells. * * @author btsang * @version 7.1 */ public class PWrappedList extends PList { /** * Constructs a new PWrappedList. */ public PWrappedList() { super(); initList(); } /** * Constructs a new PWrappedList. */ public PWrappedList(ListModel dataModel) { super(dataModel); initList(); } /** * Constructs a new PWrappedList. */ public PWrappedList(Object[] listData) { super(listData); initList(); } /** * Constructs a new PWrappedList. */ public PWrappedList(java.util.Vector listData) { super(listData); initList(); } /** * Called by the constructors to init the PWrappedList properly. */ private void initList() { setCellRenderer(new CellRenderer()); enableEvents(AWTEvent.COMPONENT_EVENT_MASK); } /** * We override this function to enable proper word-wrapping in a JScrollPane. */ public boolean getScrollableTracksViewportWidth() { return true; } /** * Capture resize events. */ protected void processComponentEvent(ComponentEvent e) { super.processComponentEvent(e); if (e.getID() == ComponentEvent.COMPONENT_RESIZED) setFixedCellWidth(getWidth()); } /** * CellRenderer is the class which renders PWrappedList cells. * * @author btsang * @version 7.1 */ protected static class CellRenderer extends JTextArea implements ListCellRenderer { private static final Border EMPTY_BORDER = new EmptyBorder(1, 1, 1, 1); private Dimension preferredSize = new Dimension(); /** * Instantiates a CellRenderer. */ protected CellRenderer() { super(); setLineWrap(true); setWrapStyleWord(true); } /** * Overridden to get wrapping to work. * * @see javax.swing.DefaultListCellRenderer */ public Dimension getPreferredSize() { return preferredSize; } /** * Implement ListCellRenderer. */ public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) { if (list instanceof PList) { if (cellHasFocus) setBorder(((PList)list).getFocusedCellBorder()); else setBorder(((PList)list).getUnfocusedCellBorder()); } else { if (cellHasFocus) setBorder(UIManager.getBorder("List.focusCellHighlightBorder")); else setBorder(EMPTY_BORDER); } if (isSelected) { setBackground(list.getSelectionBackground()); setForeground(list.getSelectionForeground()); } else { setBackground(list.getBackground()); setForeground(list.getForeground()); } setEnabled(list.isEnabled()); setFont(list.getFont()); setText(value.toString()); setBounds(0, 0, list.getWidth(), 100); Dimension wrappedSize = super.getPreferredSize(); preferredSize.width = wrappedSize.width; preferredSize.height = wrappedSize.height; return this; } } }