e937. setting column header tool tips in a jtable components.txt

来自「这里面包含了一百多个JAVA源文件」· 文本 代码 · 共 52 行

TXT
52
字号
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;
            }
        }
    }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?