Calculate the sum of the last column values ββand put it in a TextField?
I have a Jtable with quantity, price and quantity columns. If the user enters quantity and price, the amount value will be displayed when the key is released. It works great.
I also have one text box below the table that displays the sum of the values ββof the last column of the table.
When the user modifies the data, at the same time the JTextField values ββwill also be changed.
Now I am using the mouse click event. Clicking on the textField will calculate the sum of the values ββof the last column of the table 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 changes values, at the same time this value will be reflected in the text box.
Instead MouseListener
use KeyListener
in 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 be careful that this will be called for every keystroke on a table column. Therefore, you should keep processing within the method keyTyped()
to a minimum.
I believe what you want focusListener
for textField
, since when the user clicks on this textField
this event is fired.
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
}