How do I return the actual bounds of component components in a JTable?
I have a custom render in JTable
to render JCheckbox
es for boolean
s. However, this causes a small problem, because when the user clicks on a table cell but not the checkbox, the checkbox is still checked.
Is there a way that I can return the bounds of the actual JCheckbox
one that is displayed JTable
at a specific point so that I can determine if the click is within the bounds JCheckbox
?
Many thanks.
Changing the state of a checkbox is the responsibility of the editor, not the renderer. If you use DefaultCellEditor
, you don't need to write your own code.
I may be wrong, but I think this is the default behavior for any column that is of type Boolean.class
(as defined in TableModel
). So you don't need to write any rendering / editing code, just make sure your model returns the correct column type and the column will show as checkboxes and edit with checkboxes.
UPDATE: Maybe I was confused about what you were asking. After seeing Paul comment on this question, I must agree that the checkbox should be checked if you click anywhere in a table cell.
source to share
I actually just did something like this this afternoon.
Here's my trick for JTree
. My checkbox is on the right or next to it.
public void mouseClicked(MouseEvent e) {
int x = e.getX();
int y = e.getY();
int row = getRowForLocation(x, y);
Rectangle rect = getRowBounds(row);
Rectangle rect2 = new Rectangle(rect.x, rect.y, rect.height + 2, rect.height);
if (rect2.contains(x, y)) .... // The click is on the checkbox
source to share