2012-07-13 54 views
3

我是JTable的新手。如何在运行时更新jtable?

我想在运行时按钮按下事件更新jtable数据。

这是我的代码。

import java.awt.BorderLayout; 
import java.awt.event.ActionEvent; 
import java.awt.event.ActionListener; 
import java.util.Vector; 
import javax.swing.*; 
import javax.swing.JScrollPane; 
import javax.swing.JTable; 
import javax.swing.table.DefaultTableModel; 
public class SetEditableTableCell extends JPanel { 
JPanel top = new JPanel(); 
JPanel bottom = new JPanel(); 
JButton update = new JButton("Update"); 
JTable table; 
Vector<String> rowOne; 
Vector<String> rowTwo; 
DefaultTableModel tablemodel; 
public SetEditableTableCell() { 
    this.setLayout(new BorderLayout()); 
    rowOne = new Vector<String>(); 
    rowOne.addElement("Row1-1"); 
    rowOne.addElement("Row1-2"); 
    rowOne.addElement("Row1-3"); 
    rowTwo = new Vector<String>(); 
    rowTwo.addElement("Row2-2"); 
    rowTwo.addElement("Row2-3"); 
    rowTwo.addElement("Row2-4"); 
    Vector<Vector> rowData = new Vector<Vector>(); 
    rowData.addElement(rowOne); 
    rowData.addElement(rowTwo); 
    Vector<String> columnNames = new Vector<String>(); 
    columnNames.addElement("Column One"); 
    columnNames.addElement("Column Two"); 
    columnNames.addElement("Column Three"); 
    tablemodel = new DefaultTableModel(rowData, columnNames); 
    table = new JTable(tablemodel); 
    // table.setValueAt("aa", 0, 0);  
    update.addActionListener(new ActionListener() { 
     @Override 
     public void actionPerformed(ActionEvent e) { 
      updatedata(); 
     } 
     private void updatedata() { 
      rowOne = new Vector<String>(); 
      rowOne.addElement("updated Row1-1"); 
      rowOne.addElement("updated Row1-2"); 
      rowOne.addElement("updated Row1-3"); 
      rowTwo = new Vector<String>(); 
      rowTwo.addElement("updated Row2-2"); 
      rowTwo.addElement("updated Row2-3"); 
      rowTwo.addElement("updated Row2-4"); 
      // tablemodel.addRow(rowTwo); 
      tablemodel.fireTableDataChanged(); 
      table.setModel(tablemodel); 
      System.out.println("button pressed"); 
      // table.setValueAt("aa", 0, 0);  
     } 
    }); 
    JScrollPane scrollPane = new JScrollPane(table); 
    top.add(scrollPane); 
    bottom.add(update); 
    add(top, BorderLayout.NORTH); 
    add(bottom, BorderLayout.SOUTH); 
} 
public static void main(String args[]) { 
    JFrame frame = new JFrame(); 
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
    SetEditableTableCell obj = new SetEditableTableCell(); 
    frame.add(obj); 
    //frame.setSize(400, 300); 
    frame.pack(); 
    frame.setVisible(true); 
} 
} 

但按下更新按钮后没有更新。

任何人都可以解决我的问题吗?

在此先感谢..

回答

3

它没有更新,因为你不修改您的TableModel值。通过在您的updateData方法中指定一个新的VectorrowOnerowTwo,您正在修改其他Vector实例,然后是您的TableModel知道的实例。

一个可能的解决方案是重建数据向量,并使用setDataVector方法

+0

是的,它得到更新。它会附加以前的数据。但我想用新的价值取代旧的价值观。这怎么可能? – 2012-07-21 07:36:47

0

使用AbstractTableModel上构建自己的表格模型,并用它的“事件”触发将更改通知JTable的底层模型