It seems simple, but it takes more than a few lines of code to make data look neat and tidy. In this Java Q&A, we’ll provide code that allows you to do this, and we’ll explain where the complications lie.

Q: How do you justify (align vertically and horizontally) data within a cell in a Jtable, and why does such a common feature require so much effort to implement?


A: We’ve set up a sidebar with an example to illustrate how you can horizontally align data within a cell in a JTable. In particular, consider the code snippet:

   private DefaultTableCellRenderer renderer = new
   private JTable table;

   private void setTableCellAlignment(int alignment) {
      for (int i=0; i<table.getColumnCount();i++){
      // repaint to show table cell changes


The renderer.setHorizontalAlignment(int alignment)—a method inherited from JLabel that accepts the constants JLabel.LEFT, JLabel.CENTER, or JLabel.RIGHT—does the actual work of aligning the data within the cell. Each cell within a JTable implements a renderer object to aid in the presentation of the cell’s data. Therefore, once the renderer alignment property has been set, it needs to be associated with each cell in the table. One way to accomplish the association is to retrieve all the columns of the table and set their cell renderer property. Hence, the above forloop cycles on the number of columns and uses the available method table.setDefaultRenderer(…).

Lastly, since there were property changes to the underlying structures of the JTable, a call to validate the JTable is performed via table.updateUI().

Why the effort for such a common feature?
Within the JTable, each cell is responsible for the data it contains, in terms of presentation, datatype, etc. Thus, a “simple” change to presentation requires a visit to each cell to change a display property. Though this may seem cumbersome, it also lends itself to extreme flexibility, since each cell can contain its own distinct renderer, if necessary. More likely, you’ll have an entire column within a JTable display differently from another column.

To set one column’s cell renderer properties, consider using the following code, where Value is a column name inside a JTable:


 TableColumn tc = table.getColumn(“Value”);


The table.getColumn(“Value”) method obtains the entire Value column from the JTable as a TableColumn object. Every cell’s renderer can be set within the column with one command, tc.setCellRenderer(renderer).



Java help

Got a Java question?’s technical staff can help. Send us your Java question, and we’ll take a crack at it.