java swing 在tablebox行后添加按钮
时间: 2024-05-16 21:17:20 浏览: 16
要在 Java Swing 的 JTable 中的每一行后面添加一个按钮,可以使用 JTable 的 DefaultTableModel 和 JButtonRenderer。首先,创建一个 DefaultTableModel 对象,并使用 addColumn() 方法添加列。然后,使用 addRow() 方法添加行。接下来,创建一个 JButtonRenderer 类,该类扩展了 JButton 并实现了 TableCellRenderer 接口,以便 JTable 可以在单元格中呈现按钮。最后,将 JButtonRenderer 分配给表格列的单元格渲染器。
下面是一个示例代码片段:
```java
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Name");
model.addColumn("Age");
model.addColumn("Button");
JTable table = new JTable(model) {
public TableCellRenderer getCellRenderer(int row, int column) {
if (column == 2) {
return new JButtonRenderer();
} else {
return super.getCellRenderer(row, column);
}
}
};
table.getColumnModel().getColumn(2).setCellRenderer(new JButtonRenderer());
model.addRow(new Object[]{"John", 25, "Click"});
model.addRow(new Object[]{"Jane", 30, "Click"});
// JButtonRenderer class
class JButtonRenderer extends JButton implements TableCellRenderer {
public JButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
setText((value == null) ? "" : value.toString());
return this;
}
}
```
在这个示例中,我们创建了一个包含三列的表格(Name、Age 和 Button)。我们使用 DefaultTableModel 的 addRow() 方法添加两行到表格中。最后,我们创建了一个 JButtonRenderer 类,并将其设置为第三列的单元格渲染器。在 getTableCellRendererComponent() 方法中,我们设置了按钮的文本并返回该按钮。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)