How can I get the component at the mouse click position, when using a TableCellEditor?

◇◆丶佛笑我妖孽 提交于 2019-12-04 05:08:04
kleopatra

Not entirely sure I understand what's going wrong (just let me know if I'm off, so I can delete this :-)

Assuming you want to get the "real" component under the mouse (click/press) which triggered the start of editing, the trick is to do the conversion (from parent to editor coordinates) after the editor is added to its parent. That's guaranteed for shouldSelectCell, but not for isCellEditable (the latter being called before)

A recent answer in the context of a tree (should be similar enough) has some runnable example. Here's the relevant snippet:

/**
 * At this point in time the editing component is added to the table (not documented!) but
 * table's internal cleanup might not yet be ready
 */ 
@Override
public boolean shouldSelectCell(EventObject anEvent) {
    if (anEvent instanceof MouseEvent) {
        redirect((MouseEvent) anEvent);
    }
    return false;
}

private void redirect(final MouseEvent anEvent) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            MouseEvent ev = SwingUtilities.convertMouseEvent(anEvent.getComponent(), anEvent, editor);
            // at this point you have the mouse coordinates in the editor's system
            // do stuff, like f.i. findComponent
            ....
        }
    });
}
trashgod

This is not an answer to your question but an explanation of the result you see: findComponentAt() returns null because "there is no child component at the requested point." MyCellPanel is located on a CellRendererPane used by JTable to speed rendering. There's an example of how it's used here.

You can get the table's row and column from the clicked point. Then call the same renderer's getTableCellRendererComponent method to get renderer component. Then correct point subtracting previous rows' heights from y and previous cells' widths from x. Then get proper child of rendered component.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!