Swing/ItemListenerActionListener のバックアップ(No.8)
- バックアップ一覧
 - 差分 を表示
 - 現在との差分 を表示
 - 現在との差分 - Visual を表示
 - ソース を表示
 - Swing/ItemListenerActionListener へ行く。
 
- category: swing folder: ItemListenerActionListener title: ItemListenerとActionListenerの動作の違いを比較する tags: [ItemListener, ActionListener, JComboBox, JCheckBox, JRadioButton, ButtonGroup] author: aterai pubdate: 2018-04-23T18:28:12+09:00 description: JComboBoxやJCheckBoxなどに設定したItemListenerとActionListenerの動作を比較テストします。 image: https://drive.google.com/uc?id=1xpBmSl-frNjI1eCiUe2pzY2vo6Zp_FpKjA
 
Summary
JComboBoxやJCheckBoxなどに設定したItemListenerとActionListenerの動作を比較テストします。
Screenshot

Advertisement
Source Code Examples
JComboBox<DayOfWeek> combo = new JComboBox<>(DayOfWeek.values());
combo.addItemListener(e -> {
  ItemSelectable c = e.getItemSelectable();
  DayOfWeek dow = (DayOfWeek) e.getItem();
  boolean b = e.getStateChange() == ItemEvent.SELECTED;
  print(textArea, "ItemListener", c.getClass(), b, dow);
});
combo.addActionListener(e -> {
  Object c = e.getSource();
  DayOfWeek dow = combo.getItemAt(combo.getSelectedIndex());
  boolean b = Objects.equals("comboBoxChanged", e.getActionCommand());
  print(textArea, "ActionListener", c.getClass(), b, dow);
});
View in GitHub: Java, KotlinExplanation
JComboBox
ItemListenerItemEvent#getItemSelectable()でイベント元のJComboBoxが取得可能ItemEvent#getItem()でJComboBoxで選択されたアイテムが取得可能ItemEvent#getStateChange()でJComboBoxのアイテムが選択、選択解除されたかを取得可能JComboBox#setSelectedIndex(...)メソッドなどを使用してJComboBoxを直接マウスやキー入力で操作しなくてもItemEventは発生するJComboBoxの同じアイテムを選択してもItemEventは発生しない
ActionListenerActionEvent#getSource()でイベント元のJComboBoxが取得可能- デフォルトの
JComboBoxはActionEvent#getActionCommand()でcomboBoxChangedを返す JComboBox#setSelectedIndex(...)メソッドなどを使用してJComboBoxを直接マウスやキー入力で操作しなくても、ActionEventは発生するJComboBoxの同じアイテムを選択してもActionEventは発生する
JCheckBox
ItemListenerItemEvent#getItemSelectable()、またはItemEvent#getItem()でイベント元のJCheckBoxが取得可能ItemEvent#getStateChange()でJCheckBoxが選択されたかを取得可能JCheckBox#setSelected(...)メソッドなどを使用してJCheckBoxを直接マウスやキー入力で操作しなくてもItemEventは発生するJCheckBox#setSelected(...)メソッドを使用しても選択状態が変化しない場合、ItemEventは発生しない
ActionListenerActionEvent#getSource()でイベント元のJCheckBoxが取得可能- デフォルトの
JCheckBoxはActionEvent#getActionCommand()でJCheckBox#getText()と同じ値を返す JCheckBox#setSelected(...)メソッドなどを使用してJCheckBoxの状態を変更しても、ActionEventは発生しない
JRadioButton(ButtonGroup)
ItemListenerItemEvent#getItemSelectable()、またはItemEvent#getItem()でイベント元のJCheckBoxが取得可能ItemEvent#getStateChange()でJRadioButtonが選択されたかを取得可能JRadioButton#setSelected(...)メソッドなどを使用してJRadioButtonを直接マウスやキー入力で操作しなくても、ItemEventは発生するJRadioButton#setSelected(...)メソッドを使用しても選択状態が変化しない場合、ItemEventは発生しないButtonGroup#getSelection()はJRadioButton#setSelected(...)メソッドを使用して選択変更した場合はnull、マウスなどで選択変更した場合はそのButtonModelを返す
ActionListenerActionEvent#getSource()でイベント元のJRadioButtonが取得可能- デフォルトの
JRadioButtonはActionEvent#getActionCommand()でJRadioButton#getText()と同じ値を返す JRadioButton#setSelected(...)メソッドなどを使用してJRadioButtonの状態を変更してもActionEventは発生しない