如何在Jtable中每行最后一节添加删除按钮
时间: 2024-05-16 13:17:02 浏览: 164
JTable实现网页的编辑和删除按钮Demo.rar
可以通过自定义表格单元格渲染器来实现在 JTable 中为每行添加一个删除按钮。
首先,创建一个类继承 JButton,用于创建删除按钮。例如:
```
class DeleteButtonRenderer extends JButton implements TableCellRenderer {
public DeleteButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected) {
setBackground(table.getSelectionBackground());
} else {
setBackground(table.getBackground());
}
setText("Delete");
return this;
}
}
```
然后,创建一个类继承 AbstractCellEditor,用于创建删除按钮的编辑器。例如:
```
class DeleteButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
protected JButton button;
public DeleteButtonEditor() {
button = new JButton("Delete");
button.addActionListener(this);
}
public Object getCellEditorValue() {
return "Delete";
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
return button;
}
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
}
```
最后,在 JTable 中为每行添加删除按钮。例如:
```
TableColumnModel columnModel = table.getColumnModel();
columnModel.getColumn(columnModel.getColumnCount() - 1).setCellRenderer(new DeleteButtonRenderer());
columnModel.getColumn(columnModel.getColumnCount() - 1).setCellEditor(new DeleteButtonEditor());
```
这样,每行最后一列将包含一个删除按钮,点击该按钮将触发相应的操作。
阅读全文