Calculate the sum of a last column values and put it on TextField?

1.2k views Asked by At

I have a Jtable with columns of Quantity, price and amount. If the user enters quantity and price, the amount value will show at the time of key releasing. It's working perfectly.

I am also having one textfield below the table, that shows the sum of table's last column values.

When the user changes the data, at the same time the JTextField values also will be change.

Now I am using a mouse click event. When clicking on the textField it will calculate sum of table last column values and display.

Can anyone help me?

Here is my code:

int rowCount = Table.getRowCount();

int lastRow = rowCount - 1;

//System.out.println("Last Row = " + lastRow);
//System.out.println("Last Row Value is = " + Table.getValueAt(lastRow, 0));

if (Table.getValueAt(lastRow, 0) == null) {
  DefaultTableModel tmodel = (DefaultTableModel) Table.getModel();
  tmodel.removeRow(lastRow);
} 
else {
  double value;
  double total = 0;

  //System.out.println("Row Count = " + rowCount);
  for (int i = 0; i < rowCount; i++) {
    value = (double) Table.getValueAt(i, 5);
    total = total + value;
  }

  totalField.setText(new DecimalFormat("##.##").format(total));
}

But I don't want this mechanism.

When the user enters some values or modifies the values, at the same time that value will reflect in Textfield.

2

There are 2 answers

0
Codebender On BEST ANSWER

Instead of MouseListener, use a KeyListener on the JTable.

    table.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent arg0) {
            // You can set the value of textField to the value of Jtable column here.

        }

        @Override
        public void keyReleased(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }

        @Override
        public void keyPressed(KeyEvent arg0) {
            // TODO Auto-generated method stub

        }
    });

But beware that this will be called for every keystroke on the table column. So you should keep the processing inside the keyTyped() method to a minimum.

0
Uma Kanth On

I believe you want a focusListener for the textField, as and when a user clicks on this textField this event gets triggered.

Get the values from the table and do the math here.

JTextField textField = new JTextField("A TextField");
textField.addFocusListener(new FocusListener() {
    public void focusGained(FocusEvent e) {
       //do here
      }