1

I have created the following JTable and some buttons. One of the buttons (jbtClear) is trying to empty the table using the setRowCount() function. Any ideas , why it is not working and produces this error?

Here is the code :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nysemarketpick;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

/**
 *
 * @author Administrator
 */
public class PortfolioForm extends javax.swing.JFrame {

    /**
     * Creates new form PortfolioForm
     */
    public PortfolioForm() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jbtAddRow = new javax.swing.JButton();
        jbtDeleteRow = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jbtSave = new javax.swing.JButton();
        jbtClear = new javax.swing.JButton();
        jbtRestore = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Row functions"));

        jbtAddRow.setText("Add New Row");

        jbtDeleteRow.setText("Delete Selected Row");

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(34, 34, 34)
                        .add(jbtAddRow))
                    .add(jPanel1Layout.createSequentialGroup()
                        .add(16, 16, 16)
                        .add(jbtDeleteRow)))
                .addContainerGap(40, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .add(jbtAddRow)
                .add(18, 18, 18)
                .add(jbtDeleteRow)
                .addContainerGap(26, Short.MAX_VALUE))
        );

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Stock Symbol", "Stock Name", "Shares", "Value (in Dollars)", "Total Value"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.Integer.class, java.lang.Double.class, java.lang.Double.class
            };
            boolean[] canEdit = new boolean [] {
                true, false, true, true, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        tableModel = (DefaultTableModel)jTable1.getModel();
        jTable1.setColumnSelectionAllowed(true);
        jTable1.setRowSelectionAllowed(true);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getSelectionModel().setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        //add action listeners
        jbtAddRow.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                if (jTable1.getSelectedRow() >= 0)
                tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
                else
                tableModel.addRow(new Vector());
            }
        });
        jbtDeleteRow.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                if (jTable1.getSelectedRow() >= 0)
                tableModel.removeRow(jTable1.getSelectedRow());
            }
        });
        jbtSave.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("portfolio.dat"));
                    out.writeObject(tableModel.getDataVector());
                    out.writeObject(getColumnNames());
                    out.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
        jbtClear.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                tableModel.setRowCount(0);
            }
        });
        jbtRestore.addActionListener(new ActionListener(){
            public void actionPerformed(ActionEvent e)
            {
                try
                {
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream("portfolio.dat"));
                    Vector rowData = (Vector)in.readObject();
                    Vector columnNames = (Vector)in.readObject();
                    tableModel.setDataVector(rowData, columnNames);
                    in.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }
        });
        //add other listeners
        tableModel.addTableModelListener(new TableModelListener(){
            public void tableChanged(TableModelEvent e)
            {
                DefaultTableModel model = (DefaultTableModel)e.getSource();
                //Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
                if (e.getColumn() == 0)
                {
                    Object data = model.getValueAt(e.getFirstRow(), e.getColumn());
                    String stockSymbol = (String)data;
                    XMLService2 myService = new XMLService2(stockSymbol);
                    String stockName = XMLService2.getStockName();
                    model.setValueAt(stockName, e.getFirstRow(), e.getColumn() + 1);
                }
                if (e.getColumn() != 4 && model.getValueAt(e.getFirstRow(), 2) != null && model.getValueAt(e.getFirstRow(), 3) != null)
                {
                    Double myDouble =(Integer)model.getValueAt(e.getFirstRow(), 2)*(Double)model.getValueAt(e.getFirstRow(), 3);
                    model.setValueAt(myDouble, e.getFirstRow(), 4);
                }
            }
        });

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Table functions"));

        jbtSave.setText("Save");

        jbtClear.setText("Clear");

        jbtRestore.setText("Restore");

        org.jdesktop.layout.GroupLayout jPanel2Layout = new org.jdesktop.layout.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .add(34, 34, 34)
                .add(jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(jbtRestore)
                    .add(jbtClear)
                    .add(jbtSave))
                .addContainerGap(41, Short.MAX_VALUE))
        );

        jPanel2Layout.linkSize(new java.awt.Component[] {jbtClear, jbtRestore, jbtSave}, org.jdesktop.layout.GroupLayout.HORIZONTAL);

        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .add(jbtSave)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jbtClear)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .add(jbtRestore))
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(layout.createSequentialGroup()
                        .add(21, 21, 21)
                        .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 645, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE))
                    .add(layout.createSequentialGroup()
                        .add(31, 31, 31)
                        .add(jPanel1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                        .add(78, 78, 78)
                        .add(jPanel2, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(50, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .addContainerGap()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 399, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .add(27, 27, 27)
                .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING, false)
                    .add(jPanel1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .add(jPanel2, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new PortfolioForm().setVisible(true);
            }
        });
    }

    //---other methods
    private Vector getColumnNames()
    {
        Vector<String> columnNames = new Vector<String>();
        for (int i = 0; i < jTable1.getColumnCount(); i++)
            columnNames.add(jTable1.getColumnName(i));

        return columnNames;
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private DefaultTableModel tableModel;
    private javax.swing.JButton jbtAddRow;
    private javax.swing.JButton jbtClear;
    private javax.swing.JButton jbtDeleteRow;
    private javax.swing.JButton jbtRestore;
    private javax.swing.JButton jbtSave;
    // End of variables declaration
}

Post edit : Here is working code from a book with the same function :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package projecttable5;

import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.UIManager;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;

/**
 *
 * @author Administrator
 */
public class ModifyTable extends JFrame{

    //Create table column names
    private String[] columnNames = {"Country", "Capital", "Population in Millions", "Democracy"};

    //Create table data
    private Object[][] rowData = {

        {"USA", "Washington DC", 280, true},
        {"Canada", "Ottawa", 32, true},
        {"United Kingdom", "London", 60, true},
        {"Germany", "Berlin", 83, true},
        {"France", "Paris", 60, true},
        {"Norway", "Oslo", 4.5, true},
        {"India", "New Delhi", 1046, true}
    };

    //Create a table model
    private DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames);

    //Create a table
    private JTable jTable1 = new JTable(tableModel);

    //Create buttons
    private JButton jbtAddRow = new JButton("Add New Row");
    private JButton jbtAddColumn = new JButton("Add New Column");
    private JButton jbtDeleteRow = new JButton("Delete Selected Row");
    private JButton jbtDeleteColumn = new JButton("Delete Selected Column");
    private JButton jbtSave = new JButton("Save");
    private JButton jbtClear = new JButton("Clear");
    private JButton jbtRestore = new JButton("Restore");

    //Create a combo box for selection modes
    private JComboBox jcboSelectionMode = new JComboBox(new String[] {"SINGLE_SELECTION", "SINGLE_INTERVAL_SELECTION", "MULTIPLE_INTERVAL_SELECTION"});

    //Create check boxes
    private JCheckBox jchkRowSelectionAllowed = new JCheckBox("RowSelectionAllowed", true);
    private JCheckBox jchkColumnSelectionAllowed = new JCheckBox("ColumnSelectionAllowed", false);


    //---Default constructor
    public ModifyTable()
    {
        JPanel panel1 = new JPanel();
        panel1.setLayout(new GridLayout(2, 2));
        panel1.add(jbtAddRow);
        panel1.add(jbtAddColumn);
        panel1.add(jbtDeleteRow);
        panel1.add(jbtDeleteColumn);

        JPanel panel2 = new JPanel();
        panel2.add(jbtSave);
        panel2.add(jbtClear);
        panel2.add(jbtRestore);

        JPanel panel3 = new JPanel();
        panel3.setLayout(new BorderLayout(5, 0));
        panel3.add(new JLabel("Selection Mode"), BorderLayout.WEST);
        panel3.add(jcboSelectionMode, BorderLayout.CENTER);

        JPanel panel4 = new JPanel();
        panel4.setLayout(new FlowLayout(FlowLayout.LEFT));
        panel4.add(jchkRowSelectionAllowed);
        panel4.add(jchkColumnSelectionAllowed);

        //Gather panel3 and panel4
        JPanel panel5 = new JPanel();
        panel5.setLayout(new GridLayout(2, 1));
        panel5.add(panel3);
        panel5.add(panel4);

        //Gather panel1 and panel2
        JPanel panel6 = new JPanel();
        panel6.setLayout(new BorderLayout());
        panel6.add(panel1, BorderLayout.SOUTH);
        panel6.add(panel2, BorderLayout.CENTER);


        add(panel5, BorderLayout.NORTH);
        add(new JScrollPane(jTable1), BorderLayout.CENTER);
        add(panel6, BorderLayout.SOUTH);

        //Initialize table selection mode
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //Add listeners
        jbtAddRow.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                if (jTable1.getSelectedRow() >= 0)
                    tableModel.insertRow(jTable1.getSelectedRow(), new Vector());
                else
                    tableModel.addRow(new Vector());
            }

        });
        jbtAddColumn.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                String name = JOptionPane.showInputDialog("New Column Name");
                tableModel.addColumn(name, new Vector());
            }

        });
        jbtDeleteRow.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                if (jTable1.getSelectedRow() >= 0)
                    tableModel.removeRow(jTable1.getSelectedRow());
            }

        });
        jbtDeleteColumn.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                if (jTable1.getSelectedColumn() >= 0)
                {
                    TableColumnModel columnModel = jTable1.getColumnModel();
                    TableColumn tableColumn = columnModel.getColumn(jTable1.getSelectedColumn());
                    columnModel.removeColumn(tableColumn);
                }
            }

        });
        jbtSave.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                try
                {
                    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("tablemodel.dat"));
                    out.writeObject(tableModel.getDataVector());
                    out.writeObject(getColumnNames());
                    out.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }

        });
        jbtClear.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                tableModel.setRowCount(0);
            }

        });
        jbtRestore.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                try
                {
                    ObjectInputStream in = new ObjectInputStream(new FileInputStream("tablemodel.dat"));
                    Vector rowData = (Vector)in.readObject();
                    Vector columnNames = (Vector)in.readObject();
                    tableModel.setDataVector(rowData, columnNames);
                    in.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }
            }

        });
        jchkRowSelectionAllowed.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                jTable1.setRowSelectionAllowed(jchkRowSelectionAllowed.isSelected());
            }

        });
        jchkColumnSelectionAllowed.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                jTable1.setColumnSelectionAllowed(jchkColumnSelectionAllowed.isSelected());
            }

        });
        jcboSelectionMode.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                String selectedItem = (String)jcboSelectionMode.getSelectedItem();

                if (selectedItem.equals("SINGLE_SELECTION"))
                    jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
                else if (selectedItem.equals("SINGLE_INTERVAL_SELECTION"))
                    jTable1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
                else if (selectedItem.equals("MULTIPLE_INTERVAL_SELECTION"))
                    jTable1.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
            }

        });

    }//end of default constructor

    private Vector getColumnNames()
    {
        Vector<String> theColumnNames = new Vector<>();

        for (int i = 0; i < jTable1.getColumnCount(); i++)
            theColumnNames.add(jTable1.getColumnName(i));

        return theColumnNames;
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        try
        {
            UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
        }
        catch(Exception e)
        {

        }

        ModifyTable frame = new ModifyTable();
        frame.setLocationRelativeTo(null);  //Center the frame
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setTitle("TableSortFilter");
        frame.pack();
        //frame.setSize(new Dimension(300, 300));
        frame.setVisible(true);
    }
}
skiabox
  • 3,449
  • 12
  • 63
  • 95
  • On which line is the exception thrown? – Sjoerd Sep 11 '12 at 10:56
  • 1
    good start if you know the row :-) From here, try to isolate when/how it happens: first remove all the unrelated stuff from the example (simply use a statically populated model). If the error is still there, it's easy to reproduce (for anybody willing to run your the example, which at that time will be a SSCCE :-) and probably come up with an idea. If the error is not there, add _one additional function at a time_ and see when it re-appears. – kleopatra Sep 11 '12 at 11:13
  • btw: you are [_still_](http://stackoverflow.com/q/12360483/203657) doing something completely wrong (in setting a value in a modelListener) .. wondering why you ask if you are not prepared to learn? – kleopatra Sep 11 '12 at 11:17
  • @kleopatra hmmm I'm lazy to continue (see another 4-5 issues then I deleted answer) answer is simple to [popupating JTable contents from tableModelListener events](http://stackoverflow.com/questions/8099098/why-never-change-the-notifier-in-receiving-a-change-event) – mKorbel Sep 11 '12 at 11:20
  • The code is from the 'Introduction to Java Programming Comprehensive' book and there it is working, so I really don't know why it is not working here. – skiabox Sep 11 '12 at 11:23
  • I can paste here the code of the book guys, if that helps... – skiabox Sep 11 '12 at 11:24
  • @mKorbel not sure I understand what you mean, so repeating myself: the answer is simply to **not** populate a model from its listener :-) – kleopatra Sep 11 '12 at 11:26
  • I just added the book code...see again the original post...hope that helps – skiabox Sep 11 '12 at 11:28
  • 1
    @skiabox TableModelListener is about notifying about the change(s) from TableModel to outside, this way you can to created endless loop with FileIO, that not close() in finally block(possible outofmemoryexception), – mKorbel Sep 11 '12 at 11:29
  • Here is an example that looks exactly like the book code : http://stackoverflow.com/questions/3879610/clear-contents-of-a-jtable – skiabox Sep 11 '12 at 11:32
  • again (as @kleopatra mentioned too) you have got a few issues, ordered by inpact 1) TableModelListener, 2) ListModelListener, 3) How XxxTableModel works 4) lifecycle into XxxTableModel and (react to ) JTables view 5) recude you post to the rellated issue 6) aaach split that to the 3-4 separated questions 7) sure you can waiting, maybe someone has idea – mKorbel Sep 11 '12 at 11:38
  • I am trying now a getRowCount() in the place of setRowCount() to see if the specific part of code sees the rows. – skiabox Sep 11 '12 at 11:41
  • @skiabox did you read my answer in your thread, (I deleted it) – mKorbel Sep 11 '12 at 11:41
  • `I am trying now a getRowCount() in the place of setRowCount()` those are about my points 3 and 4. – mKorbel Sep 11 '12 at 11:43
  • I added two rows and getRowCount() sees them but setRowCount() and iteration with tableModel.removeRow() to remove the rows one by one gives the same error.I believe that it has to do with the DefaultTableModel object initialization inside the table constructor, maybe the listeners are created before the model. – skiabox Sep 11 '12 at 12:03
  • I've added an if (tableModel != null) around the action listener but the error continues... – skiabox Sep 11 '12 at 12:13
  • @mKorbel : My last answer is working fine at all possible situations. please grade it accordingly, thank you. – skiabox Sep 11 '12 at 22:02

