How to add row in 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
How to add a row in Jtable
"Kindly tell me how take out file reading stuff from the model"
In your model, you have two Vectors
, one for the data, and one for the columns. Read the data to the vectors, then just create a DefaultTableModel
with them. Though what may be messing you up, is that for the data you are using a single Vector
for the data. The data should be two dimensional, so you would want a Vector<Vector>
, just like if you were to use arrays for the data, it would be Object[][] data
. So you may want to change your implementation to something like
Vector<Vector> data = new Vector<>();
Vector<String> columnName = new Vector();
...
while ((line = reader.nextLine()) != null) {
Vector row = new Vector();
// tokenize and add the `row`
data.add(row);
}
DefaultTableModel model = new DefaultTableModel(data, columnsNames);
JTable table = new JTable(model);
See the DefaultTableModel API documentation for more methods you can use to manipulate the data.
Here's a simple example
import java.util.Vector;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
public class StackoverflowStuff {
public static void main(String[] args) {
Vector<Vector> data = new Vector<>();
Vector<String> columnNames = new Vector<>();
final int rows = 10;
final int columns = 4;
for (int i = 0; i < columns; i++) {
columnNames.add("Col");
}
for (int i = 0; i < rows; i++) {
Vector row = new Vector();
for (int j = 0; j < columns; j++) {
row.add(j);
}
data.add(row);
}
DefaultTableModel model = new DefaultTableModel(data, columnNames);
JTable table = new JTable(model);
table.setPreferredScrollableViewportSize(table.getPreferredSize());
JOptionPane.showMessageDialog(null, new JScrollPane(table));
}
}
If you later want to add a row to the model, you can simply use the addRow
method of DefaultTableModel
, which is overloaded to accept a Vector
or an Object[]
array
UPDATE
What you are doing is
Vector<Vector> data = new Vector();
while (... ) {
while(...) {
Vector row = new Vector();
String data = ...
row.add(data);
data.add(row);
}
}
You adding a new row for each token, when you should be creating the row vector outside the loop, and adding the tokens inside the loop, then adding the row outside the loop
Vector<Vector> data = new Vector();
while (... ) {
Vector row = new Vector();
while(...) {
String data = ...
row.add(data);
}
data.add(row);
}
How to add row dynamically in JTable
i Have also found one solution for this and it runs successfully
DefaultTableModel dm = new DefaultTableModel(0, 0);
String header[] = new String[] { "Status", "Task Title", "Start",
"Pause", "Stop", "Statulses" };
dm.setColumnIdentifiers(header);
tblTaskList.setModel(dm);
for (int count = 1; count <= 10; count++) {
Vector<Object> data = new Vector<Object>();
data.add(count);
data.add("Project Title" + count);
data.add("Start");
data.add("Stop");
data.add("Pause");
data.add("Status");
System.out.println("test :- " + count);
dm.addRow(data);
}
Adding a Row in a Jtable with AbstractTableModel
How can i add a row in this code properly ?
You need to re-do your model. Currently you're hard-coding the data in fixed-sized arrays which will hamstring your ability to add data. Instead:
- Use a
List<RowType>
for the nucleus of your model, not a 2-d array of object. Note that RowType is a class that you create that holds all the data held in a row. - Use this RowType to easily get and set items from each cell. This means changing your getValueAt and setValue at methods to accommodate your RowType objects.
- Give your model an
public void addRow(RowType rowData)
method that allows you to add a new object to the list. You can't use DefaultTableModel's method since your model doesn't extend this, and so you will have to write you're own. - Inside this method, call the appropriate
fireXxxx(...)
method of the super class.
Alternatively: don't have your model extend AbstractTableModel but rather have it extend DefaultTableModel and use its methods. If you go this route, you'd not have your class hold a 2D array but rather would use the Default's own data nucleus, one that you can fill and modify via the Default's super constructors and methods. You'd also do well to create an addRow method overload, one that accepts a parameter of class RowType
For example assuming a RowData class with fields and setters and getters to match the columns, you could extend DefaultTableModel to look something like this:
public class MyTableModel extends DefaultTableModel {
public static final String[] COLUMN_NAMES = { "name", "cc", "age", "phone", "date", "amount" };
public MyTableModel() {
super(COLUMN_NAMES, 0);
}
@Override
public Class<?> getColumnClass(int columnIndex) {
if (getRowCount() > 0 && getValueAt(0, columnIndex) != null) {
return getValueAt(0, columnIndex).getClass();
}
return super.getColumnClass(columnIndex);
}
public void addRow(RowData rowData) {
if (rowData == null) {
throw new IllegalArgumentException("rowData cannot be null");
}
Vector<Object> rowVector = new Vector<>();
rowVector.add(rowData.getName());
rowVector.add(rowData.getCc());
rowVector.add(rowData.getAge());
rowVector.add(rowData.getPhone());
rowVector.add(rowData.getDate());
rowVector.add(rowData.getAmount());
rowVector.add(rowData.getCc());
super.addRow(rowVector);
}
// TODO: methods to return a row as a RowData object
}
Then you could use either the super's addRow(Vector data)
method or your overload above.
JTable How to add a row between rows
Use a DefaultTableModel
<- see docs more contructors
DefaultTableModel model = new DefualtTableModel(String colNames, int rows);
JTable table = new JTable(model);
Then you can use one of the following methods
DefaultTableModel#insertRow(int row, Object[] rowData)
- Inserts a row at row in the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
Or
DefaultTableModel#insertRow(int row, Vector rowData)
- Inserts a row at row in the model. The new row will contain null values unless rowData is specified. Notification of the row being added will be generated.
How do I insert a row of data into JTable?
Okay, I followed - camickr .
Solved quite nicely thank you. Very informative.
This code is the what was intended. (almost)
/**
* A basic 3x3 JTable within JFrame inserting data from top row
*/
public class TestCode {
private DefaultTableModel tm;
// Insert at row zero and push other row by one row
// and remove row three
public void insertRowZero() {
tm.insertRow(0, new Object[]{"numone", "numtwo", "numthree"});
tm.removeRow(3);
}
// Create a fixed size table, 3 row and 3 column
public void createTable() {
tm = new DefaultTableModel();
JTable table = new JTable(tm);
tm.addColumn("x");
tm.addColumn("y");
tm.addColumn("z");
tm.insertRow(0, new Object[]{"r0-c0", "r0-c1", "r0-c2"});
tm.insertRow(1, new Object[]{"r1-c0", "r1-c1", "r1-c2"});
tm.insertRow(2, new Object[]{"r2-c0", "r2-c1", "r2-c2"});
JFrame frame = new JFrame();
frame.setSize(300, 100);
frame.add(table);
frame.add(new JScrollPane(table)); // needed to show column header
frame.setVisible(true); // don't really want scroll pane
try {
Thread.sleep(2000);
} catch (InterruptedException ex) {
Logger.getLogger(TestCode.class.getName()).log(Level.SEVERE, null, ex);
}
}
public TestCode() {
// construct
createTable();
insertRowZero();
}
public static void main(String[] args) {
// just a start point
new TestCode();
}
}
Insert a new row in jTable automatically while entering data in the last row
You could try it with a TableModelListener
. Basic idea: you get notified, whenever a cell was edited. You can then check if the cell was in the last row, and if it was, add a new row to the table.
DefaultTableModel tableModel = new DefaultTableModel();
JTable table = new JTable(tableModel);
tableModel.addTableModelListener(new TableModelListener() {
@Override
public void tableChanged(TableModelEvent e) {
if ((e.getLastRow() + 1) == tableModel.getRowCount()) {
// something was entered into the last row, add a new row
}
}
});
Related Topics
How to Exclude Some Concrete Urls from <Url-Pattern> Inside <Filter-Mapping>
How to Load Rsa Private Key from File
How to Interrupt a Serversocket Accept() Method
Should I Keep My Project Files Under Version Control
Hibernate Criteria Returns Children Multiple Times with Fetchtype.Eager
Who Sets Response Content-Type in Spring MVC (@Responsebody)
Junit: How to Simulate System.In Testing
Can a Java Class Add a Method to Itself at Runtime
How to Move My Jmenubar to the Screen Menu Bar on MAC Os X
How to Mark Jtable Cell Input as Invalid
Is Java.Sql.Connection Thread Safe
How to Generate a Random Biginteger Value in Java
Log4J Does Not Recreate Files on Deletion
Loading Resources Using Getclass().Getresource()
How to Execute Linux Commands on a Remote MAChine Using Java