JSortedTable¶
A JSortedTable works like a classic JTable, but allows the user to sort each column.
The JTable class provided by Swing, does not allow to sort columns by clicking on the column header. The jshred library offers methods to add this feature.
The SortableTableModelProxy used here, is a connection layer between the table and the classic table model. Sorting is only performed in this proxy. The table model itself is unaffected.
/*
* Examples for the jshred library
*
* Copyright (c) 2004 Richard "Shred" Körber
* http://www.shredzone.net/go/jshred
*
* This example is free software. Use and modify it at will.
*/
import net.shredzone.jshred.swing.*;
import javax.swing.*;
import javax.swing.table.*;
/**
* This is an example of a sortable Table using {@link JSortedTable}
* and the {@link SortableTableModelProxy}. As you will see, this is
* pretty easy.
*/
public class SortedTable extends JFrame {
/**
* Create a new SortedTable example.
*/
public SortedTable() {
// An array of all the column titles
Object[] columns = new Object[] {"Nr.", "Name", "Phone", "City"};
// An array of all the cell contents
Object[][] data = new Object[][] {
new Object[] {new Integer(1), "Peter" , "555-1234", "Berlin" },
new Object[] {new Integer(2), "Mary" , "555-9942", "New York"},
new Object[] {new Integer(3), "William", "444-1357", "London" },
new Object[] {new Integer(4), "Alex" , "555-2222", "Sydney" },
};
// Create a TableModel
// The TableModel will contain the data from the arrays above.
TableModel model = new DefaultTableModel(data, columns);
// Create the SortableTableModelProxy
// The proxy will take care for sorting the rows and mapping
// the sort order to the TableModel. Note that the TableModel
// will not be changed in any way if a column is sorted.
SortableTableModelProxy proxy = new SortableTableModelProxy(model);
// Create the JSortedTable
// The SortableTableModelProxy is provided as model to the
// JSortedTable. Anyhow you could provide any model here
// that implements the SortableTableModel interface.
JSortedTable table = new JSortedTable(proxy);
// Spread the columns
// Each table column will now only consume as little space as
// required to show all the column content. This is just for a
// pretty table, but not required for sorting the columns.
table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
SwingUtils.spreadColumns(table);
// Add the table to the frame
getContentPane().add(new JScrollPane(table));
}
/**
* Start this demo as an application.
*
* @param args Shell arguments
*/
public static void main(String[] args) {
SortedTable demo = new SortedTable();
demo.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
demo.pack();
demo.show();
}
}