2013-08-27 63 views
0

我知道,通過使用JTable,當我們點擊列標題時列被排序,但我想要的是,當我右鍵單擊列名稱時,應該顯示函數名稱「sort」。有什麼建議嗎?如何在jTable中添加一個對列進行排序的函數?

+0

爲什麼讓你的用戶很難? – kleopatra

+0

@kleopatra實際上這是客戶端所要求的,因爲他不希望列單擊列標題時不小心得到排序。 :) – John11

回答

2

如果我理解正確的話,你想通過一些明確的行動(在彈出觸發f.i.)排序而不是通過正常的左鍵的一個例子。

如果是這樣,棘手的部分是強制ui委託不做任何事情。有兩個選項:

  • 鉤到由UI委託安裝在默認的鼠標偵聽器,如described in a recent QA
  • 讓UI做的東西,而是通過分類器實現欺騙它不遵守規則( 提防:這是因爲第一種方法爲髒)

誤運行得選機:

public class MyTableRowSorter extends TableRowSorter { 

    public MyTableRowSorter(TableModel model) { 
     super(model); 
    } 

    /** 
    * Implemented to do nothing to fool tableHeader internals. 
    */ 
    @Override 
    public void toggleSortOrder(int column) { 
    } 

    /** 
    * The method that really toggles, called from custom code. 
    * 
    * @param column 
    */ 
    public void realToggleSortOrder(int column) { 
     super.toggleSortOrder(column); 
    } 

} 

//使用

final JTable table = new JXTable(new AncientSwingTeam()); 
table.setRowSorter(new MyTableRowSorter(table.getModel())); 
Action toggle = new AbstractAction("toggleSort") { 

    @Override 
    public void actionPerformed(ActionEvent e) { 
     JXTableHeader header = SwingXUtilities.getAncestor(
       JXTableHeader.class, (Component) e.getSource()); 
     Point trigger = header.getPopupTriggerLocation(); 
     int column = trigger != null ? header.columnAtPoint(trigger) : -1; 
     if (column < 0) return; 
     int modelColumn = header.getTable().convertColumnIndexToModel(column); 
     ((MyTableRowSorter) header.getTable().getRowSorter()) 
      .realToggleSortOrder(modelColumn); 
    } 
}; 
JPopupMenu menu = new JPopupMenu(); 
menu.add(toggle); 
table.getTableHeader().setComponentPopupMenu(menu); 

呀,忍不住在一些SwingX API扔,我懶:-)帶滑動的Swing,你必須寫一些線條更,但基本是相同的:安裝tricksy分揀機並使用其自定義切換排序真的排序whereever needed,fi在mouseListener中。

相關問題