java表格添加按钮
时间: 2023-02-07 09:59:08 浏览: 175
tableview_fx
在 Java 中,可以使用 JTable 类来创建表格。要在表格中添加按钮,需要使用一个称为表格渲染器 (table renderer) 的组件。
下面是一个示例代码,可以帮助你在表格中添加按钮:
```
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellRenderer;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class TableButtonExample {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object[][] data = {
{"John", "Doe", new JButton("Click me")},
{"Jane", "Doe", new JButton("Click me")},
};
String[] columnNames = {"First Name", "Last Name", "Button"};
JTable table = new JTable(new AbstractTableModel() {
@Override
public int getRowCount() {
return data.length;
}
@Override
public int getColumnCount() {
return columnNames.length;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return data[rowIndex][columnIndex];
}
@Override
public String getColumnName(int column) {
return columnNames[column];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return columnIndex == 2;
}
});
table.getColumn("Button").setCellRenderer(new TableCellRenderer() {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton) value;
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked for row " + row);
}
});
return button;
}
});
frame.add(new JScrollPane(table));
frame.pack();
frame.setVisible(true);
}
}
```
在上面的代码中,我们使用了 AbstractTableModel 类来创建一个表格模
阅读全文