How to add button in a row of JTable in Swing java
You don't add it to a row - you add it to the cell. This tutorial describes what you need.
You can add Component as a table cell.
First of all, you should implement a class that has JButton
as its parent class and two interfaces: TableCellRenderer
and TableCellEditor
.
The reason that it should implement TableCellEditor
is for receiving button's ActionEvent
.
public class TableButton extends JButton implements TableCellRenderer, TableCellEditor {
private int selectedRow;
private int selectedColumn;
Vector<TableButtonListener> listener;
public TableButton(String text) {
super(text);
listener = new Vector<TableButtonListener>();
addActionListener(new ActionListener() {
public void actionPerformed( ActionEvent e ) {
for(TableButtonListener l : listener) {
l.tableButtonClicked(selectedRow, selectedColumn);
}
}
});
}
public void addTableButtonListener( TableButtonListener l ) {
listener.add(l);
}
public void removeTableButtonListener( TableButtonListener l ) {
listener.remove(l);
}
@Override
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus, int row, int col) {
return this;
}
@Override
public Component getTableCellEditorComponent(JTable table,
Object value, boolean isSelected, int row, int col) {
selectedRow = row;
selectedColumn = col;
return this;
}
@Override
public void addCellEditorListener(CellEditorListener arg0) {
}
@Override
public void cancelCellEditing() {
}
@Override
public Object getCellEditorValue() {
return "";
}
@Override
public boolean isCellEditable(EventObject arg0) {
return true;
}
@Override
public void removeCellEditorListener(CellEditorListener arg0) {
}
@Override
public boolean shouldSelectCell(EventObject arg0) {
return true;
}
@Override
public boolean stopCellEditing() {
return true;
}
}
Then I added an EventListener named
TableButtonListener` for handling button event as follows.
public interface TableButtonListener extends EventListener {
public void tableButtonClicked( int row, int col );
}
And use above Renderer/Editor.
TableButton buttonEditor = new TableButton("Button");
buttonEditor.addButtonListener(new TableButtonListener() {
@Override
public void tableButtonClicked(int row, int col) {
// do something
}
});
TableColumn col = new TableColumn(1, 80);
col.setCellRenderer(buttonEditor);
col.setCellEditor(buttonEditor);
cols.addColumn(colPattern);
If you want to display different buttons label for each row, you should insert a code block into the getTableCellRendererComponent
and getTableCellEditorComponent
methods to modify button's label.