java jtable 添加按钮,添加按钮到jtable
时间: 2023-11-17 21:07:13 浏览: 249
要向 JTable 添加按钮,你需要创建一个自定义的 TableCellRenderer 和 TableCellEditor,以便显示和编辑该单元格的按钮。
以下是一个简单的例子,演示如何将按钮添加到 JTable 中:
```java
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.AbstractCellEditor;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class ButtonRendererEditorExample {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable with Buttons");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[][] data = {
{"Button 1", new JButton("Click 1")},
{"Button 2", new JButton("Click 2")},
{"Button 3", new JButton("Click 3")},
{"Button 4", new JButton("Click 4")}
};
String[] columnNames = {"Button Name", "Button"};
JTable table = new JTable(data, columnNames);
table.getColumn("Button").setCellRenderer(new ButtonRenderer());
table.getColumn("Button").setCellEditor(new ButtonEditor(new JButton()));
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
frame.pack();
frame.setVisible(true);
}
static class ButtonRenderer extends JButton implements TableCellRenderer {
public ButtonRenderer() {
setOpaque(true);
}
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus,
int row, int column) {
setText((value == null) ? "" : value.toString());
return this;
}
}
static class ButtonEditor extends AbstractCellEditor implements TableCellEditor, ActionListener {
private JButton button;
public ButtonEditor(JButton button) {
this.button = button;
this.button.addActionListener(this);
}
public Object getCellEditorValue() {
return button.getText();
}
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
return button;
}
public void actionPerformed(ActionEvent e) {
fireEditingStopped();
}
}
}
```
在此示例中,我们将一个 JTable 填充了四个带有不同标签的 JButton 对象。我们使用自定义的 ButtonRenderer 类为 JTable 中的按钮单元格提供渲染,以便它们可以正确显示。我们使用自定义的 ButtonEditor 类作为单元格编辑器,以便用户可以在单元格上单击按钮。当用户单击按钮时,我们会触发 fireEditingStopped() 方法,以便通知 JTable 编辑已完成。
阅读全文