2017-04-16 68 views
6

我有JTable並希望允許通過單擊表的空白部分來取消選擇所有行。迄今爲止,這工作得很好。然而,即使我打電話table.clearSelection();表仍顯示先前啓用的小區周圍的邊框(請參閱細胞中的例子):JTable:在清除行選擇時清除單元格周圍的邊框

Table deselection issue

我想擺脫這個邊界,以及(它看起來特別不適合Mac的原生外觀和感覺,細胞突然變黑)。

完全正常的小例子代碼:

public class JTableDeselect extends JFrame { 
    public JTableDeselect() { 
     Object rowData[][] = { { "1", "2", "3" }, { "4", "5", "6" } }; 
     Object columnNames[] = { "One", "Two", "Three" }; 
     JTable table = new JTable(rowData, columnNames); 
     table.setFillsViewportHeight(true); 
     table.addMouseListener(new MouseAdapter() { 
      @Override 
      public void mousePressed(MouseEvent e) { 
       if (table.rowAtPoint(e.getPoint()) == -1) { 
        table.clearSelection(); 
       } 
      } 
     }); 
     add(new JScrollPane(table)); 
     setSize(300, 150); 
    } 
    public static void main(String args[]) throws Exception { 
     UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName()); 
     new JTableDeselect().setVisible(true); 
    } 
} 

[編輯]嘗試添加這是在這裏提到table.getColumnModel().getSelectionModel().clearSelection();。但是這也沒有幫助。

回答

3

嘗試添加table.getColumnModel()getSelectionModel()clearSelection();

table.clearSelection()方法調用該方法和TableColumnModelclearSelection()方法。

除了清除您還需要重置「錨,並導致」選擇模型的指標選擇:

table.clearSelection(); 

ListSelectionModel selectionModel = table.getSelectionModel(); 
selectionModel.setAnchorSelectionIndex(-1); 
selectionModel.setLeadSelectionIndex(-1); 

TableColumnModel columnModel = table.getColumnModel(); 
columnModel.getSelectionModel().setAnchorSelectionIndex(-1); 
columnModel.getSelectionModel().setLeadSelectionIndex(-1); 

現在,如果你使用箭頭鍵焦點將去(0,0 ),所以你確實丟失了被點擊的最後一個單元格的信息。

如果您只清除選擇模型,那麼您將丟失行信息,但列信息將保留。

嘗試清除其中一個或兩個模型以獲得所需的效果。

5

您的問題:即使選擇丟失,您的表格單元仍具有焦點,因此它通過顯示加粗的邊框來顯示它自身。瞭解 一種可能的解決方案是創建自己的渲染器,當單元格失去選擇時刪除單元格的焦點。例如:

table.setDefaultRenderer(Object.class, new DefaultTableCellRenderer() { 
    @Override 
    public Component getTableCellRendererComponent(JTable table, Object value, 
      boolean isSelected, boolean hasFocus, int row, int column) { 
     if (!isSelected) { 
      hasFocus = false; 
     } 
     return super.getTableCellRendererComponent(table, value, isSelected, hasFocus, row, column); 
    } 
}); 
+0

謝謝!簡單而有效! – qqilihq

+0

@qqilihq,這假定表中的所有數據使用相同的渲染器。對於更一般的解決方案,除了清除選擇之外,還需要重置選擇模型的錨/索引索引。那麼你不需要自定義渲染器。 – camickr

+0

@camickr:謝謝你。 1+給你的答案 –