Google Tag Manager

2008/09/16

JTable Tri-state row sorting (cycle through ascending descending unsorted)

Code

TableModel model = new DefaultTableModel();
JTable table = new JTable(model);
//sort toggles ascending descending unsorted (like TableSorter.java)
TableRowSorter< TableModel > sorter = new TableRowSorter< TableModel >(model) {
  @Override
  public void toggleSortOrder(int column) {
    if(column >= 0 && column < getModelWrapper().getColumnCount() && isSortable(column)) {
      List< SortKey > keys = new ArrayList< SortKey >(getSortKeys());
      if(!keys.isEmpty()) {
        SortKey sortKey = keys.get(0);
        if(sortKey.getColumn()==column && sortKey.getSortOrder()==SortOrder.DESCENDING) {
          setSortKeys(null);
          return;
        }
      }
    }
    super.toggleSortOrder(column);
  }
};
table.setRowSorter(sorter);

References

2008/09/11

Double-click on each tab and change its name like Excel

Code

private Component tabComponent = null;
private int editing_idx = -1;
private int len = -1;
private Dimension dim;
private void startEditing() {
  //System.out.println("start");
  editing_idx  = tabbedPane.getSelectedIndex();
  tabComponent = tabbedPane.getTabComponentAt(editing_idx);
  tabbedPane.setTabComponentAt(editing_idx, editor);
  editor.setVisible(true);
  editor.setText(tabbedPane.getTitleAt(editing_idx));
  editor.selectAll();
  editor.requestFocusInWindow();
  len = editor.getText().length();
  dim = editor.getPreferredSize();
  editor.setMinimumSize(dim);
}
private void cancelEditing() {
  //System.out.println("cancel");
  if(editing_idx>=0) {
    tabbedPane.setTabComponentAt(editing_idx, tabComponent);
    editor.setVisible(false);
    editing_idx = -1;
    len = -1;
    tabComponent = null;
    editor.setPreferredSize(null);
  }
}
private void renameTabTitle() {
  //System.out.println("rename");
  String title = editor.getText().trim();
  if(editing_idx>=0 && !title.isEmpty()) {
    tabbedPane.setTitleAt(editing_idx, title);
  }
  cancelEditing();
}

References