接受的答案不会像或考虑修饰键那样考虑,但它们表明当前选择不应被替换,而应扩展。ctrlshift
另外,我通过检查和添加了多操作系统支持。mousePressed
mouseReleased
下面,您可以找到有关如何使用 ListSelectionModel
调整所选行的完整示例,包括 MouseEvent#getModifiers
检查。之后,可以打开一个(可选的)JPopupMenu
。
JPopupMenu contextMenu = new JPopupMenu();
// ...
// add elements to the popup menu
// ...
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
handleRowClick(e);
if (e.isPopupTrigger()) {
doPop(e);
} else {
hidePop();
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
doPop(e);
}
}
private void handleRowClick(MouseEvent e) {
ListSelectionModel selectionModel = table.getSelectionModel();
Point contextMenuOpenedAt = e.getPoint();
int clickedRow = table.rowAtPoint(contextMenuOpenedAt);
if (clickedRow < 0) {
// No row selected
selectionModel.clearSelection();
} else {
// Some row selected
if ((e.getModifiers() & InputEvent.SHIFT_MASK) == InputEvent.SHIFT_MASK) {
int maxSelect = selectionModel.getMaxSelectionIndex();
if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
// Shift + CTRL
selectionModel.addSelectionInterval(maxSelect, clickedRow);
} else {
// Shift
selectionModel.setSelectionInterval(maxSelect, clickedRow);
}
} else if ((e.getModifiers() & InputEvent.CTRL_MASK) == InputEvent.CTRL_MASK) {
// CTRL
selectionModel.addSelectionInterval(clickedRow, clickedRow);
} else {
// No modifier key pressed
selectionModel.setSelectionInterval(clickedRow, clickedRow);
}
}
}
private void doPop(MouseEvent e) {
if (table.getSelectedRowCount() == 0) {
return;
}
contextMenu.setVisible(true);
contextMenu.show(e.getComponent(), e.getX(), e.getY());
}
private void hidePop() {
contextMenu.setVisible(false);
}
});