Question

So here's the thing. I have a JTable in my frame displaying some data that can be edited. New rows can be added, old rows can be removed.

Now, if I start with a table populated with some data, it works fine. I'm able to delete rows, and that also deletes the rows from my data Vector<Vector>. However, when I add a row, the row is shown in my table, but the change is not reflected in the data.

Vector<Object> newQuestion = new Vector<Object>(3, 1);
newQuestion.add(question.getText());
newQuestion.add(answer.getText());
newQuestion.add(false);
model.addRow(newQuestion); // Update the model with new question

model is a DefaultTableModel. I tried model.fireTableDataChanged(); even though DTM fires that by itself, however that didn't work either.

Any pointers?

EDIT: What's interesting is, that if I start with some data in the table, and add a row, the change is reflected in the data as well.

EDIT 2: https://github.com/thekarangoel/YALT/blob/master/src/editDB.java From line 65 is what adds a row! To try, compile, run, File > Add new Database. Give a name. Add New Row.

EDIT 3: For this code: System.out.println("Data: " + data); Vector> modelData = model.getDataVector(); System.out.println("Data: " + modelData);

I get this:

Data: null
Data: [[w, a, false]]

The first if data from my Vector. The second is data in the Vector of `model. Why is this happening? When I add something to existing table, the file line also shows the change.

Was it helpful?

Solution

Look at how you create the data:

public Vector<Vector<Object>> convertMapToVector(Map<String, String> quesToAnsMap) {
    if (quesToAnsMap.size() > 0) {
        // the data field is initialized here
        data = new Vector<Vector<Object>>(quesToAnsMap.size(), 1); 
        ...
        return data;
    }
    // but not here
    return new Vector<Vector<Object>>();
}

My advices to make the code more robust:

  • don't use a data field. It's not useful since the data is contained in the model already. So, to get the data, you just need to get it from the model.
  • either make all your method take arguments and return values, or not take anything, return void, and initialize fields, but mixing both is confusing. The method above initializes a field and returns it, but the else clause only returns it without initializing it.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top