Reputation: 110
I've created a JTable using following way. This table has 5 columns and 4 rows. All 4 rows are empty in this status.
String[] columns = {"Emplotee ID","Name","Address","City","Salary"};
//Table that already have 4 empty rows
DefaultTableModel model = new DefaultTableModel(columns,4);
JTable detail = new JTable(model);
JScrollPane scroll = new JScrollPane(detail);
Now I want to add values into those empty rows using String array. The GUI of this program has 5 JTextFields to get user input. When I enter values into JTextFileds and click Add button, all JTextFiled values get by String array named values.
String[] values = new String[6];
//When click addButton all textFiled data should go into table
addButton.addMouseListener(new MouseAdapter(){
@Override
public void mouseClicked(MouseEvent evt){
values[0] = idField.getText(); //get JTextFields data into array
values[1] = nameField.getText();
values[2] = addressField.getText();
values[3] = cityField.getText();
values[4] = salaryField.getText();
//What now?
}
});
I know I can use this to add new row into the table. But this is not the feature what I want.
DefaultTableModel newModel = (DefaultTableModel)detail.getModel();
newModel.addRow(values);
Upvotes: 0
Views: 4725
Reputation: 4592
Set contents of an existing table row with:
int row;
....
// make sure row is set to index of the table row
// you want to populate
for (int c=0; c<values.length; ++c)
detail.setValueAt(values[c], row, c);
TableModel
also has setValueAt
method, if you prefer.
Upvotes: 1