Need a simple Swing code to demonstrate how to add a button in a column of a Jtable using tablecellrenderer and tablecelleditor.
Asked
Active
Viewed 7.6k times
7
-
Check this topic this may helpful. http://stackoverflow.com/questions/9321623/adding-button-to-jtable – Shantanu Banerjee Dec 12 '12 at 05:59
-
need a full sample code..i can't understand it.. – deva Dec 12 '12 at 06:04
-
What have you tried? There are many sources available for doing this. Look at this http://tips4java.wordpress.com/2009/07/12/table-button-column/ by Rob Camick. It is explained very well. – Amarnath Dec 12 '12 at 06:37
2 Answers
26
Here a really nice example which adds a JButton
to a cell in JTable
:
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultCellEditor;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellRenderer;
public class JButtonTableExample {
public JButtonTableExample() {
JFrame frame = new JFrame("JButtonTable Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
DefaultTableModel dm = new DefaultTableModel();
dm.setDataVector(new Object[][]{{"button 1", "foo"},
{"button 2", "bar"}}, new Object[]{"Button", "String"});
JTable table = new JTable(dm);
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));
JScrollPane scroll = new JScrollPane(table);
table.setPreferredScrollableViewportSize(table.getPreferredSize());//thanks mKorbel +1 http://stackoverflow.com/questions/10551995/how-to-set-jscrollpane-layout-to-be-the-same-as-jtable
table.getColumnModel().getColumn(0).setPreferredWidth(100);//so buttons will fit and not be shown butto..
frame.add(scroll);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
new JButtonTableExample();
}
});
}
}
class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setForeground(table.getSelectionForeground());
setBackground(table.getSelectionBackground());
} else {
setForeground(table.getForeground());
setBackground(UIManager.getColor("Button.background"));
}
setText((value == null) ? "" : value.toString());
return this;
}
}
class ButtonEditor extends DefaultCellEditor {
protected JButton button;
private String label;
private boolean isPushed;
public ButtonEditor(JCheckBox checkBox) {
super(checkBox);
button = new JButton();
button.setOpaque(true);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
});
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected) {
button.setForeground(table.getSelectionForeground());
button.setBackground(table.getSelectionBackground());
} else {
button.setForeground(table.getForeground());
button.setBackground(table.getBackground());
}
label = (value == null) ? "" : value.toString();
button.setText(label);
isPushed = true;
return button;
}
@Override
public Object getCellEditorValue() {
if (isPushed) {
JOptionPane.showMessageDialog(button, label + ": Ouch!");
}
isPushed = false;
return label;
}
@Override
public boolean stopCellEditing() {
isPushed = false;
return super.stopCellEditing();
}
}
References:

hoat4
- 1,182
- 12
- 9

David Kroukamp
- 36,155
- 13
- 81
- 138
-
How to addActionlistener for that Button to delete the corresponding row.. – deva Dec 13 '12 at 04:33
-
-
I tried this code and it displays button perfecly, but I am not able to click it, its not enabled or disabled, so do you know what is the issue with it? It looks like on the picture you posted, but i cant click it...Thanks in advance! – Vasilije Bursac Jan 03 '20 at 14:34
-
2I fixed the issue. Remember that cell must be Editable. So in your cell editor you need to have something like this: `@Override public boolean isCellEditable(EventObject e){ return true; }` Hope this will help someone! – Vasilije Bursac Jan 03 '20 at 16:39
23
###Add button to JTable
JTable table = new JTable(new JTableModel());
JScrollPane scrollPane = new JScrollPane(table);
table.setFillsViewportHeight(true);
TableCellRenderer buttonRenderer = new JTableButtonRenderer();
table.getColumn("Button1").setCellRenderer(buttonRenderer);
table.getColumn("Button2").setCellRenderer(buttonRenderer);
###Sample JTableModel
, This is manage the columns and rows, Setting components
public static class JTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] COLUMN_NAMES = new String[] {"Id", "Stuff", "Button1", "Button2"};
private static final Class<?>[] COLUMN_TYPES = new Class<?>[] {Integer.class, String.class, JButton.class, JButton.class};
@Override public int getColumnCount() {
return COLUMN_NAMES.length;
}
@Override public int getRowCount() {
return 4;
}
@Override public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
@Override public Class<?> getColumnClass(int columnIndex) {
return COLUMN_TYPES[columnIndex];
}
@Override public Object getValueAt(final int rowIndex, final int columnIndex) {
/*Adding components*/
switch (columnIndex) {
case 0: return rowIndex;
case 1: return "Text for "+rowIndex;
case 2: // fall through
/*Adding button and creating click listener*/
case 3: final JButton button = new JButton(COLUMN_NAMES[columnIndex]);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JOptionPane.showMessageDialog(JOptionPane.getFrameForComponent(button),
"Button clicked for row "+rowIndex);
}
});
return button;
default: return "Error";
}
}
}
###Sample Button click listener
, This manage the when mouse is clicked over the component
private static class JTableButtonMouseListener extends MouseAdapter {
private final JTable table;
public JTableButtonMouseListener(JTable table) {
this.table = table;
}
public void mouseClicked(MouseEvent e) {
int column = table.getColumnModel().getColumnIndexAtX(e.getX()); // get the coloum of the button
int row = e.getY()/table.getRowHeight(); //get the row of the button
/*Checking the row or column is valid or not*/
if (row < table.getRowCount() && row >= 0 && column < table.getColumnCount() && column >= 0) {
Object value = table.getValueAt(row, column);
if (value instanceof JButton) {
/*perform a click event*/
((JButton)value).doClick();
}
}
}
}
###Sample JTable Cell Renderer, Managing the cell component
private static class JTableButtonRenderer implements TableCellRenderer {
@Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton)value;
return button;
}
}

Community
- 1
- 1

Shantanu Banerjee
- 1,417
- 6
- 31
- 51
-
1
-
3you've missed table.addMouseListener(new JTableButtonMouseListener(table)); – Andrew Selivanov Feb 26 '16 at 16:43
-
-
More simple solution is here - https://stackoverflow.com/a/40440287/341117 – Ravindra Gullapalli Nov 05 '20 at 19:29
-
You are putting things that are supposed to be in the View (the JButton) into the Model (TableModel). The JButton should only be part of the renderer. -1. – searchengine27 Jun 17 '22 at 17:22