2017-04-16 69 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+给你的答案 –