KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > contrib > javapro > JSortTable


1 /*
2 =====================================================================
3
4   JSortTable.java
5   
6   Created by Claude Duguay
7   Copyright (c) 2002
8   
9 =====================================================================
10 */

11
12 package contrib.javapro;
13
14 import java.awt.*;
15 import java.awt.event.*;
16 import java.util.*;
17 import javax.swing.*;
18 import javax.swing.event.*;
19 import javax.swing.table.*;
20
21 public class JSortTable extends JTable
22   implements MouseListener
23 {
24   protected int sortedColumnIndex = -1;
25   protected boolean sortedColumnAscending = true;
26   
27   public JSortTable(SortTableModel model)
28   {
29     super(model);
30     initSortHeader();
31   }
32
33   public JSortTable(SortTableModel model,
34     TableColumnModel colModel)
35   {
36     super(model, colModel);
37     initSortHeader();
38   }
39
40   public JSortTable(SortTableModel model,
41     TableColumnModel colModel,
42     ListSelectionModel selModel)
43   {
44     super(model, colModel, selModel);
45     initSortHeader();
46   }
47
48   protected void initSortHeader()
49   {
50     JTableHeader header = getTableHeader();
51     header.setDefaultRenderer(new SortHeaderRenderer());
52     header.addMouseListener(this);
53   }
54
55   public int getSortedColumnIndex()
56   {
57     return sortedColumnIndex;
58   }
59   
60   public boolean isSortedColumnAscending()
61   {
62     return sortedColumnAscending;
63   }
64   
65   public void mouseReleased(MouseEvent event)
66   {
67     TableColumnModel colModel = getColumnModel();
68     int index = colModel.getColumnIndexAtX(event.getX());
69     int modelIndex = colModel.getColumn(index).getModelIndex();
70     
71     SortTableModel model = (SortTableModel)getModel();
72     if (model.isSortable(modelIndex))
73     {
74       // toggle ascension, if already sorted
75
if (sortedColumnIndex == index)
76       {
77         sortedColumnAscending = !sortedColumnAscending;
78       }
79       sortedColumnIndex = index;
80     
81       model.sortColumn(modelIndex, sortedColumnAscending);
82     }
83   }
84   
85   public void mousePressed(MouseEvent event) {}
86   public void mouseClicked(MouseEvent event) {}
87   public void mouseEntered(MouseEvent event) {}
88   public void mouseExited(MouseEvent event) {}
89 }
90
91
Popular Tags