Java-方法更改JTable中变量的值(刷新不起作用)

我有一个JTable,其中一个单元格内有一个变量.单击Button时,变量会更改,但JTable中没有任何更改.
这是我的简单示例代码:

public class Test extends JPanel {
static String var = "One";
Object rowData[][] = { { var, "Two", "Three" },
    { "Four", "Five", "Six" } };
Object columnNames[] = { "Column One", "Column Two", "Column Three" };
static JTable table;

static DefaultTableModel tableModel;
JButton button = new JButton("Refresh");
public Test(){
    tableModel = new DefaultTableModel(rowData, columnNames);
    table = new JTable(tableModel);
    add(table);
    button.addActionListener(new Action());
    add(button);
}
private static class Action implements ActionListener {

    @Override
    public void actionPerformed(ActionEvent e) {
        var = "ONE";
        System.out.println(var);
        String[] data = {"ciao"};
        tableModel.fireTableStructureChanged();
    }
}
}

有人能帮助我吗?
谢谢!

解决方法:

您根本不会更改tableModel的数据,因此JTable永远不会更改是有道理的.也许您想在模型上调用setValueAt(…)来更改其单元格之一所保存的值.完成此操作后,无需在模型上调用fireXxxx(…),因为这是(并且应该)由模型本身在内部调用.

啊,我明白你做了什么.您以为通过更改var所引用的String,JTable的数据将发生神奇的变化,但这是一种神奇的思考,因为您所做的只是更改var变量所引用的对象,并且您对该变量完全没有影响.它先前引用的并且正在JTable中显示的String对象.这个问题涉及Java OOP模型的核心概念,即对象和引用变量之间的区别.更改变量引用对其引用的对象没有影响.再次,在模型上调用setValueAt(…)即可解决问题.

例如:

import java.awt.event.*;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;

public class Test extends JPanel {
   static String var = "One";
   Object rowData[][] = { { var, "Two", "Three" }, { "Four", "Five", "Six" } };
   Object columnNames[] = { "Column One", "Column Two", "Column Three" };
   JTable table;

   DefaultTableModel tableModel;
   JButton button = new JButton("Refresh");

   public Test() {
      tableModel = new DefaultTableModel(rowData, columnNames);
      table = new JTable(tableModel);
      add(table);
      button.addActionListener(new Action());
      add(button);
   }

   private class Action implements ActionListener {

      @Override
      public void actionPerformed(ActionEvent e) {
         String var2 = "ONE";
         System.out.println(var2);
         // String[] data = { "ciao" };
         // tableModel.fireTableStructureChanged();

         tableModel.setValueAt(var2, 0, 0);
      }
   }

   private static void createAndShowGui() {
      JFrame frame = new JFrame("Test");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(new Test());
      frame.pack();
      frame.setLocationRelativeTo(null);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}
上一篇:HTTP详解教程 / HTTP 响应头信息 HTTP 响应头信息


下一篇:Silverlight形状、画笔、变换、图像处理、几何图形