Hy ,

I have a problem with the TableModelListener , my application should print out the cell were the content has been modfied but it does notheing.

Here is my code.

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
/**
 *
 * @author Pilu
 */
public class Afisare extends javax.swing.JFrame implements ActionListener, TableModelListener {

    //private JButton getValue;
       
    private Vector<Vector<String>> data;
    private Vector<String> header;
    /** Creates new form Afisare */
    public Afisare() throws Exception {
        DBEngine dbengine = new DBEngine();
        
         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 );
         
         initComponents();


    }
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) this.jTable2.getModel();
        int[] rows = jTable2.getSelectedRows();
              String connectionURL = "jdbc:mysql://localhost:3306/bazadedate";
              Connection connection;
              try{
                  Class.forName("com.mysql.jdbc.Driver");
                  connection = DriverManager.getConnection(connectionURL, "root", "123456");
                  String query = "SELECT * FROM tabel ORDER BY id DESC LIMIT 1" ;
                  Statement st = connection.createStatement();
                  ResultSet result = st.executeQuery(query);
                  String textField1 = jTextField1.getText();
                  String textField2 = jTextField2.getText();
                  String textField3 = jTextField3.getText();
                  while(result.next()){
                     int lastRowValue = result.getInt("id");
                     model.addRow(new Object[]{(lastRowValue+1),textField1,textField2,textField3});
                     st.executeUpdate("INSERT INTO tabel (nume,prenume,pret) VALUES ('"+textField1+"','"+textField2+"','"+textField3+"')");
                  }
              }
              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( model.getValueAt(row, column) );
            System.out.println("Value at (" + row + "," + column + ") changed to " + "'" + cellValue + "\'");
}
   

public void actionPerformed( ActionEvent evt ) {
    
                DefaultTableModel model = (DefaultTableModel)evt.getSource();
		int row = jTable2.getSelectedRow();
		int column = jTable2.getSelectedColumn();

		if ( evt.getSource() == jButton3 ) {
			String value = (String)  model.getValueAt(row,column) ;
			System.out.println("Value at (" + row + "," + column + ") is " + "\'" + value + "\'");
		}		
	}
  public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try
                {
                    new Afisare().setVisible(true);
                    
                }catch(Exception e){e.printStackTrace();}
            }
        });
        
    }

The problem might be in the Afisare() method , but i couldn`t find it.

Recommended Answers

All 19 Replies

Yes, the trouble is in your constructor. You declare a variable 'tableModel', initialize it, and add a listener to it - and then you don't do anything with it. It goes out of scope.

Your JTable is still using whatever default model it had in initComponents(). If you want to use the 'tableModel' you created, you can use the JTable.setModel(); method or pass that model to the JTable constructor when you create the table.

Thank you for the last repleys

How should the method look , because i tried id and still no answer.

You tried what? I wrote above what you need to do. Post your revised code.

here is it :

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;
/**
 *
 * @author Pilu
 */
public class Afisare extends javax.swing.JFrame implements ActionListener, TableModelListener {
 
    //private JButton getValue;
 
    private Vector<Vector<String>> data;
    private Vector<String> header;
    /** Creates new form Afisare */
    public Afisare() throws Exception {
        DBEngine dbengine = new DBEngine();
 
         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);
//New
         jTable2.setModel(tableModel);
//END new
	 tableModel.addTableModelListener( this );
 
         initComponents();
 
 
    }
    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:
        DefaultTableModel model = (DefaultTableModel) this.jTable2.getModel();
        int[] rows = jTable2.getSelectedRows();
              String connectionURL = "jdbc:mysql://localhost:3306/bazadedate";
              Connection connection;
              try{
                  Class.forName("com.mysql.jdbc.Driver");
                  connection = DriverManager.getConnection(connectionURL, "root", "123456");
                  String query = "SELECT * FROM tabel ORDER BY id DESC LIMIT 1" ;
                  Statement st = connection.createStatement();
                  ResultSet result = st.executeQuery(query);
                  String textField1 = jTextField1.getText();
                  String textField2 = jTextField2.getText();
                  String textField3 = jTextField3.getText();
                  while(result.next()){
                     int lastRowValue = result.getInt("id");
                     model.addRow(new Object[]{(lastRowValue+1),textField1,textField2,textField3});
                     st.executeUpdate("INSERT INTO tabel (nume,prenume,pret) VALUES ('"+textField1+"','"+textField2+"','"+textField3+"')");
                  }
              }
              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( model.getValueAt(row, column) );
            System.out.println("Value at (" + row + "," + column + ") changed to " + "'" + cellValue + "\'");
}
 
 
public void actionPerformed( ActionEvent evt ) {
 
                DefaultTableModel model = (DefaultTableModel)evt.getSource();
		int row = jTable2.getSelectedRow();
		int column = jTable2.getSelectedColumn();
 
		if ( evt.getSource() == jButton3 ) {
			String value = (String)  model.getValueAt(row,column) ;
			System.out.println("Value at (" + row + "," + column + ") is " + "\'" + value + "\'");
		}		
	}
  public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                try
                {
                    new Afisare().setVisible(true);
 
                }catch(Exception e){e.printStackTrace();}
            }
        });
 
    }

As i said , i do not know what to do

The statement you added would work, though I would imagine it's giving you fits about a null pointer. You can't assign a model to a table you haven't created yet.

I have this example that works , but i don`t know how to implemet it to my project

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.*;
import javax.swing.event.*;

