Results 1 to 4 of 4

Thread: setModel error

  1. #1
    razvan is offline Member
    Join Date
    Jul 2011
    Posts
    1
    Rep Power
    0

    Default setModel error

    Hy ,


    If is use setModel(...) i can not use anymore DefaultTableModel model ... , model.removeRow / model.addRow , basically model.

    If i don`t use setMode(...) i can not use it because i can not get the modeified cell.
    This is the code i`m using, i have googled it but i did not found anything



    Java Code:
    /*
     * To change this template, choose Tools | Templates
     * and open the template in the editor.
     */
    
    /*
     * adaugare.java
     *
     * Created on Jul 24, 2011, 8:09:42 AM
     */
    package aplicatie;
    import java.util.Vector;
    import aplicatie.DBEngine;
    import javax.swing.table.DefaultTableModel;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.Statement;
    import java.sql.ResultSet;
    import java.sql.Connection;
    import java.sql.SQLException;
    import javax.swing.table.TableCellEditor;
    import javax.swing.event.TableModelListener;
    import javax.swing.event.TableModelEvent;
    import java.lang.Object;
    import java.sql.*;
    import java.lang.*;
    import java.lang.ClassCastException;
    import java.awt.event.*;
    import java.lang.String;
    import java.lang.Exception;
    import java.awt.*;
    import java.awt.event.*;
    //import java.awt.event.ActionListener;
    import javax.swing.*;
    import javax.swing.table.AbstractTableModel;
    import javax.swing.table.*;
    import javax.swing.event.*;
    
    /**
     *
     * @author Pilu
     */
    public class adaugare extends javax.swing.JFrame implements ActionListener, TableModelListener {
    
        /** Creates new form adaugare */
        DefaultTableModel tableModel;
        private Vector<Vector<String>> data;
        private Vector<String> header;
    
        public adaugare() throws Exception {
            DBEngine dbengine = new DBEngine();
            getContentPane().setLayout(new FlowLayout());
    
            DefaultTableModel tableModel;
    
                data = dbengine.getTabel();
                header = new Vector<String>();
                header.add("ID");
                header.add("Nume");
                header.add("Prenume");
                header.add("Pret");
                tableModel = new DefaultTableModel(data,header);
                tableModel.addTableModelListener(this);            
                table = new JTable(tableModel);            
                initComponents();
           //     table.setModel(new javax.swing.table.DefaultTableModel(
           //             data,header
           //     ));
        }
    
        /** 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() {
    
            jScrollPane1 = new javax.swing.JScrollPane();
            //table = new javax.swing.JTable();
            jButton1 = new javax.swing.JButton();
    
            setName("Form"); // NOI18N
    
            jScrollPane1.setName("jScrollPane1"); // NOI18N
      //      table.setModel(new javax.swing.table.DefaultTableModel(
      //              data,header
      //          ));
            table.setName("table"); // NOI18N
            jScrollPane1.setViewportView(table);
            org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(aplicatie.AplicatieApp.class).getContext().getResourceMap(adaugare.class);
            table.getAccessibleContext().setAccessibleName(resourceMap.getString("table.AccessibleContext.accessibleName")); // NOI18N
    
            jButton1.setText(resourceMap.getString("Delete Selected.text")); // NOI18N
            jButton1.setName("Delete Selected"); // NOI18N
            jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
                public void mouseClicked(java.awt.event.MouseEvent evt) {
                    jButton1MouseClicked(evt);
                }
            });
    
            javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
            getContentPane().setLayout(layout);
            layout.setHorizontalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(18, 18, 18)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 569, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(220, Short.MAX_VALUE))
            );
            layout.setVerticalGroup(
                layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(layout.createSequentialGroup()
                    .addGap(29, 29, 29)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 31, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 311, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addContainerGap(84, Short.MAX_VALUE))
            );
    
            pack();
        }// </editor-fold>                        
    
        private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                      
            // TODO add your handling code here:      
            DefaultTableModel model = (DefaultTableModel) table.getModel();
                 int[] rows = table.getSelectedRows();
                 int col=0;
                 int j;
                 String connectionURL = "jdbc:mysql://localhost:3306/bazadedate";
                 Connection connection;
                 for(int i=rows.length-1;i>=0;i--){
                     Object value =  table.getValueAt(rows[i] , col);
                     System.out.println("randul : "+rows[i]);
                     System.out.println("id : "+value);
                     model.removeRow(rows[i]);
                     
                  try{
                      Class.forName("com.mysql.jdbc.Driver");
                      connection = DriverManager.getConnection(connectionURL, "root", "123456");
                      PreparedStatement pst =  connection.prepareStatement("DELETE FROM tabel WHERE id="+ value);
                      j = pst.executeUpdate();
                  }
                  catch(Exception e){
                      System.out.println("The exception is " + e);
                   } 
                 }                 
        }                                     
       
        public void tableChanged(TableModelEvent e) {
            DefaultTableModel model = (DefaultTableModel) e.getSource();
            int row = e.getFirstRow();
            int column = e.getColumn();
    
            String cellValue = String.valueOf(table.getValueAt(row, column));
    
            System.out.println("Value at (" + row + "," + column + ") changed to " + "'" + cellValue + "\'");
        }
    
        public void actionPerformed(ActionEvent evt) {
            int row = table.getSelectedRow();
            int column = table.getSelectedColumn();
    
            //if ( evt.getSource() == getValue ) {
            String value = String.valueOf(table.getValueAt(row, column));
            System.out.println("Value at (" + row + "," + column + ") is " + "\'" + value + "\'");
            //}		
        }
    
           
        /**
         * @param args the command line arguments
         */
        public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
    
                public void run() {
                    try {
                        new adaugare().setVisible(true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        // Variables declaration - do not modify                     
        private javax.swing.JButton jButton1;
        private javax.swing.JScrollPane jScrollPane1;
        private javax.swing.JTable table;
        // End of variables declaration                   
    }


    I commented setModel for test reasons .

    Can anybody tell me how to create this app withiut errors ?

    The app should show a table linked with a database , if a cell is edited it edits in the database , if i add a row it adds it in the database and in the table , same goes to the delete part
    Last edited by razvan; 07-25-2011 at 09:40 AM.

  2. #2
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

    Default

    It's hard to tell what your problem is since you have a ton of unrelated code in your post above, and my suggestions don't help, I suggest that you simplify your code to its bare essentials that allow it to compile and demonstrates the error, but has none of all that code that doesn't apply to the problem, an SSCCE. This would mean creating your code without all that NetBeans created junk, something you should learn to do regardless.

    A big problem I see is that you are declaring more than one model variable and so the variable that has class visibility (declared in the class and not in a method or constructor) is not the model that is currently being used by your JTable:

    Java Code:
    public class adaugare extends javax.swing.JFrame implements ActionListener, TableModelListener {
    
        /** Creates new form adaugare */
        DefaultTableModel tableModel; // [color="red"][b]*** Declared here ***[/b][/color]
        private Vector<Vector<String>> data;
        private Vector<String> header;
    
        public adaugare() throws Exception {
            DBEngine dbengine = new DBEngine();
            getContentPane().setLayout(new FlowLayout());
    
            DefaultTableModel tableModel;  // [color="red"][b]*** And declared again here ***[/b][/color]
    
                data = dbengine.getTabel();
                header = new Vector<String>();
                header.add("ID");
                header.add("Nume");
                header.add("Prenume");
                header.add("Pret");
                tableModel = new DefaultTableModel(data,header); // [color="red"][b]*** and initialized here ***[/b][/color]
                tableModel.addTableModelListener(this);            
                table = new JTable(tableModel);            
                //....
    Don't re-declare the variable in the constructor but rather use the class's variable throughout the program.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,184
    Rep Power
    19

    Default

    Last edited by DarrylBurke; 07-25-2011 at 09:24 PM.

  4. #4
    Fubarable's Avatar
    Fubarable is offline Moderator
    Join Date
    Jun 2008
    Posts
    19,316
    Blog Entries
    1
    Rep Power
    26

Similar Threads

  1. java out of memory error-heap space error
    By elsanthosh in forum NetBeans
    Replies: 4
    Last Post: 06-15-2010, 09:31 AM
  2. Replies: 1
    Last Post: 03-10-2010, 01:53 PM
  3. Replies: 1
    Last Post: 12-05-2009, 07:28 AM
  4. Replies: 1
    Last Post: 10-26-2009, 04:38 PM
  5. Replies: 3
    Last Post: 01-23-2009, 08:53 AM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •