Making a JButton clickable inside a JTable

前端 未结 6 1630
滥情空心
滥情空心 2020-12-05 23:38

Here is the screenshot of what I want to do :

\"enter

What\'s happening there

6条回答
  •  庸人自扰
    2020-12-06 00:08

    The problem is that the JButton no longer exists when painted in the table. Those components are only used to create a 'stamp' when the table is rendered. There is no actual button present.

    There is a way to allow you to click on the button, and still keep your table non-editable, but it is far from proper code. Just a quick outline for a possible solution (I do not have the time at this moment to give a full code example)

    • attach a mouse listener to the table
    • when you receive a mouse click, determine the cell in which the mouse click occurred
    • ask the table renderer for the component for that cell
    • use the location of the mouse click to determine whether a button is present in the component from the previous step at that particular location
    • if so, do the click through the button api (the doClick method)

    And this is not even the dirty part of the code. Since your renderer (hopefully) does not return a new JButton each time, you should in your ActionListener which is attached to the JButton keep track of for which component the click actually occurred. A possible solution is to keep a reference to the table model value for which you the last time created a JButton (so in the getCellRendererComponent method keep track of the row/column), but I am unsure whether this is the best approach.

    As said, a possible solution but far from elegant.

    The easiest way is to just make that one column editable and use an editor, as pointed out in other answers

提交回复
热议问题