java-如何在运行时更新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);
}
}

但是按更新按钮后它不会更新.

谁能解决我的问题?

提前致谢..

解决方法:

它不会更新,因为您不修改TableModel中的值.通过在updateData方法中将新的Vector分配给rowOne和rowTwo,您将更改其他Vector实例,然后更改TableModel知道的实例.

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

上一篇:java-在其之前和之后打印带有特定文本的jtable


下一篇:java-在选择JComboBox的列中更改值