java - 当行索引 < 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");
}
}
});
这个简单的程序唯一一次按我想要的方式工作是当我将它设置setFillsViewportHeight
为false
或忽略它时,因为它是false
默认的。
table.setFillsViewportHeight
那么在设置为时我该怎么做true
呢?
解决方案
您可以使用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");
}
}
推荐阅读
- c# - 时间:2019-05-10 标签:c#singletonclassworkingwellconfirmation
- python - 如何在 django 中创建另一个用户(学生和教师)表
- node.js - MongoDb $inc 自动增加两倍
- python - Pickle - 无法将附加的字典正确存储到列表中
- php - 在 codeigniter 中的 form_validation > set_rules > valid_email 中出现错误
- python - 图卷积网络上的词项加权
- rust - 无法将 RefCell 中的 TlsStream 借用为可变的
- javascript - 在 javascript 文件中注释 HTML 代码
- ios - RxSwift 和三个 API 请求
- maven - 用于查找工件的 Nexus 存储库管理器不起作用