32

How to center a value in JTable cell? I'm using Netbeans.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Daniel Pereira
  • 435
  • 2
  • 7
  • 13
  • you must be using some other component inside the cell, example JLabel so it would have it's alignment properties. – Amanpreet Sep 15 '11 at 15:53

6 Answers6

72

You need to customize the renderer. To center the first column you can do:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.getColumnModel().getColumn(0).setCellRenderer( centerRenderer );

To center all columns with String data you can do:

DefaultTableCellRenderer centerRenderer = new DefaultTableCellRenderer();
centerRenderer.setHorizontalAlignment( JLabel.CENTER );
table.setDefaultRenderer(String.class, centerRenderer);
camickr
  • 321,443
  • 19
  • 166
  • 288
  • that doesn't work for me. JLabel.RIGHT aligns right, JLabel.LEFT aligns left, but if I use JLabel.CENTER it aligns right again. Why would it be? – giorgiline Nov 02 '12 at 23:53
  • @nawara, JTableHeader has its own renderer. – camickr Aug 16 '13 at 21:51
  • 5
    Though it is an old post, but still it should be better. You should use `SwingConstants.CENTER` rather than `JLabel.CENTER`. Though, `JLabel.CENTER' is also referring to `SwingConstants.CENTER`, it will be much more concise to use generic constant class, rather than `JLabel` which is out of context in this scenario. – Aakash May 20 '15 at 08:45
  • 2
    Why doesn't `((DefaultTableCellRenderer)table.getDefaultRenderer(String.class)).setHorizontalAlignment(SwingConstants.CENTER);` work instead of your second piece of code? -- I've tried it, it doesn't work, I don't know why. No errors, it just remains uncentered. It seems to me this one liner should work. Your code works, of course. – Pimp Trizkit Dec 04 '15 at 12:25
  • I ask the above question because the code: `((DefaultTableCellRenderer)table.getTableHeader().getDefaultRenderer()).setHorizontalAlignment(SwingConstants.CENTER);`... does work for the table header. As mention in this [answer](http://stackoverflow.com/a/7493428/693927). – Pimp Trizkit Dec 04 '15 at 12:33
  • @PimpTrizkit, changing the alignment of the default renderer works fine for me. I can only guess you have some other code that resets the renderer? – camickr Dec 04 '15 at 16:07
  • @camickr - I cant think of what it would be. I got a few lines of code. `JScrollPane sp = new JScrollPane();JTable jt = new JTable(new MyTModel(dataArray, colNames)); ((DefaultTableCellRenderer) jt.getDefaultRenderer(Integer.class)).setHorizontalAlignment(SwingConstants.CENTER); sp.setViewportView(jt); myTPane.addTab("# "+x,sp);` -- I make the table with my custom model, adjust it, set the scroll pane viewport, add scroll pane to tab. And its not centered. Data is ints. – Pimp Trizkit Dec 11 '15 at 05:04
  • @PimpTrizkit, create a proper [SSCCE](http://sscce.org/) that demonstrates your problem and then post a question on the forum. – camickr Dec 11 '15 at 16:27
  • 1
    Wanted to post an observation, using Object.class instead of String.class needs to be used if the data is in a TableModel – Ironluca May 16 '21 at 09:09
  • 1
    @Ironluca *if the data is in a TableModel* - all data is in a TableModel. The default Implementation of the `getColumnClass(...)` method of the DefaultTableModel, simply returns Object.class, so you would be correct. However it is standard to override the `getColumnClass(...)` method to return the proper class of the column so the appropriate renderer can be used. – camickr May 16 '21 at 14:25
  • For me, `Object.class` instead of `String.class` worked (thank you @Ironluca ). Not sure why though. – Mahm00d Nov 30 '21 at 10:57
9

Another good way to center all columns is with a loop:

 for(int x=0;x<numberofcols;x++){
         table1.getColumnModel().getColumn(x).setCellRenderer( centerRenderer );
        }
4

Here you go:

import javax.swing.*;
import javax.swing.table.DefaultTableCellRenderer;
import javax.swing.table.TableModel;

public class JTableUtilities
{
    public static void setCellsAlignment(JTable table, int alignment)
    {
        DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
        rightRenderer.setHorizontalAlignment(alignment);

        TableModel tableModel = table.getModel();

        for (int columnIndex = 0; columnIndex < tableModel.getColumnCount(); columnIndex++)
        {
            table.getColumnModel().getColumn(columnIndex).setCellRenderer(rightRenderer);
        }
    }
}

Usage:

JTableUtilities.setCellsAlignment(table, SwingConstants.CENTER);
BullyWiiPlaza
  • 17,329
  • 10
  • 113
  • 185
2

I had a similar problem. I wanted to align a single cell depending on the value of another cell. If cell X was NULL, then cell Y should be RIGHT aligned. Else, cell Y should be LEFT aligned.

I found this solution really helpful. It consists on creating a custom Render, extending DefaultTableCellRender.

Here's the code:

public class MyRender extends DefaultTableCellRenderer{

@Override
 public Component getTableCellRendererComponent(JTable table,Object value,boolean isSelected,boolean hasFocus,int row,int column){
    super.getTableCellRendererComponent (table, value, isSelected, hasFocus, row, column);
    MyTableModel mtm = (MyTableModel)table.getModel();
    switch(column){
        case Y : 
            if(mla.getValueAt(row,X)!=null)
                setHorizontalAlignment(SwingConstants.RIGHT);
            else
                setHorizontalAlignment(SwingConstants.LEFT);
            break;
     }
    return this;
   }

 }

After that, just create a new instance of MyRender and set it to column Y, in this case. I do this when I load the information on the table.

MyRender render = new MyRender();
table.getColumnModel().getColumn(Y).setCellRender(render);

Hope it's useful!

Suever
  • 64,497
  • 14
  • 82
  • 101
jUNT
  • 41
  • 5
2
((DefaultTableCellRenderer) jTable1.getTableHeader().getDefaultRenderer())
            .setHorizontalAlignment(JLabel.CENTER); // header to center

This code header center jtable

DefaultTableCellRenderer rendar = new DefaultTableCellRenderer();
    rendar.setHorizontalAlignment(jLabel1.CENTER);

    jTable1.getColumnModel().getColumn(0).setCellRenderer(rendar); 

this code to column center

Shinwar ismail
  • 299
  • 2
  • 9
1

Instead of JLabel.CENTER, you can use SwingConstants.CENTER.

1ac0
  • 2,875
  • 3
  • 33
  • 47