问题
I searched for tutorials for adding button in jtable and found a class file from, http://tips4java.wordpress.com/2009/07/12/table-button-column/ Where to set label for the button?
[code]
private void createTable(){
model = new DefaultTableModel();
editorTable.setModel(model);
model.addColumn("COL1");
model.addColumn("COL2");
model.addColumn("ADD");
model.addColumn("DELETE");
model.addRow(new Object[]{"DATA1", "DATA2"});
Action delete = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
editorTable = (JTable) e.getSource();
int modelRow = Integer.valueOf(e.getActionCommand());
((DefaultTableModel) editorTable.getModel()).removeRow(modelRow);
}
};
ButtonColumn bc = new ButtonColumn(editorTable, delete, 3);
bc.setMnemonic(KeyEvent.VK_D);
}
[/code]
回答1:
It is set automatically in the table renderer and editor from the data in your DefaultTableModel. For example, for the table editor, the code is:
public Component getTableCellEditorComponent(
JTable table, Object value, boolean isSelected, int row, int column) {
...
editButton.setText( value.toString() );
editButton.setIcon( null );
...
}
where value is the value from your table model. See ButtonColumn.java for details.
EDIT: Since you are adding 4 columns, you should probably change your row data to
model.addRow(new Object[]{"DATA1", "DATA2", "DATA3", "DELETE"});
in order to see the delete buttons on the 4th column.
回答2:
MyClass myClass = new MyClass();
jTable1.getColumnModel().getColumn(0).setCellEditor(myClass);
jTable1.getColumnModel().getColumn(0).setCellRenderer(myClass);
class MyClass extends AbstractCellEditor implements TableCellEditor, TableCellRenderer
{
@Override
public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column)
{
JPanel panel=(JPanel)jTable1.getCellRenderer(row, column).getTableCellRendererComponent(table, value, isSelected, isSelected, row, column);
panel.setBackground(table.getSelectionBackground());
return panel;
}
@Override
public Object getCellEditorValue()
{
return null;
}
@Override
public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column)
{
AbstractAction action = new AbstractAction()
{
@Override
public void actionPerformed(ActionEvent e)
{
JOptionPane.showMessageDialog(rootPane,"Row :"+jTable1.getSelectedRow()+" "+ e.getActionCommand() + " clicked");
}
};
JButton button1 = new JButton(action);
JButton button2 = new JButton(action);
button1.setText("Button1");
button2.setText("Button2");
JPanel panel = new JPanel();
panel.add(button1);
panel.add(button2);
panel.setBackground(table.getBackground());
return panel;
}
}
}
来源:https://stackoverflow.com/questions/9321623/adding-button-to-jtable