We can dynamically add rows to a JTable when clicking on “+ Add” button. To add rows dynamically in a JTable, we have used the method addRow().
Load the data from the database... String sql="SELECT * FROM hwList"; ResultSet rs = st. executeQuery(sql); Add each row of data to the table model...
Here, Type indicates the type of an arraylist. For example, // create Integer type arraylist ArrayList<Integer> arrayList = new ArrayList<>(); // create String type arraylist ArrayList<String> arrayList = new ArrayList<>(); In the above program, we have used Integer not int.
We can remove a selected row from a JTable using the removeRow() method of the DefaultTableModel class.
I want to add the row dynamically in JTable and I have writen the following code for that:
tblTaskList = new JTable();
tblTaskList.setShowVerticalLines(false);
tblTaskList.setCellSelectionEnabled(true);
tblTaskList.setColumnSelectionAllowed(true);
tblTaskList.setBorder(new LineBorder(null));
for (int count = 1; count <= 10; count++) {
tblTaskList.setModel(new DefaultTableModel(new Object[][] { {
count, "title1", "start", "stop", "pause", "status" }, },
new String[] { "status", "Task Title", "Start", "Stop",
"Pause", "Status" }));
}
tblTaskList.getColumnModel().getColumn(0).setPreferredWidth(31);
tblTaskList.getColumnModel().getColumn(1).setPreferredWidth(346);
tblTaskList.getColumnModel().getColumn(2).setPreferredWidth(33);
tblTaskList.getColumnModel().getColumn(3).setPreferredWidth(31);
tblTaskList.getColumnModel().getColumn(4).setPreferredWidth(28);
tblTaskList.setBounds(93, 34, 614, 160);
frmTaskList.getContentPane().add(tblTaskList);
The problem is that only the last row is added, i.e. count print the value 10 in first column,,,can anyone explain how to solve the problem?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With