簡體   English   中英

JTable:清除行選擇時刪除單元格周圍的邊框

[英]JTable: Remove border around cell when clearing row selection

我有一個JTable並希望通過單擊表的空白部分來取消選擇所有行。 這到目前為止工作正常。 但是,即使我調用table.clearSelection(); 該表仍顯示先前啟用的單元格周圍的邊框(請參閱示例中的單元格5 ):

表取消選擇問題

我也想擺脫這個邊界(它看起來特別不合適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);
    }
}

[edit]試圖添加table.getColumnModel().getSelectionModel().clearSelection(); 這是在這里提到的。 但這也無濟於事。

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

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);
    }
});

試圖添加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),因此您將丟失有關最后一個單擊單元格的信息。

如果僅清除選擇模型,則將丟失行信息,但列信息將保留。

嘗試清除一個或兩個模型以獲得您想要的效果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM