Java JTable With Custom Columns

How to Create a JTable with Custom Columns In Java Netbeans

Create JTable With RadioButton, CheckBox, ComboBox, Spinner, TextField and Button Columns In Java Netbeans


In this Java Tutorial we will see How To Create a JTable with custom components in each cell. The table has six columns: RadioButton, CheckBox, ComboBox, Spinner, TextField, and Button.
For each column in the table, custom renderers and editors are set using the setColumnRendererAndEditor method. 
This method associates a TableCellRenderer (for rendering cell content) and a TableCellEditor (for editing cell content) with a specific column in the table.
The getJobList Method: Returns an array of job titles. This array is used to populate the ComboBox in the third column.

What We Are Gonna Use In This Project:

- Java Programming Language.
- NetBeans Editor.






Project Source Code:

RadioButtonRenderer Class:

public class RadioButtonRenderer extends JRadioButton implements TableCellRenderer{

    public RadioButtonRenderer(){
        setHorizontalAlignment(SwingConstants.CENTER);
        setOpaque(false);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        setSelected(value != null && (boolean)value);
        return this;
    
    }

}


RadioButtonEditor Class:

public class RadioButtonEditor extends AbstractCellEditor implements TableCellEditor{

    private final JRadioButton button;
    
    public RadioButtonEditor(){
        button = new JRadioButton();
        button.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the radiobutton
        return button.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        button.setSelected(value != null && (boolean)value);
        return button;
        
    }

    
}


JTable With RadioButton Column





CheckBoxRenderer Class:

public class CheckBoxRenderer extends DefaultTableCellRenderer{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxRenderer(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected state based on the value
        checkBox.setSelected(value != null && (boolean)value);
        return checkBox;
    
    }
    
}


CheckBoxEditor Class:

public class CheckBoxEditor extends AbstractCellEditor implements TableCellEditor{

    private final JCheckBox checkBox = new JCheckBox();
    
    public CheckBoxEditor(){
        checkBox.setHorizontalAlignment(SwingConstants.CENTER);
    }
    
    @Override
    public Object getCellEditorValue() {
    
        // retun the value of the checkbox
        return checkBox.isSelected();
        
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
    
        // Set the selected state based on the value
        checkBox.setSelected((boolean)value);
        return checkBox;
        
    }
    
}


JTable With CheckBox Column





ComboboxRenderer Class:

public class ComboboxRenderer extends JComboBox<String> implements TableCellRenderer{

    public ComboboxRenderer(String[] items){ super(items); }
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
     
        // Set the selected item in the JComboBox based on the cell value
        setSelectedItem(value);
        
        // Ensure the JComboBox is focused before rendering
        if(hasFocus){ requestFocusInWindow(); } 
        
        return this;
    }

}



ComboboxEditor Class:

public class ComboboxEditor extends DefaultCellEditor{

    public ComboboxEditor(String[] items){ 
        super(new JComboBox<>(items)); 
        // Set the number of clicks needed to start editing
        setClickCountToStart(0);
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
     
         // Set the selected item in the JComboBox based on the cell value
         ((JComboBox<?>) editorComponent).setSelectedItem(value);
         
         // Ensure the JComboBox is focused before editing
         SwingUtilities.invokeLater(() -> {
             ((JComboBox<?>) editorComponent).requestFocusInWindow();
         });
        
         return editorComponent;
    }
    
    
    @Override
    public Object getCellEditorValue(){
        // Return the selected item from the JComboBox
        return ((JComboBox<?>) editorComponent).getSelectedItem();
    }
  
}


JTable With ComboBox Column





SpinnerRenderer Class:

public class SpinnerRenderer extends JSpinner implements TableCellRenderer{
    
    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // set value of the spinner
        setValue(value);
        return this;
    
    }

}



SpinnerEditor Class:

public class SpinnerEditor extends DefaultCellEditor{

    public SpinnerEditor(JSpinner spinner) {
        // Initialize the spinner editor
        super(new JCheckBox());
        editorComponent = spinner;
        delegate = new EditorDelegate() {
            
            // Set the value of the spinner
            @Override
            public void setValue(Object value){spinner.setValue(value);}
            
            // Get the value of the spinner
            @Override
            public Object getCellEditorValue(){ return spinner.getValue(); }
            
        };
    }
 
}



JTable With Spinner Column





TextFieldRenderer Class:

public class TextFieldRenderer extends JTextField implements TableCellRenderer{

