How to control decimal places displayed in JTable column?

Java, Swing 10.9.2015 1 Comment

Rendering of table cells is handled by instances of TableCellRenderer. By default JTable uses a DefaultTableCellRenderer to render all of its cells.
To control the number of decimal places used we just need to subclass DefaultTableCellRenderer and format the cell double value before passing the (formatted) value to to the parent (DefaultTableCellRenderer) class.
To get the table to use that class we tell the JTable to use it for a given column.

Following example illustrates what is required.

package com.learnjava.swing.table;

import java.awt.*;
import java.text.DecimalFormat;
import javax.swing.*;
import javax.swing.table.*;

public class DecimalPlacesInTable extends JFrame {
	public static void main( String[] args ) {
		DecimalPlacesInTable frame = new DecimalPlacesInTable();
		frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
		frame.pack();
		frame.setVisible( true );
	}

	public DecimalPlacesInTable() {
		Object[] columnNames = { "A", "B", "C" };
		Object[][] data = {
				{ "abc", new Double( 850.503 ), 5 },
				{ "def", new Double( 36.23254 ), 6 },
				{ "ghi", new Double( 8.3 ), 7 },
				{ "jkl", new Double( 246.0943 ), 23 }};

		JTable table = new JTable(data, columnNames);

        // Tell the table what to use to render our column of doubles

		table.getColumnModel().getColumn(1).setCellRenderer(
			new DecimalFormatRenderer() );
		getContentPane().add(new JScrollPane(table));
	}

        /**
         Here is our class to handle the formatting of the double values
         */

	static class DecimalFormatRenderer extends DefaultTableCellRenderer {
		private static final DecimalFormat formatter = new DecimalFormat( "#.00" );

		public Component getTableCellRendererComponent(
			JTable table, Object value, boolean isSelected,
			boolean hasFocus, int row, int column) {

			// First format the cell value as required

			value = formatter.format((Number)value);

            // And pass it on to parent class

			return super.getTableCellRendererComponent(
				table, value, isSelected, hasFocus, row, column );
		}
	}
}

One Response to “How to control decimal places displayed in JTable column?”

  1. Liz Tejada

    Thank you so much it worked perfect for me 🙂

Leave a Reply

s2Member®