Sebastian Zeki
Sebastian Zeki

Reputation: 6874

How to extract named column from tablemodel in java swing

I have a table that shows the results of user defined queries in a swing project. I want to allow the user to extract the data from a particular names column, if present. At the moment I can select the data from a column when I click the column but I don't know how to do the same thing from a button so that only a particular column's data (the column is called HNum) is obtainable. The code I have so far is as follows. If this is impossible I could always try to make sure that HNum is the first column but I need something cleaner I think.

btnCompare.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
        Object[] data_L = columnToArray(table,table.getSelectedColumn());
    }
}


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);
}

Upvotes: 0

Views: 48

Answers (1)

Sylvain Goubaud
Sylvain Goubaud

Reputation: 88

Do you tried to use a TableColumnModel ? You can define all the treatment you need like a getColumnName{}

https://docs.oracle.com/javase/7/docs/api/javax/swing/table/TableColumnModel.html

edit :

an example http://www.java2s.com/Tutorial/Java/0240__Swing/ExtendingAbstractTableModel.htm

Upvotes: 2

Related Questions