access textfield outside Jtable

Hi

I have a table for which I maintain a cumulative total for one
of the columns. I'd like to know how to set a textfield outside the jtable to the value of this total.


Regards

Deepa
deepasAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

vladi21Commented:
what about tf.setText((String)table.getValueAt(row,column)) ?
0
jsridharCommented:
there is no single method to add all the values in the column, you could do something like this:

int total = 0;
for (int i = 0; i < table.getRowCount(); i++) {
 total += Integer.parseInt(table.getValueAt(i, column));
}

tf.setText("" + total);

this code assumes you have integer values in the column you wanted to add-up.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
vladi21Commented:
jsridhar: can u post comments?
0
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

deepasAuthor Commented:
the textfield is in a different pane from the table.When I try to settext for the text field I get runtime errors. I've got the total, I just need to display it.
0
vladi21Commented:
post ur code
0
vladi21Commented:
0
deepasAuthor Commented:
Here's the code. I've commented out the settext portion.

import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.AbstractTableModel;
import java.awt.*;
import java.util.*;
import javax.swing.table.*;
import javax.swing.event.*;
import java.text.*;
import javax.swing.DefaultCellEditor;

class DecimalField extends JTextField {
    private NumberFormat format;

    public DecimalField(double value, int columns, NumberFormat f) {
        super(columns);
        format = f;
        setValue(value);
    }

    public double getValue() {
        double retVal = 0.0;

        try {
            retVal = format.parse(getText()).doubleValue();
        } catch (ParseException e) {
            // This should never happen because insertString allows
            // only properly formatted data to get in the field.
            Toolkit.getDefaultToolkit().beep();
            System.err.println("getValue: could not parse: " + getText());
        }
        return retVal;
    }

    public void setValue(double value) {
        setText(format.format(value));
    }
}

class rowrecord
{
      int serial;
      String site,item,um,ppu,discount;
      Double np = new Double(0.0);
      public rowrecord(int serial)
      {
            this.serial = serial;
            this.site = " ";
            this.item = " ";
            this.um = " ";
            this.ppu = " ";
            this.discount = " ";
            this.np = new Double(0.0);;
      }
}


