使用fireTableDataChanged更新表数据

时间:2017-05-03 17:52:40

标签: java swing jtable

我有两个表,我试图在点击该记录时将一个表中的记录中的数据添加到另一个表中。

目前,当我点击表格时,会将值添加到clickedData,但此数据不会在表格中刷新。

这是我的代码:

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

1 个答案:

答案 0 :(得分:1)

由于DefaultTableModel在内部使用convertToVector(),因此更新用于创建clickedData的{​​{1}}数组不会更改模型model2的内容。因此,dataVector会通知收听fireTableDataChanged(),但模型在此期间未发生变化。相反,请通过JTable更新model2,这将为您触发正确的事件。审查了类似的问题here

另请考虑使用ListSelectionListener代替setValueAt()