Swing/AutoRepeatTimer のバックアップ(No.15)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/AutoRepeatTimer へ行く。
  - 1 (2015-06-08 (月) 00:01:19)
- 2 (2017-03-15 (水) 18:28:17)
- 3 (2017-10-18 (水) 13:40:43)
- 4 (2019-04-09 (火) 15:50:08)
- 5 (2021-01-19 (火) 19:34:01)
- 6 (2022-05-02 (月) 01:19:27)
- 7 (2022-08-29 (月) 01:50:40)
- 8 (2023-09-29 (金) 11:00:25)
- 9 (2025-01-03 (金) 08:57:02)
- 10 (2025-01-03 (金) 09:01:23)
- 11 (2025-01-03 (金) 09:02:38)
- 12 (2025-01-03 (金) 09:03:21)
- 13 (2025-01-03 (金) 09:04:02)
- 14 (2025-06-19 (木) 12:41:37)
- 15 (2025-06-19 (木) 12:43:47)
 
- category: swing
folder: AutoRepeatTimer
title: JButtonがマウスで押されている間、アクションを繰り返すTimerを設定する
tags: [JButton, ActionListener, MouseListener, Timer]
author: aterai
pubdate: 2015-06-08T00:00:32+09:00
description: JButtonがマウスで押されている間は指定したアクションを繰り返し実行するTimerを設定します。
image:  
Summary
JButtonがマウスで押されている間は指定したアクションを繰り返し実行するTimerを設定します。
Screenshot

Advertisement
Source Code Examples
class AutoRepeatHandler extends MouseAdapter implements ActionListener {
  private final Timer autoRepeatTimer;
  private final BigInteger extent;
  private final JTextComponent view;
  private JButton arrowButton;
  protected AutoRepeatHandler(int extent, JTextComponent view) {
    super();
    this.extent = BigInteger.valueOf(extent);
    this.view = view;
    autoRepeatTimer = new Timer(60, this);
    autoRepeatTimer.setInitialDelay(300);
  }
  @Override public void actionPerformed(ActionEvent e) {
    Object o = e.getSource();
    if (o instanceof Timer) {
      boolean released= arrowButton != null && !arrowButton.getModel().isPressed();
      if (released && autoRepeatTimer.isRunning()) {
        autoRepeatTimer.stop();
        // arrowButton = null;
      }
    } else if (o instanceof JButton) {
      arrowButton = (JButton) o;
    }
    BigInteger i = new BigInteger(view.getText());
    view.setText(i.add(extent).toString());
  }
  @Override public void mousePressed(MouseEvent e) {
    if (SwingUtilities.isLeftMouseButton(e) && e.getComponent().isEnabled()) {
      autoRepeatTimer.start();
    }
  }
  @Override public void mouseReleased(MouseEvent e) {
    autoRepeatTimer.stop();
    arrowButton = null;
  }
  @Override public void mouseExited(MouseEvent e) {
    if (autoRepeatTimer.isRunning()) {
      autoRepeatTimer.stop();
    }
  }
}
Description
上記のサンプルでは、JButtonをクリックすると編集不可のJTextFieldに表示される数値を増減するActionListenerと、JButtonが押されている間はこのアクションを自動的にリピートするTimerを起動するためのMouseListenerのふたつのリスナーを設定しています。
- JSpinnerで使用されている- javax.swing.plaf.basic.BasicSpinnerUI内の- ArrowButtonHandlerと、このサンプルで使用している- Timerのリピート間隔(- 60ms)や初回起動までの時間(- 300ms)は同じ値を使用している
Reference
- BasicSpinnerUI (Java Platform SE 8)
- JSliderの値を増減するJButtonを作成する
- JTabbedPaneのタブスクロールボタンで連続スクロールを実行する
- jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSpinnerUI.java at master · openjdk/jdk