I want to provide multi-cell editing functionality to a JTable: double click will still edit the value in the selected cell (the standard behavior), while right-click should open up a popup menu with an entry "Edit selected cells".
When the user hits this menu entry, the last cell in the selected range becomes editable. The other selected cells remain selected. Then they write the new value and, when the edition is finished (usually by hitting Enter), all of the selected cells get this value.
Let's assume, for simplicity, that all cells contain the same value types, say, integers.
Here's the code that shows up the popup dialog, to get started:
table.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
table.setCellSelectionEnabled(true);
table.addMouseListener(new MouseAdapter() {
@Override
public void mousePressed(MouseEvent e) {
if (e.isPopupTrigger()) {
doPop(e);
}
}
@Override
public void mouseReleased(MouseEvent e) {
if (e.isPopupTrigger()) {
doPop(e);
}
}
private void doPop(MouseEvent e) {
MultiEditPopUp menu = new MultiEditPopUp(tblRanges);
menu.show(e.getComponent(), e.getX(), e.getY());
}
});
class MultiEditPopUp extends JPopupMenu {
JMenuItem menuItem;
MultiEditPopUp(JTable table) {
menuItem = new JMenuItem("Edit selected");
menuItem.setAction(new BulkEditAction(table));
add(menuItem);
}
}
class BulkEditAction extends AbstractAction {
private final JTable table;
public BulkEditAction(JTable table) {
this.table = table;
}
@Override
public void actionPerformed(ActionEvent actionEvent) {
// TODO: let the user edit the last cell, and then apply to the others
}
}
How can I do such a thing?