Page 1 of 2 12 LastLast
Results 1 to 20 of 40
  1. #1
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default Total column issue again

    I'm trying to add up the total for the last column and print it out in the last column of the last row. But this code doesn't work, please help. Attached is my program, please change it to .java if need to compile.

    calButton.addActionListener(new ActionListener(){
    public void actionPerformed (ActionEvent e) {
    int i=lastRow; //lastRow is the last row where total is
    while(i > 1){ //loop until the first row, notice it doesn't read the first row.
    Object value = model.getValueAt(i-1, 4 );
    total = total + (Float) value;
    }
    model.setValueAt(total, lastRow, 4 ); //setting the value to the last row
    }
    });

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    But this code doesn't work
    Can you explain what is wrong with it. Show what it does and what you want it to do.

    Where do you change the value of i, the loop control variable?

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

    Default

    You might want to create and post an SSCCE. Please check out the link as it will explain all. Also, you're better off using code tags when posting code rather than indents. The link in my signature will show you how. Much luck!

  4. #4
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    Thank you, Norm. I've figured out my issue. I was using 'total = total + (Float) value;'
    which was the problem. I had to use 'total = total + Double.parseDouble( String.valueOf( value ) );'

    Is this because value (an Object) is also a String? I'm confuse why I need to use String.valueOf and parse it.

  5. #5
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    Thank you, Norm. I've figured out my issue. I was using 'total = total + (Float) value;'
    which was the problem. I had to use 'total = total + Double.parseDouble( String.valueOf( value ) );'

    Is this because value (an Object) is also a String? I'm confuse why I need to use String.valueOf and parse it.
    Only you know if your table model contains Strings or not. An Object is not automagically also a String. b.t.w. your code adds values of a single column #4 and tries to put the total in the last row. The first index is the row index, the second index is the column index; you should also adjust the value of 'i' in your while loop.

    kind regards,

    Jos

  6. #6
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    Yeah, I fixed my code and incremented i in the loop. Thank you.

  7. #7
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    Yeah, I fixed my code and incremented i in the loop. Thank you.
    According to the structure of your original loop you should decrement i. I prefer a for-loop:

    Java Code:
    total= 0.0;
    for (int i= 1; i < lastRow; i++)
       total+=  ...;
    kind regards,

    Jos

  8. #8
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    This is what I changed it to.
    XML Code:
    public void actionPerformed (ActionEvent e) {
       double total=0;
       for(int i=1; i<lastRow; i++){
          Object value = model.getValueAt(i, 4 );
          total += Double.parseDouble( String.valueOf( value ) );
       }
       model.setValueAt(total, lastRow, 4 );
    }
    What do you think?

  9. #9
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    This is what I changed it to.
    XML Code:
    public void actionPerformed (ActionEvent e) {
       double total=0;
       for(int i=1; i<lastRow; i++){
          Object value = model.getValueAt(i, 4 );
          total += Double.parseDouble( String.valueOf( value ) );
       }
       model.setValueAt(total, lastRow, 4 );
    }
    What do you think?
    Bettter, much better; but why do you convert the values in all the rows to Strings first and parse them to a double value?

    kind regards,

    Jos

  10. #10
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    At first I wanted float, as I debugging my program. Double somehow came in place, and once I got it to work. I left it as double, any issue with that? would float variable be better?

  11. #11
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    oops, didn't your question correctly.

    if I do total += (double) value, it didn't work before. So I did some searching. I found an example of getting the cell value and assign it to an object. After that they convert to String then parse.

  12. #12
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    oops, didn't your question correctly.

    if I do total += (double) value, it didn't work before. So I did some searching. I found an example of getting the cell value and assign it to an object. After that they convert to String then parse.
    You have to cast your table value to Double (capital D) because that's what it actually is; there is no need to first cast it to a String and parse it to a double value later.

    kind regards,

    Jos

  13. #13
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    even with Double, it still won't work.

  14. #14
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    I got the following error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at MoneyNest4You$3.actionPerformed(MoneyNest4You.java :116)

  15. #15
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    even with Double, it still won't work.
    Only you know the type of the objects in your table model. If they are Doubles, cast them to Double; if they are Floats, cast them to Float. They are definitely numbers because otherwise the method Double.parseDouble( ... ) would've failed ...

    kind regards,

    Jos

  16. #16
    JosAH's Avatar
    JosAH is offline Moderator
    Join Date
    Sep 2008
    Location
    Voorschoten, the Netherlands
    Posts
    13,361
    Blog Entries
    7
    Rep Power
    20

    Default

    Quote Originally Posted by ninjalord918 View Post
    I got the following error:
    Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Double
    at MoneyNest4You$3.actionPerformed(MoneyNest4You.java :116)
    Show us what you did, we are replying out of phase now ...

    kind regards,

    Jos

  17. #17
    camickr is offline Senior Member
    Join Date
    Jul 2009
    Posts
    1,234
    Rep Power
    7

    Default

    There should be no need to do any parsing since you should be storing Double values in the TableModel, not String values. Here is a simple example:

    Java Code:
    import java.awt.*;
    import javax.swing.*;
    import javax.swing.event.*;
    import javax.swing.table.*;
    
    public class TableProcessing extends JFrame implements TableModelListener
    {
    	JTable table;
    
    	public TableProcessing()
    	{
    		super("Table");
    		String[] columnNames = {"Item", "Quantity", "Price", "Cost"};
    		Object[][] data =
    		{
    			{"Bread", new Integer(1), new Double(1.11), new Double(1.11)},
    			{"Milk", new Integer(1), new Double(2.22), new Double(2.22)},
    			{"Tea", new Integer(1), new Double(3.33), new Double(3.33)},
    			{"Cofee", new Integer(1), new Double(4.44), new Double(4.44)}
    		};
    
    		DefaultTableModel model = new DefaultTableModel(data, columnNames);
    		model.addTableModelListener( this );
    //
    		table = new JTable( model )
    		{
    			//  Returning the Class of each column will allow different
    			//  renderers to be used based on Class
    			public Class getColumnClass(int column)
    			{
    				return getValueAt(0, column).getClass();
    			}
    
    			//  The Cost is not editable
    			public boolean isCellEditable(int row, int column)
    			{
    				int modelColumn = convertColumnIndexToModel( column );
    				return (modelColumn == 3) ? false : true;
    			}
    		};
    		table.setPreferredScrollableViewportSize(table.getPreferredSize());
    //
    		JScrollPane scrollPane = new JScrollPane( table );
    		getContentPane().add( scrollPane );
    
    
    		String[] items = { "Bread", "Milk", "Tea", "Coffee" };
    		JComboBox editor = new JComboBox( items );
    
    		DefaultCellEditor dce = new DefaultCellEditor( editor );
    		table.getColumnModel().getColumn(0).setCellEditor(dce);
    	}
    
    	/*
    	 *  The cost is recalculated whenever the quantity or price is changed
    	 */
    	public void tableChanged(TableModelEvent e)
    	{
    		if (e.getType() == TableModelEvent.UPDATE)
    		{
    			int row = e.getFirstRow();
    			int column = e.getColumn();
    
    			if (column == 1 || column == 2)
    			{
    				TableModel model = table.getModel();
    				int	quantity = ((Integer)model.getValueAt(row, 1)).intValue();
    				double price = ((Double)model.getValueAt(row, 2)).doubleValue();
    				Double value = new Double(quantity * price);
    				model.setValueAt(value, row, 3);
    			}
    		}
    	}
    
    	public static void main(String[] args)
    	{
    		TableProcessing frame = new TableProcessing();
    		frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
    		frame.pack();
    		frame.setLocationRelativeTo( null );
    		frame.setVisible(true);
    	}
    }

  18. #18
    ninjalord918 is offline Member
    Join Date
    Jul 2010
    Posts
    30
    Rep Power
    0

    Default

    Here is my completed code. First of all, when I compile this. I got two windows, I can't seem to figure out why there's a small window. Second, my table title row doesn't show in the right panel, so that's why I repeated the titles again in the table. Third is the total column issue, I tried not parsing the double and got errors.

    XML Code:
    import javax.swing.*;
    import javax.swing.event.TableModelEvent;
    import javax.swing.event.TableModelListener;
    import javax.swing.table.DefaultTableModel;
    import javax.swing.table.TableColumn;
    import javax.swing.table.TableModel;
    import javax.swing.ImageIcon;
    
    import java.awt.BorderLayout;
    import java.awt.Color;
    import java.awt.Dimension;
    import java.awt.GridLayout;
    import java.awt.event.*;
    
    import java.awt.event.ActionListener;
    import java.awt.event.ActionEvent;
    import java.text.NumberFormat;
    
    public class MoneyNest4You extends JFrame implements TableModelListener{
    	protected static final String[][] Object = null;
    	private static int lastRow=2;
    	private static int firstRowNum=0;
    	private static int rowCount=2;
    	//private float total=0;
    	private static int columnNum=1;
    	JTable table;
    	
    	
    	public MoneyNest4You (){
    		String[] columnTitles = {"First Name",
    	            "Last Name",
    	            "Account Type",
    	            "Account Number",
    	            "Transaction Amount"};
    
    	Object[][] data = {
    	{"<html><b><font color=blue>First Name</font></b></html>", "<html><b><font color=blue>Last Name</font></b></html>",
    	"<html><b><font color=blue>Account Type</font></b></html>", "<html><b><font color=blue>Account Number</font></b></html>", "<html><b><font color=blue>Transaction Amount</font></b></html>"},
    	{"","","","", new Double(0)},
    	{"<html><b><font color=blue>Total</font></b></html>","","","", new Double(0)}};
    		JFrame frame = new JFrame("MoneyNest4You");
    		frame.setVisible(true);
    		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    		frame.setSize(1010, 300);
    		JMenuBar menubar = new JMenuBar();
    		frame.setJMenuBar(menubar);
    		JMenu file = new JMenu("File");
    		menubar.add(file);
    		ImageIcon exitIcon = new ImageIcon("src/exit.png");
    		JMenuItem exit = new JMenuItem("Exit", exitIcon);
    
    		file.add(exit);
    		
    		JMenu help = new JMenu("Help");
    		menubar.add(help);
    		JMenuItem about = new JMenuItem("About");
    		help.add(about);
    		
    		
    		JPanel leftpane = new JPanel();
    		JPanel rightpane = new JPanel();
    		JSplitPane splitpane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, leftpane, rightpane);
    		frame.add(splitpane);
    		splitpane.setOneTouchExpandable(true);
    		splitpane.setDividerLocation(200);
    		leftpane.setBackground(Color.white);
    		rightpane.setBackground(Color.gray);
    		leftpane.setLayout(new GridLayout(3,1));
    		rightpane.setLayout(new GridLayout(2,1));
    		ImageIcon calIcon = new ImageIcon("src/cal.png");
    		JButton calButton = new JButton("Calculate", calIcon);
    		JButton predictButton = new JButton("Predict");
    		JButton insertRowButton = new JButton("Insert Row");
    		leftpane.add(calButton);
    		leftpane.add(predictButton);
    		leftpane.add(insertRowButton);
    
    		final DefaultTableModel model = new DefaultTableModel(data, columnTitles){
    			 public boolean isCellEditable( int row, int col )  
    			 	{  
    				 	if ( row != firstRowNum && row!= lastRow ){  
    				 		return true;  
    				 	}  
    				 	else {  
    				 		return false;  
    				 	}  
    			 	}  
    		};
    		model.addTableModelListener(null);
    		table = new JTable(model);
    		table.setPreferredSize(new Dimension(760, 300));
    		rightpane.add(table);
    		
    		JScrollPane scroll = new JScrollPane(rightpane);
    		splitpane.add(scroll);
    		
    		
    		
    		insertRowButton.addActionListener(new ActionListener(){	
    			public void actionPerformed (ActionEvent e) {
    				model.insertRow(1, new Object[]{"","","","", new Double(0)});
    				rowCount++;
    				lastRow++;
    			}
    		});		
    		
    		calButton.addActionListener(new ActionListener(){	
    			public void actionPerformed (ActionEvent e) {
    					Double total = null;
    				for(int i=1; i<lastRow; i++){
    					double value = ((Double)model.getValueAt(i, 4 )).doubleValue();
    				    total += new Double(value);
    				}
    				model.setValueAt(total, lastRow, 4 );
    			}
    		});
    		
    		
    		class exitaction implements ActionListener{
    			public void actionPerformed (ActionEvent e) {
    				System.exit(0);
    			}
    		}
    		
    		exit.addActionListener(new exitaction());
    	}
    	
    
    	public static void main(String[] args)
    	{
    		MoneyNest4You mn4y = new MoneyNest4You();
    		mn4y.setDefaultCloseOperation( EXIT_ON_CLOSE );
    		mn4y.pack();
    		mn4y.setLocationRelativeTo( null );
    		mn4y.setVisible(true);
    	}
    
    
    	@Override
    	public void tableChanged(TableModelEvent arg0) {
    		// TODO Auto-generated method stub
    		
    	}
    
    
    }

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

    Default

    You may wish to simplify your code a lot to get a better answer than this, but one thing that bugs me quite a bit is that you've got your column headers mixed in with your 2D object arrays, and it begs the question, why? This will prevent the last column of data from all being Double objects. Also, you don't appear to be displaying the true headers anywhere.

  20. #20
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,306
    Rep Power
    25

    Default

    A couple of suggestions to solve your First problem:
    1)Change this:
    JFrame frame = new JFrame("MoneyNest4You");
    to this:
    JFrame frame = this;

    2) Move the setVisible() call to AFTER the GUI has finished being setup.

Page 1 of 2 12 LastLast

Similar Threads

  1. insert row and column and delete row and column
    By daredavil82 in forum New To Java
    Replies: 13
    Last Post: 09-22-2011, 06:10 PM
  2. Replies: 1
    Last Post: 07-06-2010, 04:50 PM
  3. Replies: 2
    Last Post: 12-10-2009, 12:06 PM
  4. Total noob
    By J_Walker in forum New To Java
    Replies: 9
    Last Post: 04-24-2009, 03:10 AM
  5. total beginner needs little help
    By asambasamba in forum New To Java
    Replies: 1
    Last Post: 06-18-2008, 05:33 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
  •