首页 > 解决方案 > 当行索引 < 0 时取消选择 JTable 行

问题描述

我的问题很简单,我只是不知道如何在谷歌上查询。

我想要的只是在单击 a 上的一行时打印选定的行索引JTable

样本

问题是,如果我单击有效的行索引(即index >= 0 && index < rowCount),然后单击没有行的表下部的有效行之外(显然是现在index < 0),打印的行索引仍然是最后一个有效的我单击的行索引。我想要的是"No row selected"在我单击没有行的表格的下部空白部分时打印并清除行选择。

在此处输入图像描述

(我已经在表格下方空白部分的行之外单击)

这是我的代码:

JTable table = new JTable(new MyTableModel());
table.setFillsViewportHeight(true);

table.addMouseListener(new MouseAdapter() {
    @Override
    public void mousePressed(MouseEvent e) {
        int rowIndex = table.getSelectedRow();
        if(rowIndex < 0) {
            System.out.println("No row selected");
            table.clearSelection();
        } else {
            System.out.println("Row " + rowIndex + " selected");
        }
    }
});

这个简单的程序唯一一次按我想要的方式工作是当我将它设置setFillsViewportHeightfalse或忽略它时,因为它是false默认的。

table.setFillsViewportHeight那么在设置为时我该怎么做true呢?

标签: javaswingjtablerowmouselistener

解决方案


您可以使用table.rowAtPoint(e.getPoint())来获取单击的行。-1如果选择无效,它将返回(当您单击表格下方时):

public void mousePressed(MouseEvent e) {
    //Updated to use rowAtPoint
    int rowIndex = table.rowAtPoint(e.getPoint());

    //Existing code
    if(rowIndex < 0) {
        System.out.println("No row selected");
        table.clearSelection();
    } else {
        System.out.println("Row " + rowIndex + " selected");
    }
}

推荐阅读