The EventTableModel and TableComparatorChooser

Now that we have our columns prepared, we can replace our JList in part one with a more sophisticated JTable. We simply replace the EventListModel with an EventTableModel, which takes our IssueTableFormat in its constructor. We use our sorted list as the source list for our new EventTableModel, which shows the issues sorted by event ID.

Although our table will be sorted by event ID, we would like our users to be able to choose a different sorting criteria by clicking on the column headers. For example, clicking on the "Type" header should sort our issues by type. Glazed Lists includes a utility class for just this purpose called TableComparatorChooser. The TableComparatorChooser is flexible and allows us to specify zero or more Comparators for each column. As the user clicks on a column's header, they cycle through the list of Comparators for that column. You must also specify whether it shall use simple single-column sorting or more powerful multiple-column sorting. The TableComparatorChooser automatically includes a Comparator for each column that sorts using the Comparable interface for that column's value. If your column's value is not Comparable, you must remove the default Comparator using TableComparatorChooser.getComparatorsForColumn(column).clear().

  /**
   * Display a frame for browsing issues.
   */
  public void display() {
    SortedList sortedIssues = new SortedList(issuesEventList, new IssueComparator());
    
    // create a panel with a table
    JPanel panel = new JPanel();
    panel.setLayout(new GridBagLayout());
    EventTableModel issuesTableModel = new EventTableModel(sortedIssues, new IssueTableFormat());
    JTable issuesJTable = new JTable(issuesTableModel);
    TableComparatorChooser tableSorter = new TableComparatorChooser(issuesJTable, sortedIssues, true);
    JScrollPane issuesTableScrollPane = new JScrollPane(issuesJTable);
    panel.add(issuesTableScrollPane, new GridBagConstraints(...));
    
    // create a frame with that panel
    JFrame frame = new JFrame("Issues");
    frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    frame.setSize(540, 380);
    frame.getContentPane().add(panel);
    frame.show();
  }