**I want to enter the value in jtable run time and want to dispaly its sum on same jtable when i pressed calculated button **
how to do please help :)

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
public class TestTable 
{
    public static void main(String[] args) 
    {
        TestTable testTable = new TestTable();
    }
    public TestTable() 
    {
        EventQueue.invokeLater(new Runnable() 
        {
            @Override
            public void run() 
            {
                try
                {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }
                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestTable.Bill());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }    
    public class Bill extends JPanel implements ActionListener 
    {
        JTextField textFieldId;
        JLabel l1;
        JLabel l2;
        JButton b1,b2,b3;
        JTextField sun,sunr,sat,satr,oth,othr;
        float sum1,totall;
        ResultSet rs1 = null;
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);

        private int rows;
        public Bill() 
        {
            setLayout(new BorderLayout());            
            JPanel fields = new JPanel();
            textFieldId = new JTextField(10);
            l1 = new JLabel("New Customer Entry :-");
            l2 = new JLabel("Customer Id");
            b1 = new JButton("OK");
            b2 = new JButton("Calculate");
            b3 = new JButton("Print");
            fields.add(l2);
            fields.add(textFieldId);
            fields.add(b1);
            fields.add(b2);
            fields.add(b3);
            add(fields, BorderLayout.NORTH);
            b1.addActionListener(this);
            b2.addActionListener(this);
            b3.addActionListener(this);
            // Don't forget to add a table.
            add(new JScrollPane(new JTable(model)));
        }
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            System.out.println("You clicked the button");
            Connection con;
            if (e.getSource() == b1) 
            {
                PreparedStatement ps = null;
                Statement stmt = null;
                try 
                {

                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    con = DriverManager.getConnection("jdbc:odbc:devendra");
                    ps = con.prepareStatement("SELECT  * FROM Customer where Customer_Id = ?");
                    // You must bind the parameter with a value...
                    ps.setString(1, textFieldId.getText());
                    rs1 = ps.executeQuery();
                    model.addColumn("Customer_Id");
                    model.addColumn("Customer_Name");
                    model.addColumn("Contact");
                    model.addColumn("Paper_Name");
                    model.addColumn("Sunday");
                    model.addColumn("Rate");
                    model.addColumn("Satarday");
                    model.addColumn("Rate");
                    model.addColumn("Other Day");
                    model.addColumn("Rate");
                    model.addColumn("Total");
                    while (rs1.next()) 
                    {                           
                            model.addRow(new Object[]{rs1.getString(1),rs1.getString(2),rs1.getString(3),rs1.getString(4),rs1.getString(5),
                                rs1.getString(6),rs1.getString(7),rs1.getString(8),rs1.getString(9),rs1.getString(10),rs1.getString(11)});
                    }
                    Vector data = model.getDataVector();

                    JOptionPane.showMessageDialog(null, "You successfully Enter the Entry");
                } 
                catch (SQLException s) 
                {
                    System.out.println("SQL code does not execute.");
                    JOptionPane.showMessageDialog(null, "Please Enter the Detail Correctly");
                } catch (Exception exp) 
                {
                    JOptionPane.showMessageDialog(this, "Failed to perform query: " + exp.getMessage());
                } finally 
                {
                    try {
                        ps.close();
                    } 
                    catch (Exception ex)
                    {
                    }
                }
                if (e.getSource() == b2)  
                {
                //    if (e.getType() == TableModelEvent.UPDATE) 
                    int rowCount = table.getRowCount();             
                    for(int i =1; i<=rowCount;i++)
                    {
                        int valuea = (Integer) table.getModel().getValueAt(rowCount, 5);
                        int valueb = (Integer) table.getModel().getValueAt(rowCount, 6);
                        int valuec = (Integer) table.getModel().getValueAt(rowCount, 7);
                        int valued = (Integer) table.getModel().getValueAt(rowCount, 8);
                        int valuee = (Integer) table.getModel().getValueAt(rowCount, 9);
                        int valuef = (Integer) table.getModel().getValueAt(rowCount, 10);
                        Double value = new Double(( valuea * valueb)+ (valuec * valued)+(valuee*valuef));
                        model.setValueAt(value,rowCount, 11);
                        table.revalidate();
                        table.repaint();


                 }


            }
            }        

        }
    }
}