    public TextFieldRenderer(){setHorizontalAlignment(JTextField.CENTER);}

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
      
        // Set the text of the text field
        setText(value != null ? value.toString() : "");
        return this;
        
    }
    
}



JTable With TextField Column





ButtonRenderer Class:

public class ButtonRenderer extends JButton implements TableCellRenderer{

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    
        // Set the text of the button
        setText(value != null ? value.toString() : "");
        return this;
        
    }

}




ButtonEditor Class:

public class ButtonEditor extends DefaultCellEditor{

    private JButton button;
    
    public ButtonEditor(JCheckBox checkBox) {
        // Initialize the button editor and add action listener for button click
        super(checkBox);
        button = new JButton();
        button.addActionListener((e) -> {
            JOptionPane.showMessageDialog(button, button.getText() + " Clicked");
        });
        
    }
    
    @Override
    public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) {
        // Set the text of the button
        button.setText(value != null ? value.toString() : "");
        return button;        
    }
    
    // Get the text of the button
    @Override
    public Object getCellEditorValue(){ return button.getText(); }

}



JTable With Button Column





CustomTableModel Class:

public class CustomTableModel extends AbstractTableModel{
    private final Object[][] data;
    private final String[] columnNames;
    
    public CustomTableModel(Object[][] data, String[] columnNames){
        this.data = data;
        this.columnNames = columnNames;
    }
    

    @Override
    public int getRowCount() { return data.length; }

    @Override
    public int getColumnCount() { return columnNames.length; }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
    
        return data[rowIndex][columnIndex];
        
    }

    @Override
    public String getColumnName(int column){ return columnNames[column]; }
    
    @Override
    public Class<?> getColumnClass(int column){ return data[0][column].getClass(); }
    
    @Override
    public boolean isCellEditable(int row, int column){ return true; }
    
    @Override
    public void setValueAt(Object value, int row, int column){
        // Update the data and notify listeners of the change
        data[row][column] = value;
        fireTableCellUpdated(row, column);
    }
    
    
}






The MainClass Class:

public class MainClass extends JFrame{

    public MainClass(){
        setTitle("Table Custom Component");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        
        CustomTableModel model = new CustomTableModel(
                new Object[][]{
                        {false, false, "Developer", 1, "Text 1", "Button 1"},
                        {false, true, "Designer", 2, "Text 2", "Button 2"},
                        {true, false, "Manager", 3, "Text 3", "Button 3"},
                        {true, false, "Engineer", 4, "Text 4", "Button 4"}
                },
                new String[]{"RadioButton", "CheckBox", "ComboBox", "Spinner", "TextField", "Button"}
        );
        
        
        JTable table = new JTable(model);
        table.setRowHeight(40);
        
        setColumnRendererAndEditor(table, 0, new RadioButtonRenderer(), new RadioButtonEditor());
        setColumnRendererAndEditor(table, 1, new CheckBoxRenderer(), new CheckBoxEditor());
        setColumnRendererAndEditor(table, 2, new ComboboxRenderer(getJobList()), new ComboboxEditor(getJobList()));
        setColumnRendererAndEditor(table, 3, new SpinnerRenderer(), new SpinnerEditor(new JSpinner()));
        setColumnRendererAndEditor(table, 4, new TextFieldRenderer(), new DefaultCellEditor(new JTextField()));
        setColumnRendererAndEditor(table, 5, new ButtonRenderer(), new ButtonEditor(new JCheckBox()));
        
        
        JScrollPane scrollPanel = new JScrollPane(table);
        add(scrollPanel);
        setSize(600, 400);
        setLocationRelativeTo(null);
        
    }
    
    
    private void setColumnRendererAndEditor(JTable table, int columnIndex, TableCellRenderer renderer, TableCellEditor editor){
        // Set the renderer and editor for a specific column
        table.getColumnModel().getColumn(columnIndex).setCellRenderer(renderer);
        table.getColumnModel().getColumn(columnIndex).setCellEditor(editor);
    }
    
    
    private String[] getJobList(){
        // Return an array of job titles
        // we will use it to populate the combobox
        return new String[]{"Engineer", "Designer", "Manager", "Developer", "Analyst"};
        
    }
    
    
    public static void main(String[] args) {
        MainClass app = new MainClass();
        app.setVisible(true);
    }
    
}



The Final Result:

Java JTable With Custom Columns







Share this

Related Posts

Latest
Previous
Next Post »