Adding a button to jtable

I searched for tutorials to add a button in jtable and found a class file from http://tips4java.wordpress.com/2009/07/12/table-button-column/ Where can I set a 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] 
+3
source share
2 answers

It is installed automatically in the table renderer and editor from the data in your DefaultTableModel. For example, for the table editor, the code:

 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 more details.

EDIT: since you are adding 4 columns, you should probably change the row data to

 model.addRow(new Object[]{"DATA1", "DATA2", "DATA3", "DELETE"}); 

to see the delete buttons in the 4th column.

+4
source
  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; } } 

}

-1
source

All Articles