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...
}
確かに、コンパイル時に未知のパラメータで各ActionListenerを呼び出す方法はありますか? – Zxaos