How to set a tooltip text for each item of a JList in Java?

AWTJavaObject Oriented ProgrammingProgrammingSwing

A JList is a subclass of JComponent class and it can be used to display a list of objects that allows the user to select one or more items. A JList can generate a ListSelectiionListener interface and need to implement the abstract method valueChanged(). A JToolTip class is used to display a text or a tip of the component, we can set a tooltip text for each item of a list by implementing the getToolTipText() method of JToolTip class.

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.util.*;
public class JListTooltipTest extends JFrame {
   private Vector vector;
   public JListTooltipTest() {
      setTitle("JListTooltip Test");
      setLayout(new FlowLayout());
      vector = new Vector();
      for (int i=1; i < 15; i++) {
         vector.addElement("Item #" + i);
      }
      final JList list = new JList(vector) {
         public String getToolTipText(MouseEvent me) {
            int index = locationToIndex(me.getPoint());
            if (index > -1) {
               String item = (String) getModel().getElementAt(index);
               return "Tooltip for " + item;
            }
            return null;
         }
      };
      list.setToolTipText("");
      add(new JScrollPane(list));
      setSize(375, 250);
      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      setLocationRelativeTo(null);
      setVisible(true);
   }
   public static void main(String[] args) {
      new JListTooltipTest();
   }
}

Output

raja
Published on 19-Jul-2019 17:29:06
Advertisements