您应该创建一个自定义 DefaultTableRenderer 和一个自定义 TableCellEditor
也许这就是你要找的:
public class ButtonTable extends JDialog {
private final JPanel contentPanel = new JPanel();
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
try {
ButtonTable dialog = new ButtonTable();
dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
dialog.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Create the dialog.
*/
public ButtonTable() {
setBounds(100, 100, 450, 300);
getContentPane().setLayout(new BorderLayout());
contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5));
getContentPane().add(contentPanel, BorderLayout.CENTER);
GridBagLayout gbl_contentPanel = new GridBagLayout();
gbl_contentPanel.columnWidths = new int[]{414, 0};
gbl_contentPanel.rowHeights = new int[]{240, 0};
gbl_contentPanel.columnWeights = new double[]{1.0, Double.MIN_VALUE};
gbl_contentPanel.rowWeights = new double[]{1.0, Double.MIN_VALUE};
contentPanel.setLayout(gbl_contentPanel);
JScrollPane scrollPane = new JScrollPane();
GridBagConstraints gbc_scrollPane = new GridBagConstraints();
gbc_scrollPane.fill = GridBagConstraints.BOTH;
gbc_scrollPane.gridx = 0;
gbc_scrollPane.gridy = 0;
contentPanel.add(scrollPane, gbc_scrollPane);
table = new JTable() {
public boolean isCellEditable(int row, int column) {
return column == 2;
};
};
table.setFillsViewportHeight(true);
table.setModel(new DefaultTableModel(
new Object[][] {
{"ONE", null, null},
{"TWO", null, null},
{"THREE", null, null},
{"FOUR", null, null},
{"FIVE", null, null},
},
new String[] {
"First Column", "Second Column", "Button"
}
));
table.getColumnModel().getColumn(0).setPreferredWidth(196);
table.getColumnModel().getColumn(1).setPreferredWidth(180);
table.setDefaultEditor(Object.class, new TableEditor(new JTextField()));
table.setDefaultRenderer(Object.class, new TableRenderer());
scrollPane.setViewportView(table);
}
}
class TableEditor extends DefaultCellEditor implements TableCellEditor {
//This is just because the Constructor of superclass needs a JTextField, or JCheckBox or whatever...
public TableEditor(JTextField field) {
super(field);
}
@Override
public Component getTableCellEditorComponent(JTable table, Object value,
boolean isSelected, int row, int column) {
if (isSelected && column == 2)
return new JButton("Delete");
return super.getTableCellEditorComponent(table, value, isSelected, row, column);
}
}
class TableRenderer extends DefaultTableCellRenderer {
@Override
public Component getTableCellRendererComponent(JTable table, Object value,
boolean isSelected, boolean hasFocus, int row, int column) {
if (isSelected && column == 2)
return new JButton("Delete");
return super.getTableCellRendererComponent(table, value, isSelected, hasFocus,
row, column);
}
}