C-man said:
Hey, I am basically looking for the source code for a generic JTable that
implements sorting by handling a mouse click on the Table headers. Does
anybody know of a good java class that does that? Thanks
It is very simple. You want something like:
public class MyTable extends JTable
{
/** The number of clicks to initiate a column sort action. */
public static final int SortClicks = 1;
/**
* Sort the specified column. Sort the data model
* for the specified column index.
*
* @param theColumn The origin-0 column index.
*/
public abstract void sortColumn(int theColumn);
/**
* The MouseListener listens for mouse clicks on the
* JTableHeader for sorting columns.
*/
protected class ColumnClickListener
extends MouseAdapter
{
/**
* Receives control when the underlying visual component
* detects a mouse click (press and release) over it.
*/
public void mouseClicked(final MouseEvent mouseEvent)
{
final TableColumnModel columnModel;
final int xClick;
final int xView;
final int xModel;
columnModel = getColumnModel();
xClick = mouseEvent.getX(); // horizontal pixel
xView = columnModel.getColumnIndexAtX(xClick); // view index
xModel = convertColumnIndexToModel(xView); // model index
// if the user clicked on a valid column header,
// then sort all rows by that column.
if((0 <= xModel) && (SortClicks == mouseEvent.getClickCount()))
{
sortColumn(xModel);
}
}
}
// instance initializer: create and register the column header mouse
listener
{
final MouseListener mouseListener;
final JTableHeader jTableHeader;
mouseListener = new ColumnClickListener();
jTableHeader = getTableHeader();
jTableHeader.addMouseListener(mouseListener);
}
// everything else you need goes here, including constructors...
//...application specific stuff...
}