---
category: swing
folder: CalendarViewTable
title: JTableにLocaleを考慮したLocalDateを適用してカレンダーを表示する
tags: [JTable, LocalDate, Locale]
author: aterai
pubdate: 2018-01-29T14:57:32+09:00
description: JTableに週の最初の曜日がLocaleに応じて変化するカレンダーを表示します。
image: https://drive.google.com/uc?export=view&id=1jXZtiYFaA5ABWsdaRBnPUKqS2_VBDkFqQA
---
* 概要 [#summary]
`JTable`に週の最初の曜日が`Locale`に応じて変化するカレンダーを表示します。

#download(https://drive.google.com/uc?export=view&id=1jXZtiYFaA5ABWsdaRBnPUKqS2_VBDkFqQA)

* サンプルコード [#sourcecode]
#code(link){{
class CalendarViewTableModel<T extends LocalDate> extends DefaultTableModel {
  private final LocalDate startDate;
  private final WeekFields weekFields = WeekFields.of(Locale.getDefault());
  protected CalendarViewTableModel(T date) {
    super();
    LocalDate firstDayOfMonth = YearMonth.from(date).atDay(1);
    int dowv = firstDayOfMonth.get(weekFields.dayOfWeek()) - 1;
    startDate = firstDayOfMonth.minusDays(dowv);
  }
  @Override public Class<?> getColumnClass(int column) {
    return LocalDate.class;
  }
  @Override public String getColumnName(int column) {
    return weekFields.getFirstDayOfWeek().plus(column)
      .getDisplayName(TextStyle.SHORT_STANDALONE, Locale.getDefault());
  }
  @Override public int getRowCount() {
    return 6;
  }
  @Override public int getColumnCount() {
    return 7;
  }
  @Override public Object getValueAt(int row, int column) {
    return startDate.plusDays(row * getColumnCount() + column);
  }
  @Override public boolean isCellEditable(int row, int column) {
    return false;
  }
}
}}

* 解説 [#explanation]
上記のサンプルでは、モデルに`Java 8`から`java.time`パッケージに追加された`LocalDate`を使用し、`JTable`に月のカレンダーを表示しています。

- [https://docs.oracle.com/javase/jp/8/docs/api/java/time/temporal/WeekFields.html#getFirstDayOfWeek-- WeekFields#getFirstDayOfWeek()]メソッドで`Locale`に応じた週の最初の曜日を取得して、`JTable`の`0`列目を設定
-- 例: フランスと`ISO-8601`標準では月曜日が週の最初の曜日になる
--- `"$JAVA_HOME/bin/java" -Duser.language=fr -jar example.jar`
#img2(https://drive.google.com/uc?export=view&id=1jXZtiYFaA5ABWsdaRBnPUKqS2_VBDkFqQA)

* 参考リンク [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/java/time/temporal/WeekFields.html#getFirstDayOfWeek-- WeekFields#getFirstDayOfWeek() (Java Platform SE 8)]
- [https://tips4java.wordpress.com/2015/04/22/local-date-combo/ Local Date Combo « Java Tips Weblog]

* コメント [#comment]
#comment
#comment