Java editable jtable example
In Java, you can create an editable JTable
component by setting the editable
property of the DefaultTableModel
to true
.
Here's an example that demonstrates how to create an editable JTable
:
import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.table.DefaultTableModel; public class EditableTableExample { public static void main(String[] args) { String[] columnNames = {"Name", "Age", "Gender"}; Object[][] rowData = { {"Alice", 25, "Female"}, {"Bob", 30, "Male"}, {"Charlie", 35, "Male"} }; DefaultTableModel model = new DefaultTableModel(rowData, columnNames); JTable table = new JTable(model); table.setEnabled(true); table.setEditable(true); JScrollPane scrollPane = new JScrollPane(table); JPanel panel = new JPanel(); panel.add(scrollPane); JFrame frame = new JFrame(); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.add(panel); frame.pack(); frame.setVisible(true); } }
In this example, we create a JTable
by using a DefaultTableModel
that contains the data and column names for the table. We then set the editable
property of the table to true
using the setEditable()
method.
Finally, we create a JScrollPane
to hold the JTable
, add it to a JPanel
, and then add the panel to a JFrame
to display the table.
Once the table is created, you can edit its contents by double-clicking on a cell and typing in a new value. You can also programmatically modify the data in the table by calling the appropriate methods on the DefaultTableModel
instance.