Tooltips for Individual Items in a JList

This Java tutorial shows how to display individual tooltips for items in a JList.

This tutorial will extend our previous tutorial of creating a font list box. In that tutorial, we showed how to create a new list cell renderer to display the font name in that font. One problem with this is the font name may not be readable which is common with symbol fonts. In this tutorial, we will show the actual font name for each item in the tooltip. Below is a screenshot of the tooltip showing for each item in the list box:



In order to display tooltips for individual items in a list box, we need to override the getToolTipText() method in JList.

public String getToolTipText(MouseEvent event)

In this method, the first thing we need to determine is where the mouse pointer is located. Based on the mouse location, we can determine which item in the list box the mouse is over.
//Get the mouse location
Point point = event.getPoint();

//Get the item in the list box at the mouse location
int index = this.locationToIndex(point);

Once we have determined the index of the list box item the mouse is over, we can get and return the value of the item from the JList model.
//Get the value of the item in the list
return (String) this.getModel().getElementAt(index);

Below is the complete code for the list box. NOTE: The FontCellRender source code can be found here.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class FontListBox extends JList
{
public FontListBox()
{
//Construct a JList with the font names
super(GraphicsEnvironment.getLocalGraphicsEnvironment().
getAvailableFontFamilyNames());

//Set the cell render
this.setCellRenderer(new FontCellRenderer());
}

public String getToolTipText(MouseEvent event)
{
//Get the mouse location
Point point = event.getPoint();

//Get the item in the list box at the mouse location
int index = this.locationToIndex(point);

/Get the value of the item in the list
return (String) this.getModel().getElementAt(index);
}
}


1 comments:

Tom said...

It seems that when the list cell renderer has a tooltip, then that tooltip is shown instead of the JList's:

lJList.setCellRenderer(new DefaultListCellRenderer()
{
public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus)
{
JLabel lJLabel = (JLabel)super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
lJLabel.setToolTipText("cell with index " + index);
return lJLabel;
}
});

Post a Comment