public class New_Prog extends JFrame
implements TableModelListener
{
      public JTextField total;
      JLabel lbl_total;
      int currentval;
      public Vector data = new Vector();
      public int current_row = 1;
      public double total_net_price = 0.0;
      private NumberFormat moneyFormat;
         private NumberFormat percentFormat;
          private DecimalFormat paymentFormat;      
      public  New_Prog()
      
      {
            super("Invoice");
            final DecimalFormat formatter = new DecimalFormat("###,##0.00");
            
            add_vector_data();

            MyTableModel mymodel = new MyTableModel();
            JTable line_items = new JTable( mymodel )
            {
                     public void editingStopped(ChangeEvent e)
                 {
                                  super.editingStopped(e);
                          reCalculate(getModel());
                         
                     }
                };
            mymodel.addKeyListenerToTableCells(line_items);
            mymodel.addTableModelListener(this);
              line_items.setPreferredScrollableViewportSize(new Dimension(500, 70));
            setUpFormats();
            setUpDecimalEditor(line_items);
            
            

            JScrollPane line_items_pane = new JScrollPane(line_items);

            JPanel bottom = new JPanel();
            bottom.setLayout(new BorderLayout());
            
            JLabel lbl_total = new JLabel("Total :");
            JTextField total = new JTextField(8);
            bottom.add("West",lbl_total);
            bottom.add("East",total);
            

            JPanel pane = new JPanel();
            pane.setBorder(BorderFactory.createEmptyBorder(20,20,20,20));
            pane.setLayout(new BorderLayout());
            pane.add("Center",line_items_pane);
            pane.add("South",bottom);
            
            
            setContentPane(pane);
            
            total.setText("" + 0.0);
      }

      public void tableChanged(TableModelEvent e)
      {
            //System.out.println("Hi");
            //total.setText("" + 0.0);
      }

      

      private void setUpDecimalEditor(JTable table)
      {
       
          final DecimalField DecimalField = new DecimalField(5,3,moneyFormat);
          DecimalField.setHorizontalAlignment(DecimalField.RIGHT);

          DefaultCellEditor DecimalEditor =
            new DefaultCellEditor(DecimalField) {
                //Override DefaultCellEditor's getCellEditorValue method
                //to return an Integer, not a String:
                public Object getCellEditorValue() {
                    return new Double(DecimalField.getValue());
                }
            };
        table.setDefaultEditor(Double.class, DecimalEditor);
        }
      
      void add_vector_data()
      {
                  
            data.addElement(new rowrecord(current_row));
            
      }
            
       private void reCalculate(TableModel ml)
       {
           if (ml == null) return;
         double total_np = 0.0;
         if (current_row == 1) return;
         for (int i=0;i<current_row;i++)
         {
              // System.out.println("Double " + ((Double)ml.getValueAt(i,6)).doubleValue());
                 total_np = total_np + ((Double)ml.getValueAt(i,6)).doubleValue();
         }
         System.out.println("Total " + total_np+ " " + current_row);
         //total.setText("" + 0.0);
           

      }


      private void setUpFormats()
      {
        moneyFormat = NumberFormat.getNumberInstance();
        //XXXX: Workaround. With an empty positive suffix
        //the format allows letters in the number.
        ((DecimalFormat)moneyFormat).setPositiveSuffix(" ");

        percentFormat = NumberFormat.getNumberInstance();
        percentFormat.setMinimumFractionDigits(3);
        //XXXX: Workaround. With an empty positive suffix
        //the format allows letters in the number.
        ((DecimalFormat)percentFormat).setPositiveSuffix(" ");

        paymentFormat = (DecimalFormat)NumberFormat.getNumberInstance();
        paymentFormat.setMaximumFractionDigits(2);
        paymentFormat.setNegativePrefix("(");
        paymentFormat.setNegativeSuffix(")");
    }
              
      class MyTableModel extends AbstractTableModel
      
      {
         final String columnNames[] = {"S.No","Site","Item","UM","Price Per Unit",
                            "Discount","Net Price"};
                
         final DecimalFormat formatter = new DecimalFormat("###,##0.00");
       public void addKeyListenerToTableCells(JTable tableV)
        {
       final JTable table = tableV;
         java.awt.event.KeyAdapter listKeyListener = new java.awt.event.KeyAdapter()
       {
            public void keyPressed(java.awt.event.KeyEvent e)
          {
                 
            if ((e.getKeyChar()=='\n') && (table.getRowCount() == (table.getSelectedRow() + 1)) && (table.getColumnCount() == (table.getSelectedColumn() + 1)))
            {
                  add();
                  table.clearSelection();
                  table.setColumnSelectionInterval(1,1);
                  table.clearSelection();
                 }

            
             }
         };
         
        table.addKeyListener(listKeyListener);
       
        }
      

      public int getColumnCount()
      {
              return columnNames.length;
      }
       
      public int getRowCount()
      {
            return data.size();
      }

      public String getColumnName(int col)
      {
            return columnNames[col];
          }

        public Object getValueAt(int row, int col)
        {
                   
         try {
            rowrecord p = (rowrecord)(data.elementAt(row));
            switch (col) {
              case 0:
                  return new Integer(p.serial);
              case 1:
                  return p.site;
              case 2:
                  return p.item;
              case 3:
                  return p.um;
              case 4:
                  return p.ppu;
              case 5:
                  return p.discount;
              case 6:
                  return  (Double)p.np;
            }
             } catch (Exception e) {
           }

           return "";
        }

        public boolean isCellEditable(int row, int col)
        {
            if (col > -1)
            {
                  return true;
            }
            else
                  return false;

          }

      
                  
       public void setValueAt(Object value, int row, int col)
       {
            double total_net_price = 0.0;
            rowrecord u = (rowrecord)data.elementAt(row);
            if (col == 1)
                  u.site = (String)value;
            if (col == 2)
                  u.item = (String)value;
            if (col == 3)
                  u.um = (String)value;
            if (col == 4)
                  u.ppu = (String)value;
            if (col == 5)
                  u.discount = (String)value;
            if (col == 6)
            {
//                  u.np = (Double)value.doubleValue();
                  if (value instanceof Double)
                  {
                         u.np = (Double)value;
                  }
                  else
                  {
                  try
                  {
                        u.np = new Double(((Number)formatter.parse((String)value)).doubleValue());
                  }
                  catch (ParseException ex)
                  {
                         u.np = new Double(0.0);
                  }
                  }
            }            
            data.setElementAt(u,row);
                fireTableCellUpdated(row, col);
            
                  
            

            
         }

        public void add()
          {
        //fireTableChanged(null);
          int index0 = getRowCount();  
          int index1 = 0;  
        current_row++;
        rowrecord p = new rowrecord(current_row);
        data.addElement(p);
          index1 = getRowCount();
          fireTableRowsInserted(index0,index1);
      
        
        
        
       }

      
      }


            
      
      public static void main(String arguments[])
      {
                   try{            

               UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
               } catch (Exception e) {
                  System.err.println("Cant set look and Feel: " + e);                  
                  }

            JFrame frame = new New_Prog();
            WindowListener l = new WindowAdapter()
            {
                  public void windowClosing(WindowEvent e)
                  {
                        System.exit(0);
                  }
            };
            frame.addWindowListener(l);
            frame.pack();
            frame.setVisible(true);
      };
      
}

0
deepasAuthor Commented:
My mistake. I'd declared the total textfield twice. The problem is gone now. Thanks
0
deepasAuthor Commented:
My mistake. I'd declared the total textfield twice. The problem is gone now. Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Editors IDEs

From novice to tech pro — start learning today.