Summary

JTable4隅のセルのみ角を丸めて描画する月次カレンダーを作成します。

Source Code Examples

enum Corner { TOP_LEFT, TOP_RIGHT, BOTTOM_LEFT, BOTTOM_RIGHT }

class CalendarTableRenderer extends DefaultTableCellRenderer {
  private final Set<Corner> roundedCorners = EnumSet.noneOf(Corner.class);
  private final LocalDate realDate = LocalDate.now(ZoneId.systemDefault());
  private int row;
  private int column;

  @Override public Component getTableCellRendererComponent(
      JTable table, Object value, boolean selected,
      boolean focused, int row, int column) {
    Component renderer = super.getTableCellRendererComponent(
        table, value, selected, focused, row, column);
    renderer.setBackground(table.getBackground());
    this.row = row;
    this.column = column;
    updateCorners(table, row, column);
    // ...
    return renderer;
  }

  private void updateCorners(JTable table, int row, int col) {
    roundedCorners.clear();
    TableModel model = table.getModel();
    int lastRow = model.getRowCount() - 1;
    int lastCol = model.getColumnCount() - 1;
    if (row == 0 && col == 0) {
      roundedCorners.add(Corner.TOP_LEFT);
    }
    if (row == 0 && col == lastCol) {
      roundedCorners.add(Corner.TOP_RIGHT);
    }
    if (row == lastRow && col == 0) {
      roundedCorners.add(Corner.BOTTOM_LEFT);
    }
    if (row == lastRow && col == lastCol) {
      roundedCorners.add(Corner.BOTTOM_RIGHT);
    }
  }
  // ...
}
View in GitHub: Java, Kotlin

Description

  • カスタムセルレンダラー:
    • CalendarTableRendererクラスで各セルの描画をカスタマイズし、セルの位置(行・列)に基づいて角丸の対象を判定する
    • 枠線(角丸を含む)はセルレンダラー側で描画するため、JTable側の罫線をすべて非表示に設定
      • JTable#setShowVerticalLines(false)
      • JTable#setShowHorizontalLines(false)
      • JTable#setIntercellSpacing(new Dimension(0, 0))
  • 4隅の判定:
    • Corner enumを使用して、JTableHeaderを除外したJTableの左上(TOP_LEFT)、右上(TOP_RIGHT)、左下(BOTTOM_LEFT)、右下(BOTTOM_RIGHT)を識別し、該当隅のセルのみ角丸で描画する
  • ベジェ曲線による描画:
  • JTableHeaderの透明化:
  • JTableの例として月次カレンダーを作成し、6行×7列のテーブル全体を角丸フレームのように表示

Reference

Comment