Search code examples
javaswingjtablejcomponent

How to render a Component in JTable using TableModel?


I have successfully displayed a JTable using an AbstractTableModel, but I want to add delete button for each row in the last column, in the getValueAt method that returns Object there is no way that I can return JButton, JLabel or any JComponent that is clickable. I tried that and I only get the object description toString.

Is there another solution to render JComponent in a JTable without using the TableModel approach?


Solution

  • Is there another solution to render JComponent in JTable without using the TableModel approach?

    The TableModel is used to hold the data for the data for the model.

    The JTable implements the view of the data for each column. The renderer is just a picture of the data. You can easily render the data to look like a button, however a renderer does not respond to any event.

    The JTable does support editors and that is how you interact with real components. When you edit a normal cell a JTextField is placed in the cell location so you can type data into the cell and then the data is save to the model.

    So if you want to click on a button then you need to use a button as an editor.

    Check out Table Column Button for a class that uses a JButton as the renderer and editor. You then provide the class an Action to be invoked when the button is clicked.

    Read the section from the Swing tutorial on Concepts: Renderers and Editor for more information. There is also a section on Using Other Editors.