import java.awt.*; import java.awt.event.*; import javax.swing.*; import javax.swing.event.*; import javax.swing.table.*; public class ColumnExample extends JFrame implements TableColumnModelListener { JTable jt; public ColumnExample() { super("Abstract Model JTable Test"); //Create the table and give the data as a two-dimensional //String array and the column headers as a one-dimensional String array. jt = new JTable(new String[][] { {"This", "is", "cell 13"}, {"a", "Test", "cell 23" }, {"cell 31", "cell 32", "cell 33" } }, new String[] {"BBBB", "CCCC", "AAAAA"}); //Make the table use our default column modell. jt.setColumnModel(new SortingColumnModel()); jt.createDefaultColumnsFromModel(); //Listen for events from the column model. jt.getColumnModel().addColumnModelListener(this); //Place the table in a JScrollPane and display it. JScrollPane jsp = new JScrollPane(jt); getContentPane().add(jsp, BorderLayout.CENTER); addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); setSize(300, 200); setVisible(true); } public void columnAdded(TableColumnModelEvent e) { System.out.println("column added"); } public void columnMarginChanged(ChangeEvent e) { System.out.println("column margin changed"); } public void columnMoved(TableColumnModelEvent e) { System.out.println("column moved"); } public void columnRemoved(TableColumnModelEvent e) { System.out.println("column removed"); } public void columnSelectionChanged(ListSelectionEvent e) { System.out.println("selection: " + e.getFirstIndex() + " - " + e.getLastIndex() + " valueIsAdjusting: " + e.getValueIsAdjusting()); int[] sel = jt.getColumnModel().getSelectedColumns(); for (int i = 0; i < sel.length; i++) System.out.println("column " + sel[i] + " selected"); System.out.println(); } public static void main(String args[]) { new ColumnExample(); } } /** A simple extension of the DefaultTableColumnModel class that sorts incoming columns.*/ class SortingColumnModel extends DefaultTableColumnModel { public SortingColumnModel() { setColumnMargin(20); } public void addColumn(TableColumn tc) { //Override addColumn to make it sort the columns alphabetically. //First add the columns to the table. super.addColumn(tc); //Get the sorted index. int sortedIndex = sortedIndexOf(tc); //The TableColumn property modelIndex has nothing to do with //the apperance on the screen. It is just the columns index //in the column model list of columns. //The method moveColumn actually moves to column on the screen. moveColumn(tc.getModelIndex(), sortedIndex); } protected int sortedIndexOf(TableColumn tc) { //This method i just a simple sort algorithm. // just do a linear search for now int stop = getColumnCount(); //Sort by column header. String name = tc.getHeaderValue().toString(); //The sort algorithm. for (int i = 0; i < stop; i++) { if (name.compareTo(getColumn(i).getHeaderValue().toString()) <= 0) { return i; } } return stop; } }