Reputation: 13
I have two tables, and I'm trying to add the data from a record in one table to another table when that record is clicked on.
Currently when I click on the table the values are added to the clickedData but this data doesn't refresh in the table.
Here is my code:
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.util.*;
class TableTest extends JPanel {
JTable tbl1, tbl2;
GridBagConstraints gc = new GridBagConstraints();
public TableTest(){
this.setLayout(new GridBagLayout());
gc.insets = new Insets(10, 10, 10, 30);
Object[][] data = new Object[100][2];
Object[][] clickedData = new Object[100][2];
String[] columnNames = {"X", "Y"};
//Initialise tables
tbl1 = new JTable(data,columnNames);
DefaultTableModel model = new DefaultTableModel(data, columnNames);
DefaultTableModel myModel = new DefaultTableModel(data,columnNames){
public boolean isCellEditable(int row, int column){
return false;
}
};
tbl1.setModel(myModel);
DefaultTableModel model2 = new DefaultTableModel(clickedData,columnNames);
tbl2 = new JTable(model2);
DefaultTableModel myModel2 = new DefaultTableModel(clickedData,columnNames){
public boolean isCellEditable(int row, int column){
return false;
}
};
//Update Table Data
tbl1.addMouseListener(new java.awt.event.MouseAdapter(){
public void mouseClicked(java.awt.event.MouseEvent evt){
int row = tbl1.rowAtPoint(evt.getPoint());
int col = tbl1.columnAtPoint(evt.getPoint());
//basket[0] = row;
clickedData[0][0] = tbl1.getValueAt(row,col);
clickedData[0][1] = tbl1.getValueAt(row,col+1);
//use fireTableDatachanged
model2.fireTableDataChanged();
}
});
initLayout(0,0,tbl1);
initLayout(3,0,tbl2);
}
public void initLayout(int xlayout, int ylayout, JComponent component){
gc.gridx = xlayout;
gc.gridy = ylayout;
this.add(component,gc);
}
}
Upvotes: 1
Views: 1348
Reputation: 205855
Because DefaultTableModel
uses convertToVector()
internally, updating the clickedData
array used to create model2
does not change the content of the model's dataVector
. As a result, fireTableDataChanged()
notifies the listening JTable
, but the model has not changed in the interim. Instead, update model2
via setValueAt()
, which will fire the correct event for you. A similar problem is examined here.
Also consider using a ListSelectionListener
instead of a MouseListener
.
Upvotes: 1