Question

Is there a way to align all the column in jtable at the same time? using this:

DefaultTableCellRenderer rightRenderer = new DefaultTableCellRenderer();
rightRenderer.setHorizontalAlignment( JLabel.RIGHT );
JTAB_TABLE.getColumnModel().getColumn(0).setCellRenderer( rightRenderer );

will let me align only one column but i need to align all.

Was it helpful?

Solution

Normally, a table contains different kinds of data, (Date, Number, Boolean, String) and it doesn't make sense to force all types of data to be right aligned.

If however you have a table with all the same type of data and you want to force the renderering of all columns to be the same, then you should probably use the same renderer. Assuming you are using the default renderer you can use:

DefaultTableCellRenderer renderer = (DefaultTableCellRenderer)table.getDefaultRenderer(Object.class);
renderer.setHorizontalAlignment( JLabel.RIGHT );

OTHER TIPS

You can do so by overriding prepareRenderer(...) in JTable. This assumes that any custom renderers are JLabels (they're JLabels by default). You'd have to guard against it otherwise.

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

public class TableDemo implements Runnable
{
  public static void main(String[] args)
  {
    SwingUtilities.invokeLater(new TableDemo());
  }

  public void run()
  {
    JTable table = new JTable(5, 5)
    {
      @Override
      public Component prepareRenderer(TableCellRenderer renderer,
                                       int row, int col)
      {
        Component comp = super.prepareRenderer(renderer, row, col);
        ((JLabel) comp).setHorizontalAlignment(JLabel.RIGHT);
        return comp;
      }
    };
    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    JScrollPane scrollPane = new JScrollPane(table);

    JFrame frame = new JFrame();
    frame.getContentPane().add(scrollPane);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top