• category: swing folder: SingleIntervalMouseSelection title: JListでカレンターを作成しマウスドラッグで日付の範囲を選択する tags: [JList, MouseListener, MouseMotionListener] author: aterai pubdate: 2021-12-27T01:14:01+09:00 description: JListで作成したカレンダーでマウスドラッグによる日付の範囲選択を実行します。 image: https://drive.google.com/uc?id=1f36wJuNyEM2Y1q80GHrW97uGZfTUfsNU

概要

JListで作成したカレンダーでマウスドラッグによる日付の範囲選択を実行します。

サンプルコード

class SingleIntervalMouseSelectionListener extends MouseInputAdapter {
  private int start = -1;

  @Override public void mousePressed(MouseEvent e) {
    JList<?> l = (JList<?>) e.getComponent();
    start = l.locationToIndex(e.getPoint());
    l.getSelectionModel().addSelectionInterval(start, start);
  }

  @Override public void mouseDragged(MouseEvent e) {
    JList<?> l = (JList<?>) e.getComponent();
    int end = l.locationToIndex(e.getPoint());
    l.getSelectionModel().addSelectionInterval(start, end);
  }
}
View in GitHub: Java, Kotlin

解説

上記のサンプルではJListで月のカーソルキー移動や、週を跨いた日付を範囲選択が可能なカレンダーを作成するで作成した「ニュースペーパー・スタイル」レイアウトを適用したJListカレンダーにMouseListenerMouseMotionListener`を追加してマウスドラッグによる日付の範囲選択を可能にしています。

参考リンク

コメント