java - 如何在工具提示中使用jTable的隐藏列数据

标签 java swing jtable

我正在尝试将隐藏列的数据显示为工具提示。使用以下代码可以完美隐藏:

    JTable table = new JTable(model){
        //Implement table cell tool tips.          
        public String getToolTipText(MouseEvent e) {
            String tip = null;
            java.awt.Point p = e.getPoint();
            int rowIndex = rowAtPoint(p);
            int colIndex = columnAtPoint(p);
            int realColumnIndex = convertColumnIndexToModel(colIndex);

            try {
                tip = getValueAt(rowIndex, 8).toString();
            } catch (RuntimeException e1) {
                //catch null pointer exception if mouse is over an empty line
            }

            return tip;
        }
    };

    TableColumnModel tcm = table.getColumnModel();

    TableColumn tc;
    for(int i = 1; i <= 7; i++){
        tc = tcm.getColumn(8);
        tcm.removeColumn(tc);
    }

但是工具提示没有显示隐藏列的数据(getValue 函数没有返回值)。那么隐藏列也会删除数据吗?

最佳答案

  1. 您不需要 for 循环,因为您不使用 i 变量 ;-)
  2. JTable 上的removeColumn不会从模型中删除数据,如 javadoc 中所述

    Removes aColumn from this JTable's array of columns. Note: this method does not remove the column of data from the model; it just removes the TableColumn that was responsible for displaying it.

    javadoc 中没有提及 TableColumnModel 上的相同方法,但我认为它的工作方式相同,但您始终可以尝试在 JTable 上调用它

  3. 代码中的真正问题是 getValueAt 的使用,它使用表的行和列索引,而不是模型的索引

    Note: The column is specified in the table view's display order, and not in the TableModel's column order. This is an important distinction because as the user rearranges the columns in the table, the column at a given index in the view will change. Meanwhile the user's actions never affect the model's column ordering.

    并且由于您删除了该列,因此该列根本不存在于该表中。调用getValue模型上的方法,不要忘记转换 row index

关于java - 如何在工具提示中使用jTable的隐藏列数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9970393/

相关文章:

java - JTable 中的多行选择

Java JTable 使用 TableCellRenderer 排序

java - JTable 中的 JFileChooser

java - Spring Boot 2.5.1 服务不会在 System.exit(0) 上停止

java - 绘制图形节点的坐标算法

Java邮件 : Concurrent read-only processing of emails and EXPUNGE issues

java - 将文件从 JFileChooser 复制到新目录

java - 动态创建时 Jlabel 数组在 netbeans 中不可见

java - 如何通过 java 中的 http 响应 header 防止 Internet Explorer 9 中的缓存?

java - 将相同的按钮数组添加到两个 JFrame