11

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.

ninesided
  • 23,085
  • 14
  • 83
  • 107
Benjamin Confino
  • 2,344
  • 3
  • 26
  • 30

3 Answers3

5

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://web.archive.org/web/20100623105810/http://ivolo.mit.edu/post/A-Simple-Pattern-for-Embedding-Components-into-a-Swing-JTable.aspx

Shog9
  • 156,901
  • 35
  • 231
  • 235
Ilya
  • 629
  • 8
  • 11
  • 2
    The link is dead, is it still possible to find that solution anywhere? – KristianMedK Jul 13 '11 at 06:13
  • 1
    The Way Back Machine has a copy... But this solution does appear to use a custom (albeit anonymous) table model, so I'm not sure at first glance what makes this tutorial better than any other... – Rini Sep 06 '11 at 17:46
3

You may also find my tutorial on a similar subject (in this case, using a JPanel) helpful as well: Custom JPanel cell with JButtons in JTable

pek
  • 17,847
  • 28
  • 86
  • 99
1

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
  • 23,085
  • 14
  • 83
  • 107
  • it's easy except getting mouse clicks to forward to a ButtonCellRenderer's buttons. – Jason S Feb 09 '10 at 19:40
  • 2
    The renderer doesn't accept events. That's the editor's job. Have a look at my tutorial in the answer I gave. – pek Sep 08 '11 at 18:38