Java Swing How to - Align all JTable column right








Question

We would like to know how to align all JTable column right.

Answer

import java.awt.Component;
//  w  ww  . j av a2  s  .  c om
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

public class Main {
  public static void main(String[] args) {

    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 f = new JFrame();
    f.getContentPane().add(scrollPane);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.pack();
    f.setVisible(true);
  }
}