JTable 为单元格添加按钮效果和事件效果
时间: 2024-02-25 09:58:39 浏览: 113
学会用JScrollPane和Jtable以及table的Defaulttablemodel*
要为 JTable 中的单元格添加按钮效果和事件效果,可以使用 TableCellRenderer 和 TableCellEditor 接口来实现。以下是一个示例代码:
```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.JOptionPane;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
public class JTableButtonDemo {
public static void main(String[] args) {
JFrame frame = new JFrame("JTable Button Demo");
Object[][] data = { { "Button 1", "Button 2" }, { "Button 3", "Button 4" } };
String[] columnNames = { "Column 1", "Column 2" };
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.getColumn("Column 1").setCellRenderer(new ButtonRenderer());
table.getColumn("Column 1").setCellEditor(new ButtonEditor());
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
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;
private Object value;
public ButtonEditor() {
button = new JButton();
button.addActionListener(this);
}
public Object getCellEditorValue() {
return value;
}
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
this.value = value;
button.setText((value == null) ? "" : value.toString());
return button;
}
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(button, "Button clicked!");
fireEditingStopped();
}
}
}
```
在上面的示例代码中,我们创建了一个 JTable,其中的第一列单元格都是按钮,点击每个按钮会弹出一个对话框。我们使用 ButtonRenderer 类来渲染单元格中的按钮,使用 ButtonEditor 类来编辑单元格中的按钮。在 ButtonEditor 中,我们添加了一个 ActionListener 来处理按钮的点击事件。注意:这个示例只是演示了如何为 JTable 添加按钮效果和事件效果,实际应用中可能需要更复杂的逻辑。
阅读全文