i want to get sum of jtable column n that value display in a jtextfield. so what is the code for that?

Dani AI

Generated

asked how to sum a JTable column and show the result in a JTextField. was on the right track: keep numeric values in the table model and trigger a recalculation when the model changes. The usual pitfalls are storing numbers as Strings, not committing an edit before summing, and not telling the model the column is numeric (which affects editors and renderers).

A minimal, robust approach:

  • Make the model return a numeric column class (so editors produce Number objects).
  • Add a TableModelListener that recalculates the total whenever the model changes.
  • In the recalculation, stop any active cell editing first, iterate rows, convert safely to Number (or parse), accumulate, then format and set the JTextField text.

Example code to attach the listener and compute the sum:

table.getModel().addTableModelListener(e -> updateSum());

private void updateSum() {
    if (table.isEditing()) {
        table.getCellEditor().stopCellEditing();
    }
    TableModel model = table.getModel();
    double sum = 0.0;
    for (int r = 0; r < model.getRowCount(); r++) {
        Object v = model.getValueAt(r, SUM_COLUMN);
        if (v instanceof Number) {
            sum += ((Number) v).doubleValue();
        } else if (v != null) {
            try {
                sum += Double.parseDouble(v.toString());
            } catch (NumberFormatException ex) {
                // ignore or log invalid cell
            }
        }
    }
    textField.setText(String.format("%.2f", sum));
}

Also override getColumnClass in the model so the column returns Double.class (or Integer.class) to keep values numeric. For money use BigDecimal and DecimalFormat for display. For more context on models and listeners, see the Swing table documentation: Swing JTable tutorial.

Recommended Answers

All 2 Replies

  1. put number to JTable column, better to play with model only

  2. override getColumnClass for correct datatype (String, Double, Date, Icon...)

  3. loop in concrete column by call getValueAt, result from this loop to add JTextField

I can't figured it out how to do it. So if you can say me the codes for that. because im new to this field.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.