Subpages: 1. JList API overview
2. Basic JList example
3. Custom rendering
4. Processing keyboard input and searching
5. List of check boxes
10.3 Custom rendering
In this section we'll add the ability to allign Strings containing tab separators into a table-like arrangement. We want each tab character to shift all text to its right, to a specified location instead of being rendered as the square symbol we saw above. These locations should be determined uniformly for all elements of the list to form columns that line up correctly.
Note that this example works well with proportional fonts as well as with fixed width fonts (i.e. it doesn't matter what font we use because alignment is not designed to be font-dependent). This makes JList a powerful but simple component, which can be used in place of JTable in simple cases such as the example presented here (where the involvement of JTable would create unnecessary overhead).
To accomplish the desired rendering we construct a custom renderer, TabListCellRenderer, which exposes accessor methods to specify and retreive tab positions based on the index of a tab character in a String being rendered:
getDefaultTab()/setDefaultTab(int): manages the default tab size (defaults to 50). In case a position is not specified for a given tab index, we use a default size to determine how far to offset a portion of text.
getTabs()/setTabs(int[]): manages an array of positions based on the index of a tab character in a String being rendered. These positions used in rendering each element in the list to provide conisitent alignment.

Figure 10.2 Custom ListCellRenderer to display tab-separated Strings in a table-like fashion.
<<file figure10-2.gif>>
The Code: StatesList.java
see \Chapter10\2
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
public class StatesList extends JFrame
{
protected JList m_statesList;
public StatesList() {
// Unchanged code from section 10.2
m_statesList = new JList(states);
TabListCellRenderer renderer = new TabListCellRenderer();
renderer.setTabs(new int[] {50, 200, 300});
m_statesList.setCellRenderer(renderer);
// Unchanged code from section 10.2
}
}
class TabListCellRenderer extends JLabel
implements ListCellRenderer
{
protected static Border m_noFocusBorder;
protected FontMetrics m_fm = null;
protected Insets m_insets = new Insets(0, 0, 0, 0);
protected int m_defaultTab = 50;
protected int[] m_tabs = null;
public TabListCellRenderer() {
super();
m_noFocusBorder = new EmptyBorder(1, 1, 1, 1);
setOpaque(true);
setBorder(m_noFocusBorder);
}
public Component getListCellRendererComponent(JList list,
Object value, int index, boolean isSelected, boolean cellHasFocus)
{
setText(value.toString());
setBackground(isSelected ? list.getSelectionBackground() :
list.getBackground());
setForeground(isSelected ? list.getSelectionForeground() :
list.getForeground());
setFont(list.getFont());
setBorder((cellHasFocus) ? UIManager.getBorder(
"List.focusCellHighlightBorder") : m_noFocusBorder);
return this;
}
public void setDefaultTab(int defaultTab) {
m_defaultTab = defaultTab;
}
public int getDefaultTab() { return m_defaultTab; }
public void setTabs(int[] tabs) { m_tabs = tabs; }
public int[] getTabs() { return m_tabs; }
public int getTab(int index) {
if (m_tabs == null)
return m_defaultTab*index;
int len = m_tabs.length;
if (index>=0 && index<len)
return m_tabs[index];
return m_tabs[len-1] + m_defaultTab*(index-len+1);
}
public void paint(Graphics g) {
m_fm = g.getFontMetrics();
g.setColor(getBackground());
g.fillRect(0, 0, getWidth(), getHeight());
getBorder().paintBorder(this, g, 0, 0, getWidth(), getHeight());
g.setColor(getForeground());
g.setFont(getFont());
m_insets = getInsets();
int x = m_insets.left;
int y = m_insets.top + m_fm.getAscent();
StringTokenizer st = new StringTokenizer(getText(), "\t");
while (st.hasMoreTokens()) {
String sNext = st.nextToken();
g.drawString(sNext, x, y);
x += m_fm.StringWidth(sNext);
if (!st.hasMoreTokens())
break;
int index = 0;
while (x >= getTab(index))
index++;
x = getTab(index);
}
}
}
Understanding the Code
Class StatesList
Minor changes have been made to this class (compared to StatesList from the previous section). We create an instance of our custom TabListCellRenderer, pass it an array of positions and set it as the renderer for our JList component.
Class TabListCellRenderer
Class TabListCellRenderer extends JLabel and implements the ListCellRenderer interface to be used as our custom renderer.
Class variable:
Border m_noFocusBorder: border to be used when a list item has no focus.
Instance variables:
FontMetrics m_fm: used in calculating text positioning when drawing.
Insets m_insets: insets of the cell being rendered.
int m_defaultTab: default tab size.
int[] m_tabs: an array of positions based on tab index in a String being rendered.
The constructor creates assigns text, sets its opaque property to true (to render the component's area with the specified background), and sets the border to m_noFocusBorder.
The getListCellRendererComponent() method is required when implementing ListCellRenderer, and is called each time a cell is about to be rendered. It takes five parameters:
JList list: reference to the list instance.
Object value: data object to be painted by the renderer.
int index: index of the item in the list.
boolean isSelected: true if the cell is currently selected.
boolean cellHasFocus: true if the cell currently has the focus.
Our implementation of this method assigns new text, sets the background and foreground (depending on whether or not the cell is selected), sets the font to that taken from the parent list component, and sets the border according to whether or not the cell has input focus.
Four additional methods provide set/get support for the m_defaultTab and m_tabs variables, and do not require detailed explanation beyond the code listing. Now let's take a close look at the getTab() method which calculates and returns the position for a given tab index. If no tab array, m_tabs, is set, this method returns the m_defaultTab distance (defaults to 50) multiplied by the given tab index. If the m_tabs array is not null and the tab index is less than it's length, the proper value from that array is returned. Otherwise, if the tab index is greater than the array's length, we have no choice but to use the default tab size again.
Since the JLabel component does not render tab characters properly, we do not benefit a lot from its inheritance and implement the paint() method to draw tabbed Strings ourselves.
Note: Because this is a very simple component that we do not plan to enhance with custom UI functionality, overriding paint() is acceptable.
First, our paint() method requests a reference to the FontMetrics instance for the given Graphics. Then we fill the component's rectangle with the background color (which is set in the getListCellRendererComponent() method depending on whether or not the cell is selected, see above), and paint the component's border.
Note: Alternatively we could use the drawTabbedText() method from the javax.swing.text.Utilities class to draw tabbed text. However, this requires us to implement the TabExpander interface. In our case it's easier to draw text directly without using that utility. As an interesting exercise you can modify the code from this example to use drawTabbedText() method. We will discuss working with tabs more in chapter 19.
In the next step we prepare to draw the tabbed String. We set the foreground color, font, and determine the initial x and y positions for drawing the text, taking into account the component's insets.
Reminder: To draw text in Java you need to use a baseline y-coordinate. This is why the getAscent() value is added to the y position. The getAscent() method returns the distance from the font's baseline to the top of most alphanumeric characters. See chapter 2 for more information on drawing text and Java 2 FontMetrics caveats.
We then use a StringTokenizer to parse the String and extract the portions separated by tabs. Each portion is drawn with the drawString() method, and the x-coordinate is adjusted to the length of the text. We cycle through this process, positioning each portion of text by calling the getTab() method, until no more tabs are found.
Running the Code
Figure 10.2 shows StatesList displaying an array of tab-separated Strings. Note that the tab symbols are not drawn directly, but form consistently aligned columns inside the list.
UI Guideline : Improved Balance
With the tab character now being displayed correctly, the list box now has much better balance. The available area for Capital City is still very large and as designer you may wish to consider reduing this, thus reducing the excessive white space to the right hand side. Such a decision would normally be made after the List Box is seen in situation and necessary alignment and overall panel balance is taken into consideration.



RSS feed Java FAQ News