2021-11-16 (火) 08:22:44
  • category: swing folder: WheelCombo title: JComboBoxの値をMouseWheelで変更 tags: [JComboBox, MouseWheelListener] author: aterai pubdate: 2004-11-15T02:34:50+09:00 description: JComboBoxにフォーカスがある場合、その値をMouseWheelの上下で変更します。 image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TQTWm95sa5I/AAAAAAAAApg/1tiQsmg5QKw/s800/WheelCombo.png

概要

JComboBoxにフォーカスがある場合、その値をMouseWheelの上下で変更します。
http://terai.xrea.jp/swing/wheelcombo/screenshot.png

サンプルコード

#spanend
#spanadd
JComboBox<String> combo = makeComboBox();
#spanend
#spanadd
combo.addMouseWheelListener(new MouseWheelListener() {
#spanend
  @Override public void mouseWheelMoved(MouseWheelEvent e) {
    JComboBox<?> source = (JComboBox<?>) e.getComponent();
    if (!source.hasFocus()) {
      return;
    }
    int ni = source.getSelectedIndex() + e.getWheelRotation();
    if (ni >= 0 && ni < source.getItemCount()) {
      source.setSelectedIndex(ni);
    }
  }
#spanadd
});
#spanend
#spanadd
View in GitHub: Java, Kotlin
combo.addMouseWheelListener(new MouseWheelListener() {
  public void mouseWheelMoved(MouseWheelEvent e) {
    JComboBox source = (JComboBox) e.getSource();
    if(!source.hasFocus()) return;
    int ni = source.getSelectedIndex() + e.getWheelRotation();
    if(ni>=0 && ni<source.getItemCount()) {
      source.setSelectedIndex(ni);
    }
  }
});

解説

上記のサンプルでは、JComboBoxMouseWheelListenerを設定しJComboBoxにフォーカスがある場合はマウスホイールの上下回転イベントに反応して表示内容を順次変更しています。

参考リンク

コメント