The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > javax.swing.table  [62 examples] > Tool Tips  [2 examples]

e937. Setting Column Header Tool Tips in a JTable Components

To display a tool tip for a column header, install a mouse motion listener on the header component and change its tool tip based on which column header is under the cursor.
    int rows = 10;
    int cols = 5;
    JTable table = new JTable(rows, cols);
    JTableHeader header = table.getTableHeader();
    
    ColumnHeaderToolTips tips = new ColumnHeaderToolTips();
    
    // Assign a tooltip for each of the columns
    for (int c=0; c<table.getColumnCount(); c++) {
        TableColumn col = table.getColumnModel().getColumn(c);
        tips.setToolTip(col, "Col "+c);
    }
    header.addMouseMotionListener(tips);
    
    public class ColumnHeaderToolTips extends MouseMotionAdapter {
        // Current column whose tooltip is being displayed.
        // This variable is used to minimize the calls to setToolTipText().
        TableColumn curCol;
    
        // Maps TableColumn objects to tooltips
        Map tips = new HashMap();
    
        // If tooltip is null, removes any tooltip text.
        public void setToolTip(TableColumn col, String tooltip) {
            if (tooltip == null) {
                tips.remove(col);
            } else {
                tips.put(col, tooltip);
            }
        }
    
        public void mouseMoved(MouseEvent evt) {
            TableColumn col = null;
            JTableHeader header = (JTableHeader)evt.getSource();
            JTable table = header.getTable();
            TableColumnModel colModel = table.getColumnModel();
            int vColIndex = colModel.getColumnIndexAtX(evt.getX());
    
            // Return if not clicked on any column header
            if (vColIndex >= 0) {
                col = colModel.getColumn(vColIndex);
            }
    
            if (col != curCol) {
                header.setToolTipText((String)tips.get(col));
                curCol = col;
            }
        }
    }

 Related Examples
e938. Setting Tool Tips on Cells in a JTable Component

See also: Cells    Column Heads    Columns    Editing    Events    Layout    Rows    Scrolling    Selection    Sorting    Table Model   


© 2002 Addison-Wesley.