I miss there

  1. override getColumnClass, its very important for JTables view to know data types stored in DefaultTableModel

  2. reset DefaultTableModel to null, use (there are a few another methods, you can to starting with) model.setRowCount(0); before a new rows are added to

  3. create (I assumed that there isn't another column structure, if yes then multiplay this variables) ColumnModel as local variable

  4. (for results from calculations :-) there isn't required table.revalidate(); table.repaint();, be sure that arrays in Java starting with 0 (zero)

  5. close() Statement stmt = null; in finnaly block too, otherwise these Objects stays in JVM memory, can't be GC'ed, increasing JVM used memory

  6. crossposted

ok do u have any example reguarding these problem???

Deve - what exactly is your problem here? You have some code to do a calc and display it when a button is pressed - what exactly happens when you try to run it?

sir. Let me tel u in sequence
1.we have to enter the customer id and then pressed ok (then in table all the detail of customer is shown these code is executing successfully)
2.in table i want to enter the integer value in respective column
3.after that i will click on calcuate button then calculation result shown in next column in respective column and row that is in Total Column..

from point 3 i getting error most off time code successfully executed but result will not be shown as per me..
if u got these problem then tell me answer please
else not i will tel u again..
please help me out.i am doing my project and need to be done on time..
else give me idead i will do..:)
its request to u..

Did you read mKorbel's post where he reminded you that Java arrays start with index 0? All your getValueAt/setValueAt calls seem to assume that the column numbers start at 1 (ie you assume they are numbered 1-11 when in reality they are numbered 0-10). Eg column "Sunday" is column 4, not 5. "Total" is column 10, not 11.

yes sir. as i told u code successfully executed but not giveing me result of calcuation..
now what to do

column "Sunday" is column 4, not 5. "Total" is column 10, not 11.

