Comment

JTableのセルに表示されている文字列の揃えを変更します。

Comment

TableColumn col = table.getColumnModel().getColumn(1);
col.setCellRenderer(new HorizontalAlignmentTableRenderer());
// ...
class HorizontalAlignmentTableRenderer extends DefaultTableCellRenderer {
  @Override public Component getTableCellRendererComponent(JTable table,
        Object value, boolean isSelected, boolean hasFocus, int row, int column) {
    Component c = super.getTableCellRendererComponent(
        table, value, isSelected, hasFocus, row, column);
    if (c instanceof JLabel) {
      initLabel((JLabel) c, row);
    }
    return c;
  }

  private void initLabel(JLabel l, int row) {
    if (leftRadio.isSelected()) {
      l.setHorizontalAlignment(SwingConstants.LEFT);
    } else if (centerRadio.isSelected()) {
      l.setHorizontalAlignment(SwingConstants.CENTER);
    } else if (rightRadio.isSelected()) {
      l.setHorizontalAlignment(SwingConstants.RIGHT);
    } else if (customRadio.isSelected()) {
      l.setHorizontalAlignment(row % 3 == 0 ? SwingConstants.LEFT:
                               row % 3 == 1 ? SwingConstants.CENTER:
                                              SwingConstants.RIGHT);
    }
  }
}
View in GitHub: Java, Kotlin

Comment

上記のサンプルでは、JTableの第1列目のセルに表示されている文字列の揃えを変更するテストを行っています。


Comment

Comment