javajtablecolumn-width

How to get column width of Jtable after a user changes it


I would like to know how to get the column width after a user changes it so that i may save it off.

after messing around i came up with this method but it's not perfect. if the user doesn't actually select a column by clicking in a row of the column, the selected column is -1 thus throws an error so i prevented that with an if statement.

the next issue is, if i select a column then change the width, it works and prints out the width as i change the column, but if i selected say column 3 but then proceed to change column 2 width without selecting in row in that column 2, it will continue to spit out the width of column 3 as i change column 2. so its working as expected with a select method, but there has to be a better way to get the width of the column i'm changing.

any ideas?

jt.getColumnModel().addColumnModelListener(new TableColumnModelListener() {

        public void columnAdded(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnRemoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMoved(TableColumnModelEvent e) {
            // TODO Auto-generated method stub

        }

        public void columnMarginChanged(ChangeEvent e) {
            int col = jt.getSelectedColumn();
            if (col >= 0) {
                TableColumn tc = jt.getColumnModel().getColumn(col);
                System.out.println(tc.getWidth());
            }
        }

        public void columnSelectionChanged(ListSelectionEvent e) {
            // TODO Auto-generated method stub

        }

    });

Solution

  • I managed to find a solution a while back, but forgot to share. I am storing all the column widths every time the mouse is released from resizing on the table header.

    jt.getTableHeader().addMouseListener( new MouseAdapter() {
            
            public void mouseReleased(MouseEvent arg0){
                for(int i=0;i<jt.getColumnModel().getColumnCount();i++ ) {
                    TableColumn column = jt.getColumnModel().getColumn(i);
                    int tableColWidth = column.getWidth();
                    String colHeader = (String) column.getHeaderValue();
                    
                    //Store the column Header with the column width
                }
            }
        });