import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.*;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;
import javax.swing.table.DefaultTableModel;
public class TestTable 
{
    public static void main(String[] args) 
    {
        TestTable testTable = new TestTable();
    }
    public TestTable() 
    {
        EventQueue.invokeLater(new Runnable() 
        {
            @Override
            public void run() 
            {
                try
                {
                    UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                }
                JFrame frame = new JFrame("Testing");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setLayout(new BorderLayout());
                frame.add(new TestTable.Bill());
                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }    
    public class Bill extends JPanel implements ActionListener ,CellEditorListener  
    {
        JTextField textFieldId;
        JLabel l1;
        JLabel l2;
        JButton b1,b2,b3;
        JTextField sun,sunr,sat,satr,oth,othr;
        float sum1,totall;
        ResultSet rs1 = null;
        DefaultTableModel model = new DefaultTableModel();
        JTable table = new JTable(model);

        private int rows;
        Double value;
        public Bill() 
        {
            setLayout(new BorderLayout());            
            JPanel fields = new JPanel();
            textFieldId = new JTextField(10);
            l1 = new JLabel("New Customer Entry :-");
            l2 = new JLabel("Customer Id");
            b1 = new JButton("OK");
            b2 = new JButton("Calculate");
            b3 = new JButton("Print");
            fields.add(l2);
            fields.add(textFieldId);
            fields.add(b1);
            fields.add(b2);
            fields.add(b3);
            add(fields, BorderLayout.NORTH);
            b1.addActionListener(this);
            b2.addActionListener(this);
            b3.addActionListener(this);
            // Don't forget to add a table.
            add(new JScrollPane(new JTable(model)));
        }
        @Override
        public void actionPerformed(ActionEvent e) 
        {
            System.out.println("You clicked the button");
            Connection con;
            if (e.getSource() == b1) 
            {
                PreparedStatement ps = null;
                Statement stmt = null;
                try 
                {

                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    con = DriverManager.getConnection("jdbc:odbc:devendra");
                    ps = con.prepareStatement("SELECT  * FROM Customer where Customer_Id = ?");
                    // You must bind the parameter with a value...
                    ps.setString(1, textFieldId.getText());
                    rs1 = ps.executeQuery();
                    model.addColumn("Customer_Id");
                    model.addColumn("Customer_Name");
                    model.addColumn("Contact");
                    model.addColumn("Paper_Name");
                    model.addColumn("Sunday");
                    model.addColumn("Rate");
                    model.addColumn("Satarday");
                    model.addColumn("Rate");
                    model.addColumn("Other Day");
                    model.addColumn("Rate");
                    model.addColumn("Price");
                    model.setRowCount(0);
                    while (rs1.next()) 
                    {                           
                            model.addRow(new Object[]{rs1.getString(1),rs1.getString(2),rs1.getString(3),rs1.getString(4),rs1.getString(5),
                                rs1.getString(6),rs1.getString(7),rs1.getString(8),rs1.getString(9),rs1.getString(10)});
                    }
                    Vector data = model.getDataVector();

                    JOptionPane.showMessageDialog(null, "You successfully Enter the Entry");
                } 
                catch (SQLException s) 
                {
                    System.out.println("SQL code does not execute.");
                    JOptionPane.showMessageDialog(null, "Please Enter the Detail Correctly");
                } catch (Exception exp) 
                {
                    JOptionPane.showMessageDialog(this, "Failed to perform query: " + exp.getMessage());
                } finally 
                {
                    try {
                        ps.close();
                    } 
                    catch (Exception ex)
                    {
                    }
                }                
            } 
            if (e.getSource() == b2)     
            {
                 int rowCount = table.getRowCount();


                 for(int i =1; i<rowCount;i++)
                 {
                      Object valuea = model.getValueAt( i, 4 ); 
                      Object valueb = model.getValueAt( i, 5 );  
                      Object valuec = model.getValueAt( i, 6 ); 
                      Object valued = model.getValueAt( i, 7 ); 
                      Object valuee = model.getValueAt( i, 8 ); 
                      Object valuef = model.getValueAt( i, 9 ); 
                      double value; 
                      value = Double.parseDouble( String.valueOf( valuea ) ) * Double.parseDouble( String.valueOf( valueb ) ); 
                      model.setValueAt( value, i, 10 ); 
                 }

        }
}

        @Override
        public void editingStopped(ChangeEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }

        @Override
        public void editingCanceled(ChangeEvent e) {
            throw new UnsupportedOperationException("Not supported yet.");
        }



    }
}

still error is same successfully executed but not showing result ....

Time for some debugging!
Just after line 149 - where yo have one row of data and the total calculated, try printing all the variables there to see if you are getting the correct data and performing the correct calculation.

140: for(int i =1; i<rowCount;i++)

How many rows of data do you have? This will ignore the first row (row zero).

i have dynamica row.
means different customer having multiple paper as per multiple rows are there in program..
@JamesCherrill

which is best for these kind of code defaultmodel table or abstractmodel table...
because for fireTableRowsUpdated query we need abstract model table ?
is i am right ?

can u modifed the code . I have attached the image of my database..
please help me out sir...

  • I gave you two full working examples, covering all required areas, with fully qualified description, based on (linked to) tutorial, better than is possible,

  • for rest, for JDBC to search for ResultSetTableModel, better TableFromDatabase

  • same with answers by @James Cherrill

... can u modifed the code ...

This is not a "we do your homework" service, and we don't write programs for free, so no, I can't write your code for you.
You have been given a lot of advice and useful links. It's time for you to study that information and start to do some work yourself.

ok sorry sir. I accept your answer. Sorry Again. Thanks for the help. I will put corrected code or what changes i made in my code when i got success.

still not geting the solution..

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.