将setvalue设置为特定列时的JTable Java错误堆栈溢出

这是我的下面的代码.我创建了一个具有4列3行的Jtable.
并添加表模型侦听器,在表更改侦听器中,当我在特定列中设置值时,将出现堆栈溢出错误.

**error is Exception in thread "AWT-EventQueue-0" java.lang.StackOverflowError
    at java.nio.Buffer.<init>(Buffer.java:189)
    at java.nio.CharBuffer.<init>(CharBuffer.java:276)
    at java.nio.HeapCharBuffer.<init>(HeapCharBuffer.java:70)
    at java.nio.CharBuffer.wrap(CharBuffer.java:369)
    at sun.nio.cs.StreamEncoder.implWrite(StreamEncoder.java:265)**

代码是:

包装测试;

import java.awt.BorderLayout;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

public class TableModelListenerDemo {

    public static void main(String args[]) {

        final Object rowData[][] = {{"1", "one", "I",null}, {"2", "two", "II",null}, {"3", "three", "III",null}};
        final String columnNames[] = {"#", "English", "Roman", "Test"};

        final JTable table = new JTable(rowData, columnNames);
        JScrollPane scrollPane = new JScrollPane(table);
        table.getModel().addTableModelListener(new TableModelListener() {

            @Override
            public void tableChanged(TableModelEvent e) {
                try {
                    System.out.println(e);
                    int row = table.getSelectedRow();
                    Object QTY = table.getValueAt(row, 0);
                    Object UPrice = table.getValueAt(row, 1);
                    Object Three = table.getValueAt(row, 2);
                    table.setValueAt(Three, row, 3);
                }catch(Exception ex){

                }

            }
        });

        table.setValueAt("", 0, 0);
        JFrame frame = new JFrame("Resizing Table");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        frame.add(scrollPane, BorderLayout.CENTER);

        frame.setSize(300, 150);
        frame.setVisible(true);

    }
}
最佳答案
JTable#setValueAt将调用TableModel#setValueAt,这将触发TableChanged事件,这就是为什么它导致您StackOverflowException的原因(陷入无限循环)

更好的解决方案是重写TableModel#setValueAt,并且如果更新了列0、1或2,也要计算列3的值,但是不要忘记触发cellUpdated事件

转载注明原文:将setvalue设置为特定列时的JTable Java错误堆栈溢出 - 代码日志