Java Swing 中JTable添加按钮流程如下:
- 实现TableCellRenderer接口
- 实现TableCellEditor接口(或者extends DefaultCellEditor)
- 继承AbstractTableModel,重写getValueAt()和getColumnClass()
- 获取列分别设置渲染器和编辑器
- 注意如果JTable设置了行选中,要禁止掉,否则点击按钮会被响应为选中行!
主要代码:
- 实现TableCellRenderer接口:
private class ButtonRenderer implements TableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
JButton button = (JButton)value;
button.setText("before");
return button;
}
}
- 继承DefaultCellEditor:
private class ButtonEditor extends DefaultCellEditor {
private static final long serialVersionUID = -6546334664166791132L;
public ButtonEditor() {
super(new JTextField());
this.setClickCountToStart(1);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
JButton button = (JButton)value;
button.setText("after");
button.addActionListener(new AbstractAction() {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("edit!!!!");
}
});
return button;
}
}
- 继承AbstractTableModel,重写getValueAt()、getColumnClass()和:
public static class JTableModel extends AbstractTableModel {
private static final long serialVersionUID = 1L;
private static final String[] COLUMN_NAMES = new String[] {
"Id", "Stuff", "Button1", "Button2"};
private static final Class<?>[] COLUMN_TYPES = new Class<?>[] {
Integer