How to Add JSpinner to JTable
In this tutorial, we are going to see how to add JSpinner to a JTable. JTable is a flexible Swing component, is a subclass of JComponent class and it can be used to create a table with information displayed in multiple rows and columns. We can insert JSpinner into a JTable by customizing the code by inheriting DefaultCellEditor class and we need to redefine the method getTableCellEditorComponent().
Java Program to Add JSpinner to JTable:
import java.awt.*; import java.awt.event.*; import java.util.*; import javax.swing.*; import javax.swing.JSpinner.DefaultEditor; import javax.swing.table.*; public class Main { //JTable Header static String[] columns = { "Product", "Quantity" }; //JTable data in a 2D table static Object[][] data = { { "Computer", 12 }, { "Keyboard", 20 }, { "Mouse", 30 }, { "Printer", 6 }, { "Scanner", 10 }, }; public static void main( String[] args ) { //create a frame JFrame f = new JFrame(); //create a JTable JTable table = new JTable(data, columns); JScrollPane scrollPane = new JScrollPane(table); //get the column model from JTable TableColumnModel model = table.getColumnModel(); //get the 2nd column TableColumn col = model.getColumn(1); //set the editor col.setCellEditor(new MySpinnerEditor()); f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); f.add(scrollPane); f.setSize(200, 150); f.setVisible(true); } public static class MySpinnerEditor extends DefaultCellEditor { JSpinner sp; DefaultEditor defaultEditor; JTextField text; // Initialize the spinner public MySpinnerEditor() { super(new JTextField()); sp = new JSpinner(); defaultEditor = ((DefaultEditor)sp.getEditor()); text = defaultEditor.getTextField(); } // Prepare the spinner component and return it public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { sp.setValue(value); return sp; } // Returns the current value of the spinners public Object getCellEditorValue() { return sp.getValue(); } } }
Output: