Java:代码示例,用于提供所选列的摘要统计信息

时间:2012-04-07 18:56:48

标签: java jtable jtableheader

我正在编写一个程序,对从csv文件或数据库导入的数据进行一些统计分析。我可以将数据加载到jTable并显示,但我正在努力进行下一步。

我希望能够点击列标题,并在jTable一侧的面板中的标签中显示列内容的摘要统计信息(参见图片)。

enter image description here

有人可以建议查看类似项目的方法或示例代码吗?任何帮助将不胜感激。

编辑: 我在netbeans中这样做。通常在netbeans中,我只需在设计模式下单击组件,然后通过右键单击添加一个监听器,然后填写源选项卡上的代码。但是,我不确定如何在设计选项卡中看不到表或标题时添加监听器。

3 个答案:

答案 0 :(得分:1)

JTable table = ...
TableColumnModel columnModel = table.getColumnModel();
columnModel.add(new TableColumnModelListener() {
    // other methods
    public void columnSelectionChanged(ListSelectionEvent e) {
        // user selected or deselected a column, change summary as necessary
    }
}

TableColumnModel reference

答案 1 :(得分:1)

对于听众部分,我使用了以下信息:

Listening for Clicks on a Column Header in a JTable Component

答案 2 :(得分:1)

因此,问题分为两部分: -

  1. 选择列时要执行的事件处理程序。

  2. 获取摘要的代码。

  3. 对于第一个(事件处理程序),您可以参考@ Jeffrey的答案。对于摘要部分,您可以编写如下方法:

    /* Method to return values in a column of JTable as an array */
    
    public Object[] columnToArray(JTable table, int columnIndex){
        // get the row count
        int rowCount = table.getModel().getRowCount();
        // declare the array
        Object [] data = new Object[rowCount];
        // fetch the data
        for(int i = 0; i < rowCount; i++){
            data[i] = table.getModel().getValueAt(i, columnIndex);        
        }
        return(data);
    }
    

    从事件处理程序内部调用此方法,如下所示:

    public void columnSelectionChanged(ListSelectionEvent e) {
        //assuming single column is selected
        Object[] data = columnToArray(table,table.getSelectedColumn());
       /* type cast if using specific data type. for eg:
        * Integer[] data = (Integer[]) columnToArray(table,table.getSelectedColumn());
        */
        // other functions to create the summary
    }
    

    对象数组可用于计算所需的摘要,例如查找范围,标准偏差等。这些应该是微不足道的。记得在调用方法中对Object数组进行类型转换。