【问题标题】:JTable's setValueAt() method is not updating cell dataJTable 的 setValueAt() 方法不更新单元格数据
【发布时间】:2014-01-05 20:33:30
【问题描述】:

我使用抽象表模型创建了一个 JTable。该表有一个二维整数对象数据数组和一个一维列标题。一切正常,除非我在程序运行时编辑和更改单元格数据,它恢复为默认值(使用 getValueAt() 创建)。我已经实现了抽象表模型 setValueAt() 方法,但它不起作用。

谁能告诉我我的代码有什么问题?

    import javax.swing.table.AbstractTableModel;

    public class TableModel1 extends AbstractTableModel {
    /**
     * 
     */
    private static final long serialVersionUID = 1L;


    String [] colNames=new String[30];  
    Object[][] data= new Integer[4][30];            


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

    @Override
    public int getRowCount() {
        return 4;  
    }


    public String getColumnName(int col){

        if (col==0){
            colNames[0]="Boarders";
            }

        else if(col>0){
            for(int i=1;i<colNames.length;i++){
                 colNames[i]=new String(""+i);
            }
        }
    return colNames[col];
    }


    @Override
    public Object getValueAt(int row, int col) {


        for(int i=0; i<data.length;i++){
            for(int j=0; j<data[i].length;j++){
                data[i][j]=new Integer(1);
                 }
                     }
        return data[row][col];
    }  


    public Class getColumnClass(int c) {            
          return getValueAt(0, c).getClass();
        }


    public boolean isCellEditable(int row, int col){
        return true;
    }

    public void  setValueAt (Object aValue, int row, int col){

            data[row][col]=(Integer)aValue;
        fireTableCellUpdated(row,col);

    }

 }//end class

【问题讨论】:

  • 请注意:在我的情况下,我在 windowActivated 事件中再次填写表格。所以它用加载时间数据覆盖了我的数据。请使用正确的事件,现在我使用了“formWindowOpened”事件。

标签: java swing jtable


【解决方案1】:

似乎发生这种情况是因为当getValueAt() 方法调用时,您总是用下一行刷新数组中的数据:

for(int i=0; i<data.length;i++){
        for(int j=0; j<data[i].length;j++){
            data[i][j]=new Integer(1);
        }
}

因此,请从 getValueAt() 方法中删除这行,并在模型的构造函数中初始化您的数组一次,而不是像现在这样每次都初始化。

【讨论】:

    【解决方案2】:

    问题出在 getValueAt 中。这些方法不断被调用。它不是一次性的。在表模型之外启动值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-29
      • 2011-12-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多