This example shows how to configure a JTable in a Java Swing form (SupplierForm) with:
- Custom
DefaultTableModel - Editable columns
- ComboBox in a specific column
public SupplierForm() {
this.supplierService = new SupplierService();
initComponents();
// Create a separate table model
DefaultTableModel supplierTableModel = new DefaultTableModel(
new Object[][]{
{null, null, null, null},
{null, null, null, null},
{null, null, null, null},
{null, null, null, null}
},
new String[]{"Supplier Code", "Name", "Phone", "Address"}
) {
boolean[] canEdit = {false, true, false, false};
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return canEdit[columnIndex];
}
};
jTableSupplier.setModel(supplierTableModel);
// Set ComboBox for the "Name" column
String[] suppliers = {"Supplier A", "Supplier B", "Supplier C"};
JComboBox<String> comboBox = new JComboBox<>(suppliers);
jTableSupplier.getColumnModel().getColumn(1)
.setCellEditor(new DefaultCellEditor(comboBox));
}-
NetBeans Preview Limitation
- Design view cannot render anonymous classes or custom editors.
- Preview may appear grey or empty, but runtime works fine.
-
DefaultCellEditor Restriction
- Only accepts input components:
JTextField,JComboBox,JCheckBox
- Non-input components like
JButtoncannot be used directly.
- Only accepts input components:
-
Using Buttons in JTable
- Requires a custom TableCellRenderer (to display button) and TableCellEditor (to handle click events).
-
Model Separation
- Assigning the model to a variable makes it easier to manipulate rows (insert/delete).
- Always set custom models/editors after
initComponents().
-
Editable Columns
- Control column editability using a
boolean[] canEditarray.
- Control column editability using a