2012-12-13 51 views
0

如何確保我的JTable中只有一些列是可選擇的(意思是它們路由到我的ListSelectionListener)?如何將特定列設置爲可在JTable中選擇?

我已經加入我的聽衆如下:

table.getSelectionModel().addListSelectionListener(new ListSelectionListener() {...}); 
+0

你爲什麼要這麼做? – DrinkJavaCodeJava

+0

當我的JTable中的某個列被選中時,我通知了一組偵聽器。但是,我在同一張表中還有另一列是編輯器。我不想在用戶選擇編輯器列時通知監聽器。 – sdasdadas

回答

3

最簡單的解決方案可能是創建你自己的選擇模型:

table.getColumnModel().setSelectionModel(new DefaultListSelectionModel() { 
    private boolean isSelectable(int index0, int index1) { 
     // TODO: Decide if this column index is selectable 
     return true; 
    } 

    @Override 
    public void setSelectionInterval(int index0, int index1) { 
     if(isSelectable(index0, index1)) { 
      super.setSelectionInterval(index0, index1); 
     } 
    } 

    @Override 
    public void addSelectionInterval(int index0, int index1) { 
     if(isSelectable(index0, index1)) { 
      super.addSelectionInterval(index0, index1); 
     } 
    } 
}); 

還要注意的是,如果你想監聽的列選擇,您想要將偵聽器添加到列模型的選擇模型(而不是表格的選擇模型)。

+0

謝謝,那很完美。 – sdasdadas

相關問題