Java Swing How to - Handle JTable column Change events








Question

We would like to know how to handle JTable column Change events.

Answer

 // w w  w  .  j  ava2 s . c o m


import javax.swing.JTable;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.TableColumnModelEvent;
import javax.swing.event.TableColumnModelListener;

public class Main {
  public static void main(String[] argv) throws Exception {
    JTable table = new JTable();
    table.getColumnModel().addColumnModelListener(new MyTableColumnModelListener(table));
  }
}

class MyTableColumnModelListener implements TableColumnModelListener {
  JTable table;
  public MyTableColumnModelListener(JTable table) {
    this.table = table;
  }

  public void columnAdded(TableColumnModelEvent e) {
    int fromIndex = e.getFromIndex();
    int toIndex = e.getToIndex();
    System.out.println(fromIndex);
    System.out.println(toIndex);
  }

  public void columnRemoved(TableColumnModelEvent e) {
    int fromIndex = e.getFromIndex();
    int toIndex = e.getToIndex();
    System.out.println(fromIndex);
    System.out.println(toIndex);
  }

  public void columnMoved(TableColumnModelEvent e) {
    int fromIndex = e.getFromIndex();
    int toIndex = e.getToIndex();
    System.out.println(fromIndex);
    System.out.println(toIndex);
  }

  public void columnMarginChanged(ChangeEvent e) {
    System.out.println(e);
    
  }

  public void columnSelectionChanged(ListSelectionEvent e) {
    System.out.println(e);
  }
}