我有一个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();
}
}
}
是的,有人能帮帮我吗?
谢谢!
答案 0 :(得分:3)
您根本不会更改tableModel的数据,因此JTable永远不会改变。也许你想在模型上调用setValueAt(...)
来改变其中一个单元格所持有的值。执行此操作后,无需在模型上调用fireXxxx(...)
,因为模型本身(并且应该)在内部调用 。
var
引用的字符串,JTable的数据会神奇地改变,但这是神奇的思考,因为您所做的只是更改var
变量引用的对象而您'对它之前引用的String对象完全没有影响,并且它正在JTable中显示。这个问题涉及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();
}
});
}
}