java - How to return actual cell component bounds in a JTable? - Stack Overflow

admin2022-06-14  64

I have a custom renderer in a JTable to display JCheckboxes for booleans. However, this causes a slight issue because when the user clicks in the table cell, but not in the checkbox, the checkbox is still checked.

Is there a way I can return the bounds of the actual JCheckbox that is rendered by the JTable at a particular point so I can determine if the click is within the bounds of the JCheckbox?

Thank you very much.

Answers:

I have a custom renderer in a JTable to display JCheckboxes for booleans. However, this causes a slight issue because when the user clicks in the table cell, but not in the checkbox, the checkbox is still checked.

Is there a way I can return the bounds of the actual JCheckbox that is rendered by the JTable at a particular point so I can determine if the click is within the bounds of the JCheckbox?

Thank you very much.

Answers:

If you are using the JCheckBox as the component returned from the TableCellEditor, then it'll be stretched to fit or something else (it doesn't appear to be specified). So, the obvious thing to do is put it in a JPanel, and that let it be stretched, leaving how to allocate space to a LayoutManager of your choice.

Answers:

Changing the state of the 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 behaviour for any column that has a type of Boolean.class (as determined by the TableModel). So you don't need to write any rendering/editing code, just ensure that your model returns the correct column type and the column will be rendered as checkboxes and edited with checkboxes.

EDIT: Maybe I was confused by what you were asking. Having seen Paul's comment on the question, I have to agree that the checkbox should be toggled if you click anywhere within the table cell.

Answers:

I actually just did similar thing this afternoon.

Here's my trick, for JTree. My checkbox is on the right most or the row.

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

转载请注明原文地址:https://www.u19.cn/read-152086.html

New Post(0)