Do you know how I can add a new row to a jTable
?
The TableModel
behind the JTable handles all of the data behind the table. In order to add and remove rows from a table, you need to use a DefaultTableModel
To create the table with this model:
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}));
To add a row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3"});
You can also remove rows with this method.
Full details on the DefaultTableModel can be found here
JTable table = new JTable(new DefaultTableModel(new Object[]{"Column1", "Column2"}, 20));
–
Wadding Use:
DefaultTableModel model = new DefaultTableModel();
JTable table = new JTable(model);
// Create a couple of columns
model.addColumn("Col1");
model.addColumn("Col2");
// Append a row
model.addRow(new Object[]{"v1", "v2"});
To add row to JTable
, one of the ways is:
1) Create table using DefaultTableModel:
DefaultTableModel model = new DefaultTableModel();
model.addColumn("Code");
model.addColumn("Name");
model.addColumn("Quantity");
model.addColumn("Unit Price");
model.addColumn("Price");
JTable table = new JTable(model);
2) To add row:
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.addRow(new Object[]{"Column 1", "Column 2", "Column 3","Column 4","Column 5"});
Use
DefaultTableModel model = (DefaultTableModel) MyJTable.getModel();
Vector row = new Vector();
row.add("Enter data to column 1");
row.add("Enter data to column 2");
row.add("Enter data to column 3");
model.addRow(row);
get the model with DefaultTableModel modelName = (DefaultTableModel) JTabelName.getModel();
Create a Vector with Vector vectorName = new Vector();
add so many row.add
as comumns
add soon just add it with modelName.addRow(Vector name);
For the sake of completeness, first make sure you have the correct import so you can use the addRow
function:
import javax.swing.table.*;
Assuming your jTable is already created, you can proceed and create your own add row method which will accept the parameters that you need:
public void yourAddRow(String str1, String str2, String str3){
DefaultTableModel yourModel = (DefaultTableModel) yourJTable.getModel();
yourModel.addRow(new Object[]{str1, str2, str3});
}
© 2022 - 2024 — McMap. All rights reserved.