views:

1039

answers:

3

I have a JTable that stores the results of a database query, so far so good. What I want is for the last column in each table to have a clickible JButton that will open the edit screen for the object represented in that row, and that means the button will need to know the details of the first column in the table from its own row (the ID from the database).

Any advice? I already tried just adding JButtons but they turned into Text when I tried to run it.

A: 

There is a nice tutorial on how to do just that here.

Pablo Santa Cruz
I think it's overkill to implement a TableModel for JButtons, they're nothing to do with the data model, they just perform an action. The simple example for the ColorRenderer in the Sun tutorial does this much more simply in my opinion
ninesided
Totally agree with you.
Pablo Santa Cruz
I've worked with that sample code from the tutorial and it doesn't seem to work exactly right. The first button I click works, but subsequent actions require a triple-click to fire. First click makes button disappear, second click it comes back, finally on the third click it fires.
Brian Knoblauch
+2  A: 

Take a look at Sun's introduction to the JTable component, specifically, the section about Editors and Renderers. It discusses the use of alternative CellRenderers, and CellEditors. What you'd need to do is create (or borrow) a ButtonCellRenderer and a ButtonCellEditor and then apply them to the column in question in your JTable. The examples found in the linked articles should give you all the information you need.

ninesided
it's easy except getting mouse clicks to forward to a ButtonCellRenderer's buttons.
Jason S
+4  A: 

Contrary to the tutorial above, there is a way to do this without a complicated positioning math, custom mouse listeners, and custom table models. Instead, it can be done with a single simple custom class following the pattern described here:

http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx

Ilya
this is excellent and very helpful.
Epaga