2 Answers2

1

If you wish to alter table content, it's better to work with table model directly. Create your own model and do what you want.

See http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#data

no id
  • 1,642
  • 3
  • 24
  • 36
  • That is exactly what I am going to do to overcome the problems that I have with the Netbeans JTable.I will extend DefaultTable and I will override getColumnClass and isCellEditable.Please guys remove the minus grade when I will present you the manual solution.Thank you. – skiabox Sep 11 '12 at 13:00
  • The problem in in the TableModelListener !(without it the application runs fine) – skiabox Sep 11 '12 at 16:07
0

Here is the final solution. The last answer of this question (http://stackoverflow.com/questions/2668547/stackoverflowerror-being-caused-by-a-tablemodellistener) helped me alot :

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nysemarketpick;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.Vector;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

/**
 *
 * @author Administrator
 */
public class PortfolioForm extends javax.swing.JFrame {

    //Create table column names
    private String[] columnNames = {"Stock Symbol", "Stock Name", "Shares", "Price (in dollars)", "Total"};

    //Create table data
    private Object[][] rowData = {
        {null, null, null, null, null}
    };

    //Create a table model
    private MyTableModel myTableModel = new MyTableModel(rowData, columnNames);

    //Create a table
    private JTable jTable1 = new JTable(myTableModel);


    /**
     * Creates new form PortfolioForm
     */
    public PortfolioForm() {
        initComponents();
        add(new JScrollPane(jTable1), BorderLayout.CENTER);

        //Initialize table selection mode
        jTable1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);

        //Allow row selection
        jTable1.setRowSelectionAllowed(true);

        //Load data
        loadData();

        //add listeners
        jbtAddRow.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                if (jTable1.getSelectedRow() >= 0)
                    myTableModel.insertRow(jTable1.getSelectedRow(), new Vector());
                else
                    myTableModel.addRow(new Vector());

            }

        });
        jbtDeleteRow.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                if ((jTable1.getSelectedRow() >= 0) && (myTableModel.getValueAt(jTable1.getSelectedRow(), 1) != null))
                {
                    System.out.println(myTableModel.getValueAt(jTable1.getSelectedRow(), 1));
                    myTableModel.removeRow(jTable1.getSelectedRow());
                }
            }

        });
        jbtSave.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                try
                {
                    ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("portfolio.dat"));
                    out.writeObject(myTableModel.getDataVector());
                    out.writeObject(getColumnNames());
                    out.close();
                }
                catch(Exception ex)
                {
                    ex.printStackTrace();
                }

                disposeForm();
            }

        });
        jbtClear.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                myTableModel.setRowCount(0);
            }

        });
        jbtTotal.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                double sum = 0;
                int numberOfRows = myTableModel.getRowCount();
                for (int i = 0; i < numberOfRows; i++)
                {
                    sum = sum + (Double)myTableModel.getValueAt(i, 4);
                }
                jLabelTotal.setText(String.valueOf(sum));
            }

        });
        jbtTotals.addActionListener(new ActionListener(){

            @Override
            public void actionPerformed(ActionEvent e) {
                Double myDouble;
                for (int i = 0; i < myTableModel.getRowCount(); i++)
                {
                    myDouble = (Integer)myTableModel.getValueAt(i, 2) * (Double)myTableModel.getValueAt(i, 3);
                    myTableModel.setValueAt(myDouble, i, 4);
                }
            }

        });


        myTableModel.addTableModelListener(new TableModelListener(){

            @Override
            public void tableChanged(TableModelEvent e) {

                myTableModel.removeTableModelListener(this);
                if (myTableModel.getRowCount() > 0)
                {
                    if (e.getColumn() == 0)
                    {
                        Object data = myTableModel.getValueAt(e.getFirstRow(), e.getColumn());
                        String stockSymbol = (String)data;
                        XMLService2 myService = new XMLService2(stockSymbol);
                        String stockName = XMLService2.getStockName();
                        myTableModel.setValueAt(stockName, e.getFirstRow(), e.getColumn() + 1);
                    }

                }
                myTableModel.addTableModelListener(this);
            }

        });
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jbtAddRow = new javax.swing.JButton();
        jbtDeleteRow = new javax.swing.JButton();
        jPanel3 = new javax.swing.JPanel();
        jbtSave = new javax.swing.JButton();
        jbtClear = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabelTotal = new javax.swing.JLabel();
        jbtTotal = new javax.swing.JButton();
        jPanel5 = new javax.swing.JPanel();
        jbtTotals = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setSize(new java.awt.Dimension(600, 400));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder("Row functions"));
        jPanel2.setLayout(new java.awt.GridLayout(2, 1));

        jbtAddRow.setText("Add New Row");
        jPanel2.add(jbtAddRow);

        jbtDeleteRow.setText("Delete Selected Row");
        jPanel2.add(jbtDeleteRow);

        jPanel1.add(jPanel2);

        jPanel3.setBorder(javax.swing.BorderFactory.createTitledBorder("Table functions"));
        jPanel3.setMinimumSize(new java.awt.Dimension(200, 111));
        jPanel3.setPreferredSize(new java.awt.Dimension(150, 100));
        jPanel3.setLayout(new java.awt.GridLayout(3, 1));

        jbtSave.setText("Save & Close");
        jPanel3.add(jbtSave);

        jbtClear.setText("Clear");
        jPanel3.add(jbtClear);

        jPanel1.add(jPanel3);

        jPanel4.setBorder(javax.swing.BorderFactory.createTitledBorder("Total Position"));
        jPanel4.setLayout(new java.awt.GridLayout(2, 1));

        jLabelTotal.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabelTotal.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jPanel4.add(jLabelTotal);

        jbtTotal.setText("Calculate");
        jPanel4.add(jbtTotal);

        jPanel1.add(jPanel4);

        getContentPane().add(jPanel1, java.awt.BorderLayout.SOUTH);

        jbtTotals.setText("Calculate Totals");

        org.jdesktop.layout.GroupLayout jPanel5Layout = new org.jdesktop.layout.GroupLayout(jPanel5);
        jPanel5.setLayout(jPanel5Layout);
        jPanel5Layout.setHorizontalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 145, Short.MAX_VALUE)
            .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel5Layout.createSequentialGroup()
                    .add(0, 0, Short.MAX_VALUE)
                    .add(jbtTotals)
                    .add(0, 0, Short.MAX_VALUE)))
        );
        jPanel5Layout.setVerticalGroup(
            jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(0, 336, Short.MAX_VALUE)
            .add(jPanel5Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                .add(jPanel5Layout.createSequentialGroup()
                    .add(0, 153, Short.MAX_VALUE)
                    .add(jbtTotals)
                    .add(0, 154, Short.MAX_VALUE)))
        );

        getContentPane().add(jPanel5, java.awt.BorderLayout.EAST);
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PortfolioForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PortfolioForm().setVisible(true);
            }
        });
    }

    //---Other methods
    private Vector getColumnNames()
    {
        Vector<String> columnNames = new Vector<String>();

        for (int i = 0; i < jTable1.getColumnCount(); i++)
            columnNames.add(jTable1.getColumnName(i));

        return columnNames;
    }

    private void disposeForm()
    {
        this.dispose();
    }

    private void loadData()
    {
        try
        {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream("portfolio.dat"));
            Vector rows = (Vector)in.readObject();
            Vector columns = (Vector)in.readObject();
            myTableModel.setDataVector(rows, columns);
            in.close();
        }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }

    }
    // Variables declaration - do not modify
    private javax.swing.JLabel jLabelTotal;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JPanel jPanel5;
    private javax.swing.JButton jbtAddRow;
    private javax.swing.JButton jbtClear;
    private javax.swing.JButton jbtDeleteRow;
    private javax.swing.JButton jbtSave;
    private javax.swing.JButton jbtTotal;
    private javax.swing.JButton jbtTotals;
    // End of variables declaration
}
skiabox
  • 3,449
  • 12
  • 63
  • 95