I want to add jButton inside column and then delete row using added jButton I've tried some stackoverflow questions and have following code but that doesn't deleting a row.
public class NewJFrame extends javax.swing.JFrame {
JButton jb = new JButton();
public NewJFrame() {
initComponents();
jTable.getColumn(" ").setCellRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
jb.setText("Delete");
return jb;
}
});
jTable.getColumn(" ").setCellEditor(new TableCellEditor() {
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
if (isSelected) {
jb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
jTable = (JTable) e.getSource();
int modelRow = Integer.valueOf(e.getActionCommand());
((DefaultTableModel) jTable.getModel()).removeRow(modelRow);
}
});
}
return jb;
}
We can do it like in below sample program. We can write a custom renderer + editor which simply returns a
JButton
as the renderer/editor component. Notice that row index is stored in a field in the editor.