2

有没有办法同时对齐 jtable 中的所有列?使用这个:

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

让我只对齐一列,但我需要全部对齐。

4

2 回答 2

5

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 );
于 2013-09-20T22:14:39.750 回答
2

您可以通过prepareRenderer(...)在 JTable 中覆盖来实现。这假定任何自定义渲染器都是 JLabels(默认情况下它们是 JLabels)。否则你必须提防它。

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);
  }
}
于 2013-09-20T21:15:37.817 回答