event.getSource() は、イベントがどの特定のボタンから発生したかを確実に知らせますが、生成されたボタンを追跡したり、ボタンをスヌーピングしたりする必要があるという副作用があります。また、ライブラリの識別に使用されるものとは異なる名前 (おそらくバージョン情報を含む) をユーザーに提示することもできます。ボタンの「ActionCommand」プロパティを使用すると、これらの問題を分離する方法が提供される場合があります。そのため、チェックボックス メニュー項目の生成とリスナーのコードを変更する必要があります。
ActionListener actionListener = ... // whatever object holds the method, possibly this
String[] libraries = ... // however you get your library names
JMenu parentMenu = ... // the menu you are adding them to
for (String s : libraries) {
// prettyName is a method to make a pretty name, perhaps trimming off
// the leading path
JCheckBoxMenuItem child = new JCheckBoxMenuItem(prettyName(s), true);
child.setActionCommand(s);
parentMenu.acc(child);
}
アクション ハンドラのコードは次のようになります...
public void actionPerformed(ActionEvent evt) {
// the 'current' selection state, i.e. what it is going to be after the event
boolean selected = ((JCheckBoxMenuItem)evt.getSource()).isSelected();
String library = evt.getActionCommand();
... process based on library and state here...
}