Skip to content

Instantly share code, notes, and snippets.

@solanoize
Created November 29, 2025 20:20
Show Gist options
  • Select an option

  • Save solanoize/518938cd0f66000ee77aba2401127bef to your computer and use it in GitHub Desktop.

Select an option

Save solanoize/518938cd0f66000ee77aba2401127bef to your computer and use it in GitHub Desktop.
SupplierForm JTable Example (Java Swing)

This example shows how to configure a JTable in a Java Swing form (SupplierForm) with:

  • Custom DefaultTableModel
  • Editable columns
  • ComboBox in a specific column

Code

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));
}

Key Notes

  1. NetBeans Preview Limitation

    • Design view cannot render anonymous classes or custom editors.
    • Preview may appear grey or empty, but runtime works fine.
  2. DefaultCellEditor Restriction

    • Only accepts input components:
      • JTextField, JComboBox, JCheckBox
    • Non-input components like JButton cannot be used directly.
  3. Using Buttons in JTable

    • Requires a custom TableCellRenderer (to display button) and TableCellEditor (to handle click events).
  4. Model Separation

    • Assigning the model to a variable makes it easier to manipulate rows (insert/delete).
    • Always set custom models/editors after initComponents().
  5. Editable Columns

    • Control column editability using a boolean[] canEdit array.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment