在Swing開發中,獲取JTable滑鼠點擊位置的行號是常見需求。關鍵在於使用JTable.rowAtPoint(Point)方法,配合滑鼠事件的getPoint()即可精確定位。
JTable table = new JTable(cells, columnNames);
table.addMouseListener(new java.awt.event.MouseAdapter() {
@Override
public void mouseClicked(java.awt.event.MouseEvent e) {
// 獲取滑鼠點擊座標
Point mousePoint = e.getPoint();
// 轉換為行號(從0開始,顯示時+1)
int rowIndex = table.rowAtPoint(mousePoint);
System.out.println("點擊行號: " + (rowIndex + 1));
// 可選:獲取總行數對比
System.out.println("表格總行數: " + table.getRowCount());
}
});
if (rowIndex >= 0)public void mouseClicked(MouseEvent e) {
int row = table.rowAtPoint(e.getPoint());
if (row >= 0) {
if (e.getClickCount() == 2) {
// 雙擊觸發編輯
startEditing(row);
} else if (SwingUtilities.isRightMouseButton(e)) {
// 右鍵彈出選單
showContextMenu(e.getX(), e.getY(), row);
}
}
}
這種方式比遍歷選擇模型更直接高效,適合即時響應滑鼠操作的場景。