JTable Java Error Stack OverFlow when setvalue to

2019-03-02 12:11发布

问题:

This is my Code below. I have created a Jtable with 4 column and 3 rows. and add table model listener, In the Table change Listener, When i set the value in a particular column Stack Overflow error is coming.

**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)**

code is:

package test;

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);

    }
}

回答1:

JTable#setValueAt will call TableModel#setValueAt, which will trigger a TableChanged event, which is why it's causing you a StackOverflowException (it's caught in an infinite loop)

The better solution would be to override the TableModel#setValueAt and if the column 0, 1 or 2 is updated, also calculate the value for column 3, but don't forget to fire a cellUpdated event