0

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);
2

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks dude. I tried to look a built in method for doing above task. But this is also working for me.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.