Question

Can you help me to make this piece of code workable? I have created a table which change its data each time a function is triggered. The code is composed of three classes.

Table Model

public class MyTableModel extends AbstractTableModel {


private static final long serialVersionUID = 1L;

private static String[] header = {"A", "B","C", "so on"};


public MyTableModel(){

}

RecordingList data = new RecordingList();

public void addData(RecordingList dataIn) {
    data=dataIn;
    this.fireTableDataChanged();

    }

@Override
public int getColumnCount() {
    return header.length; //length;
}

@Override
public int getRowCount() {
    return data.size();

}

@Override
public String getColumnName(int col) {
    return header[col];
}

@Override
public String getValueAt(int row, int col)
{
    Object[] rowSelected = data.getRecordingRow(row);

    return rowSelected[col].toString();

}

}

JTable

 public class DynamicTable extends JTable implements TableModelListener{

/**
 * 
 */
MyTableModel model;

private static final long serialVersionUID = 1L;

public DynamicTable() {

    model = new MyTableModel();
    initialize();

}

void initialize(){


        setFillsViewportHeight(true);
        setModel(model);
        getModel().addTableModelListener(this);
        setForeground(Color.BLACK);
        setShowGrid(true);
        setShowVerticalLines(true);
        setBackground(Color.WHITE);

        try {
            // 1.6+
            setAutoCreateRowSorter(true);
        } catch(Exception continuewithNoSort) {
    }
}
public void tableChanged(TableModelEvent e) {

    TableModel newModel = (TableModel)e.getSource();
    model=(MyTableModel)newModel;
    setModel(model);

    // Do something with the data...
}
}

Finally I have implemented a Third class which needs to update the table and the model

This is obviously a really WRONG approach and I put it here to give you an understanding of what I am trying to achieve:

   RecordingList recordingList = cr.getResultQuery();

            MyTableModel newModel = new MyTableModel();
            newModel.addData(recordingList);

            TableModelEvent event= new TableModelEvent(newModel);

            DynamicTable dt =new DynamicTable() ;
            dt.tableChanged(event);
Was it helpful?

Solution

You would create your new MyTableModel object, and then simply use it to set the currently displayed JTable's model. That's it. The key is getting the reference to the currently displayed JTable, and doing that will all depend on your code structure and what references you've passed where.

I'm not sure what you're trying to achieve with the TableModelEvent, but this is not needed.

If this answer is insufficient, then you will need to create and post your minimal, compilable, runnable example program so that we can better understand your problem.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top