public class Table extends JFrame implements ActionListener, TableModelListener {

 	private JTable table;
 	private JButton getValue;

	public Table() {

		getContentPane().setLayout( new FlowLayout() );

		DefaultTableModel tableModel;

		Object[] columnNames = new Object[]{"Column 1","Column 2","Column 3"};
		Object[][] rowData = {
			{"1", "2", "3"},
			{"4", "5", "6"},
			{"7", "8", "9"},
			{"10", "11", "12"},
			{"13", "14", "15"},
			{"16", "17", "18"},
			{"19", "20", "21"},
			{"22", "23", "24"}
		};

		tableModel = new DefaultTableModel(rowData, columnNames);
		tableModel.addTableModelListener( this );

		table = new JTable(tableModel);

		JScrollPane scrollPane = new JScrollPane(table);
		table.setPreferredScrollableViewportSize(new Dimension(280, 100));
		getContentPane().add(scrollPane);

		getValue = new JButton( "Get Value" );
		getValue.addActionListener( this );
		getContentPane().add( getValue );

		setVisible( true );
		setSize( 320, 200 );
	}

	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) );
			JOptionPane.showMessageDialog( this,
				"Value at (" + row + "," + column + ") is " + "\'" + value + "\'");
		}		
	}

  	public static void main ( String[] args ) {
    		Table frm = new Table();
    		frm.setVisible(true);
    		frm.setSize( 320, 200 );
	}
}

What error did you receive in the previous code you posted?

Just as you said

java.lang.NullPointerException

I got it to work with jTable2.setModel(tableModel); after initCompnent();

Thank you very much

And where are you initializing your jTable2 instance?

Edit: cross-post. I knew you would see it eventually :)

Now that i`ve putted the jTable2.setModel(tableModel); i can not use anymore DefaultTableModel model = (DefaultTableModel) this.jTable2.getModel() or something because when i try to use anything with MODEL it gives me an error :

The exception is java.lang.ArrayIndexOutOfBoundsException: -1


What should i do in this case?

You should still be able to get the model in the same manner you did before. If you need to access the model often, you can also keep a reference to it as an instance variable and use it without having to use getModel() all the time.

I still can not use it after seting the model;

public Afisare() throws Exception {
        DBEngine dbengine = new DBEngine();
        
         
         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);
         
         initComponents();
         jTable2.setModel(tableModel);
    }

 private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {                                      
        // TODO add your handling code here:        
        //DefaultTableModel model = (DefaultTableModel) jTable2.getModel();
        DefaultTableModel model = (DefaultTableModel) this.jTable2.getModel();
        model = tableModel;
        int row = jTable2.getSelectedRow();
        int col = jTable2.getSelectedColumn();
        //Object value = tableModel.getValueAt(row, col);
        //System.out.println(row+col);
              String connectionURL = "jdbc:mysql://localhost:3306/bazadedate";
              Connection connection;
              try{
                  Class.forName("com.mysql.jdbc.Driver");
                  connection = DriverManager.getConnection(connectionURL, "root", "123456");
                  String query = "SELECT * FROM tabel ORDER BY id DESC LIMIT 1" ;
                  Statement st = connection.createStatement();
                  ResultSet result = st.executeQuery(query);
                  String textField1 = jTextField1.getText();
                  String textField2 = jTextField2.getText();
                  String textField3 = jTextField3.getText();
                  while(result.next()){
                     int lastRowValue = result.getInt("id");
                     model.addRow(new Object[]{(lastRowValue+1),textField1,textField2,textField3});
                     //tableModel.addRow(new Object[]{(lastRowValue+1),textField1,textField2,textField3});
                     st.executeUpdate("INSERT INTO tabel (nume,prenume,pret) VALUES ('"+textField1+"','"+textField2+"','"+textField3+"')");
                     System.out.println("da2");
                  }
              }
              catch(Exception e){
                  System.out.println("The exception is " + e);
               } 
    }

But now i can edit a cell and if it has been modified it returns me the cell position , however when the program hits the "model" from DefaultTableModel for adding a row , deleting a row , getting a value , it stops

I dont understand your topic is about TableModelListener and your code shows Action from JButton's mouseclick

please tell us "What do you really want to"

1/ listening for changes into JTable and any changes would be saved to the databases

2/ save changes manually by clicking to the JButton

I started the thread when a had a problem with the TableListener (i wanted to get the cell where had been a change of value) but i got it resolved with the help from Ezzaral , but now after i added the jTable2.setModel(tableModel) i can not add rows to table , delete them or getting a value , and i do not know how to add the anymore.

If i comment the jTable2.setModel(tableModel) all works fine beside getting the cell which has been modified

then you really goes wrong direction, there are many mistakes present, too many to comment on all of them:

there are two choises

1/ saving the changes to the Db immediatelly row by row separatelly

2/ saving the changes once, all changes would be cached in some array

3/ you have to add ListSelectionListener in both cases, for caching TableCell values from selected TableRow before its change(s)

You didn't say which line the error was on, but if I had to guess I would imagine one these

int row = jTable2.getSelectedRow();
        int col = jTable2.getSelectedColumn();

if you don't have a cell selected in the table. They both return -1 if no selection exists.

It doesn't look like you're even using those values. Try removing those two lines.

Hy ,

I found the problem :

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


This is the code i`m using, i have googled it but i did not found anything

/*
 * 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 that has a table in which 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

Never mind , i resolved it

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.