Page 1 of 2 12 LastLast
Results 1 to 20 of 38
Like Tree1Likes

Thread: Calculating values from a jtable column

  1. #1
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Calculating values from a jtable column

    Hi everyone,

    am trying to sum up the values from a jtable column and display the sum on a jtextfield. I am using defaultTableModel and implements TableModelListener to detect changes on the table. Still the textfield doesnt display the summed up value. this is my code:

    Java Code:
     public void tableChanged(TableModelEvent e){
            if (e.getType() == TableModelEvent.INSERT){
              
                int row = jTable1.getRowCount();
                
                for (int i = 0; i <= row; i++){
                    Int total += (Integer)jTable1.getValueAt(i,4);
                }
                
                String totalResult = new Integer (total).toString();
            }

    This is the code that displays the value on textfield:

    Java Code:
    private void txtTotalActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            
            txtTotal.setText(totalResult);
        }

    i need help pls

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

    Default Re: Calculating values from a jtable column

    That code won't compile ("Int total").

    Please show us the real code as this is vitally important for us to see if we're going to have a chance of helping you.
    We need to see for example if you really do re-declare total inside of the for loop.

  3. #3
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    I actually didnt declare the "int total" in the for loop...sorry about that..error on my part when i was pasting the code here. this is the actual code:

    Java Code:
    public void tableChanged(TableModelEvent e){
           if (e.getType() == TableModelEvent.INSERT){
              
               int row = jTable1.getRowCount();
               int total=0;
                
               for (int i = 0; i <= row; i++){
                   total += (Integer)jTable1.getValueAt(i,4);
               }
                
               String totalResult = new Integer (total).toString();
           }

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

    Default Re: Calculating values from a jtable column

    Thanks for the correction.

    Now have you placed System.out.println(...) statements in this block of code? Does it ever get called when you expect that it should be called? If so, are you printing out the values that you are extracting from the table from within the for loop to see if they match with your expectations?

  5. #5
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    Quote Originally Posted by Fubarable View Post
    Thanks for the correction.

    Now have you placed System.out.println(...) statements in this block of code? Does it ever get called when you expect that it should be called? If so, are you printing out the values that you are extracting from the table from within the for loop to see if they match with your expectations?

    I haven't done that. Will do that now. Cheers

  6. #6
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    Quote Originally Posted by Fubarable View Post
    Thanks for the correction.

    Now have you placed System.out.println(...) statements in this block of code? Does it ever get called when you expect that it should be called? If so, are you printing out the values that you are extracting from the table from within the for loop to see if they match with your expectations?
    used System.out.printf() and it printed out what I'm expecting on the console but still doesnt display it on textfield.

    this is the code i used to cast the Int value to String so i can use the use the set method of the textfield:

    Java Code:
    totalResult = new Integer (total).toString();

  7. #7
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,301
    Rep Power
    20

    Default Re: Calculating values from a jtable column

    In the tableChanged(...) code you posted, the variable totalResult goes out of scope on the very next line, so can't possibly be used elsewhere in the program.

    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem. Not hundreds of lines of code; just enough to illustrate the scenario.

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  8. #8
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    Java Code:
    public void tableChanged(TableModelEvent e){
           if (e.getType() == TableModelEvent.INSERT){
               
               int row = jTable1.getRowCount();
               int total=0;
                 
               for (int i = 0; i <= row; i++){
                   total += (Integer)jTable1.getValueAt(i,4);
               }
                 
               totalResult = new Integer (total).toString(); // totalResult is declared as a String instance variable
           }

  9. #9
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    i tested my code with a little modification using a button and it worked. but i can't get it to work on tableChanged method. i have added tablemodellistener to the table in question. what am i not doing here.

    sample of my working code on jbutton actionPreformed:

    Java Code:
     private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
            // TODO add your handling code here:
            int row = jTable1.getRowCount();
                
                for (int i = 0; i < row; i++){
                    total += Integer.parseInt(jTable1.getValueAt(i,4).toString());
                }
                
                totalResult = Integer.toString(total);
                txtTotal.setText(totalResult);
            
        }

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

    Default Re: Calculating values from a jtable column

    Quote Originally Posted by victaino View Post
    i tested my code with a little modification using a button and it worked. but i can't get it to work on tableChanged method. i have added tablemodellistener to the table in question. what am i not doing here.
    You're not creating and posting an SSCCE.

    Bugs like these can be subtle, and there's a good chance that the code you're posting has nothing to do with your error, which will just lead to frustration for you and us. Do yourself a favor, read the SSCCE link, then pare down your code to its barest essentials to reproduce the error, and post it here.

  11. #11
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    Java Code:
    jTable1.getModel().addTableModelListener(this);
    
    public void tableChanged(TableModelEvent e){
            if (e.getType() == TableModelEvent.INSERT){
                int row = jTable1.getRowCount();
                
                for (int i = 0; i < row; i++){
                    total += Integer.parseInt(jTable1.getValueAt(i,4).toString()); // int total declared as instance variable
                }
                
                totalResult = Integer.toString(total); // String totalResult declared as instance variable
                System.out.println(totalResult);
                txtTotal.setText(totalResult);
            
            }
            
        }
    error

    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    	at jomas.Sales.tableChanged(Sales.java:675)
    	at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
    	at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTableModel.java:215)
    	at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:359)
    	at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:333)
    	at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:344)
    	at jomas.Sales.jTable1KeyPressed(Sales.java:483)
    	at jomas.Sales.access$300(Sales.java:29)
    	at jomas.Sales$4.keyPressed(Sales.java:237)
    	at java.awt.Component.processKeyEvent(Component.java:6333)
    	at javax.swing.JComponent.processKeyEvent(JComponent.java:2801)
    	at java.awt.Component.processEvent(Component.java:6152)
    	at java.awt.Container.processEvent(Container.java:2083)
    	at java.awt.Component.dispatchEventImpl(Component.java:4737)
    	at java.awt.Container.dispatchEventImpl(Container.java:2141)
    	at java.awt.Component.dispatchEvent(Component.java:4565)
    	at java.awt.KeyboardFocusManager.redispatchEvent(KeyboardFocusManager.java:1836)
    	at java.awt.DefaultKeyboardFocusManager.dispatchKeyEvent(DefaultKeyboardFocusManager.java:712)
    	at java.awt.DefaultKeyboardFocusManager.preDispatchKeyEvent(DefaultKeyboardFocusManager.java:990)
    	at java.awt.DefaultKeyboardFocusManager.typeAheadAssertions(DefaultKeyboardFocusManager.java:855)
    	at java.awt.DefaultKeyboardFocusManager.dispatchEvent(DefaultKeyboardFocusManager.java:676)
    	at java.awt.Component.dispatchEventImpl(Component.java:4609)
    	at java.awt.Container.dispatchEventImpl(Container.java:2141)
    	at java.awt.Window.dispatchEventImpl(Window.java:2482)
    	at java.awt.Component.dispatchEvent(Component.java:4565)
    	at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:684)
    	at java.awt.EventQueue.access$000(EventQueue.java:85)
    	at java.awt.EventQueue$1.run(EventQueue.java:643)
    	at java.awt.EventQueue$1.run(EventQueue.java:641)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:98)
    	at java.awt.EventQueue$2.run(EventQueue.java:657)
    	at java.awt.EventQueue$2.run(EventQueue.java:655)
    	at java.security.AccessController.doPrivileged(Native Method)
    	at java.security.AccessControlContext$1.doIntersectionPrivilege(AccessControlContext.java:87)
    	at java.awt.EventQueue.dispatchEvent(EventQueue.java:654)
    	at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:296)
    	at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:211)
    	at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:201)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:196)
    	at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:188)
    	at java.awt.EventDispatchThread.run(EventDispatchThread.java:122)

  12. #12
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default Re: Calculating values from a jtable column

    Something on line 675 is null. Find out what and why.

  13. #13
    DarrylBurke's Avatar
    DarrylBurke is offline Forum Police
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,301
    Rep Power
    20

    Default Re: Calculating values from a jtable column

    Quote Originally Posted by DarrylBurke View Post
    To get better help sooner, post a SSCCE (Short, Self Contained, Correct (Compilable), Example) that demonstrates the problem. Not hundreds of lines of code; just enough to illustrate the scenario.
    Quote Originally Posted by Fubarable View Post
    You're not creating and posting an SSCCE.
    You don't really want help, do you?

    db
    If you're forever cleaning cobwebs, it's time to get rid of the spiders.

  14. #14
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    don't understand what you mean. i have pasted my code already

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

    Default Re: Calculating values from a jtable column

    Quote Originally Posted by victaino View Post
    don't understand what you mean. i have pasted my code already
    Please re-read my comment in post #10. Please read the SSCCE link. You seem to have ignored both. If anything is confusing about either, please ask for clarification.

  16. #16
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    Java Code:
    
    import java.awt.event.KeyEvent;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import javax.swing.table.DefaultTableModel;
    import java.awt.print.*;
    import java.awt.*;
    import javax.swing.JOptionPane;
    import javax.swing.event.TableModelListener;
    import javax.swing.event.TableModelEvent;
    
    /**
     *
     * @author Vize
     */
    public class Sales extends javax.swing.JInternalFrame implements Printable, TableModelListener{
        
         
       int total = 0;
       String totalResult = null;
       
       // keep track of updated data
       private boolean Update = false;
       int total = 0;
       String totalResult = null;
    
        /** Creates new form Sales */
        public Sales() {
            initComponents();
        }
     @Override
        public void tableChanged (TableModelEvent e){
            if (e.getType()== TableModelEvent.UPDATE){
              int row = jTable1.getRowCount();
                
                for (int i = 0; i < row; i++){
                    total += Integer.parseInt(jTable1.getValueAt(i, 4).toString());// this is where the stack trace keep pointing to
                }
                
                totalResult = Integer.toString(total);
                txtTotal.setText(totalResult);  
            }
        }
    error
    Java Code:
    Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
        at jomas.Sales.tableChanged(Sales.java:675)
        at javax.swing.table.AbstractTableModel.fireTableChanged(AbstractTableModel.java:280)
        at javax.swing.table.AbstractTableModel.fireTableRowsInserted(AbstractTableModel.java:215)
        at javax.swing.table.DefaultTableModel.insertRow(DefaultTableModel.java:359)
        at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:333)
        at javax.swing.table.DefaultTableModel.addRow(DefaultTableModel.java:344)
        at jomas.Sales.jTable1KeyPressed(Sales.java:483)
        at jomas.Sales.access$300(Sales.java:29)
        at jomas.Sales$4.keyPressed(Sales.java:237)

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

    Default Re: Calculating values from a jtable column

    The code posted above does not comply with the SSCCE specification. Yes it is short, but I cannot compile this code, nor can I run it, test it, reproduce your error.

    And so, I still cannot help you. *Again*, if anything about the SSCCE specification or our recommendations confuse, please ask. Otherwise we're going to continue to have a very frustrating conversation.

  18. #18
    victaino is offline Member
    Join Date
    Apr 2012
    Posts
    38
    Rep Power
    0

    Default Re: Calculating values from a jtable column

    hope this meets up with SSCCE spec

    Java Code:
    
    import java.awt.EventQueue;
    
    import javax.swing.JInternalFrame;
    import java.awt.event.KeyEvent;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import javax.swing.table.DefaultTableModel;
    import java.awt.print.*;
    import java.awt.*;
    import javax.swing.JOptionPane;
    import javax.swing.event.TableModelListener;
    import javax.swing.event.TableModelEvent;
    
    
    public class Sale extends JInternalFrame implements TableModelListener {
    	
    	// declare variables   
    		 int total = 0;
    		String totalResult = null;
    		private javax.swing.JTable jTable1;
    		 private javax.swing.JTextField txtTotal;
    		private javax.swing.JTextField txtPaid;
    		private javax.swing.JTextField txtBalance;
    		private javax.swing.JButton jButton1;
    	    private javax.swing.JPanel jPanel3;
    	    private javax.swing.JScrollPane jScrollPane1;
    	    private javax.swing.JPanel jPanel4;
    	    private javax.swing.JDesktopPane jdesktop;
    
    	    public Sale(){
    	    	
    	    	// Initialize object
    	        jPanel3 = new javax.swing.JPanel();
    	        jScrollPane1 = new javax.swing.JScrollPane();
    	        jPanel4 = new javax.swing.JPanel();
    	        jButton1 = new javax.swing.JButton();
    	        jdesktop = new javax.swing.JDesktopPane();
    
    
    
    
    	    	// set layout and create table
    	    	jPanel3.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
    
    	    	        jTable1.setModel(new javax.swing.table.DefaultTableModel(
    	    	            new Object [][] {
    	    	                {null, null, null, null, null}
    	    	            },
    	    	            new String [] {
    	    	                "Item", "Quantity", "Unit Price", "Discount", "Subtotal"
    	    	            }
    	    	        ));
    	    	        jTable1.setShowGrid(false);
    	    	        jTable1.putClientProperty("terminateEditOnFocusLost", true);
    	    	        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
    	    	            public void keyPressed(java.awt.event.KeyEvent evt) {
    	    	                keyPressed(evt);
    	    	            }
    	    	        });
    	    	        jScrollPane1.setViewportView(jTable1);
    
    	    	        org.jdesktop.layout.GroupLayout jPanel3Layout = new org.jdesktop.layout.GroupLayout(jPanel3);
    	    	        jPanel3.setLayout(jPanel3Layout);
    	    	        jPanel3Layout.setHorizontalGroup(
    	    	            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    	    	            .add(org.jdesktop.layout.GroupLayout.TRAILING, jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 951, Short.MAX_VALUE)
    	    	        );
    	    	        jPanel3Layout.setVerticalGroup(
    	    	            jPanel3Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    	    	            .add(jScrollPane1, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 169, Short.MAX_VALUE)
    	    	        );
    
    	    	//set layout and create textfields
    
    	    	org.jdesktop.layout.GroupLayout jPanel4Layout = new org.jdesktop.layout.GroupLayout(jPanel4);
    	    	        jPanel4.setLayout(jPanel4Layout);
    	    	        jPanel4Layout.setHorizontalGroup(
    	    	                        .add(jPanel4Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
    	    	                            .add(txtPaid)
    	    	                            .add(txtTotal)
    	    	                            .add(txtBalance)))
    	    	                    .add(org.jdesktop.layout.GroupLayout.TRAILING, jPanel4Layout.createSequentialGroup()
    	    	                        .add(0, 0, Short.MAX_VALUE)
    	    	                        .add(jButton1))
    	    	                .addContainerGap();
    	    }
    	    	// override tablechanged method
    
    	    	@Override
    	    	    public void tableChanged (TableModelEvent e){
    	    	        if (e.getType()== TableModelEvent.UPDATE){
    	    	          int row = jTable1.getRowCount();
    	    	            
    	    	            for (int i = 0; i < row; i++){
    	    	                total += Integer.parseInt(jTable1.getValueAt(i, 4).toString());
    	    	            }
    	    	            
    	    	            totalResult = Integer.toString(total);
    	    	            txtTotal.setText(totalResult);  
    	    	        }
    	    	    }
    
    	/**
    	 * Launch the application.
    	 */
    	public static void main(String[] args) {
    		EventQueue.invokeLater(new Runnable() {
    			public void run() {
    				try {
    					Sale frame = new Sale();
    					frame.setVisible(true);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
    			}
    		});
    	}
    
    	
    
    }

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

    Default Re: Calculating values from a jtable column

    My compiler is not tolerating your GroupLayout objects. Is this from a NetBeans' project?

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

    Default Re: Calculating values from a jtable column

    Also, since this is a JInternalFrame, doesn't it need to be inside of a JDesktopPane to be displayed?
    Usually when I'm creating an SSCCE like this, I use the simplest layout possible, often a JPanel's default FlowLayout, and then put the main JPanel either in a JFrame, or if I'm really lazy, in a simple JOptionPane.

Page 1 of 2 12 LastLast

Similar Threads

  1. Replies: 1
    Last Post: 03-24-2011, 12:51 PM
  2. JTable Column Flow
    By anilkumar_vist in forum Advanced Java
    Replies: 3
    Last Post: 10-26-2010, 06:57 AM
  3. calculating with values out of another class
    By senca in forum New To Java
    Replies: 3
    Last Post: 04-08-2010, 03:01 PM
  4. split a jtable column
    By anilkumar_vist in forum Advanced Java
    Replies: 0
    Last Post: 12-14-2009, 10:29 AM
  5. JCheckBox in JTable column
    By hind in forum New To Java
    Replies: 8
    Last Post: 01-04-2009, 07:40 PM

Posting Permissions

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