現在、200 個を超えるボタンを使用しているアプリケーションがあり、それぞれが変数名の文字列を返します。これを行う方法はありますか?これらのそれぞれに name プロパティを設定すると、非常に時間がかかります。
2285 次
2 に答える
2
ボタンのコレクションを使用します。
ActionListener theActionListener = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println(((JButton) e.getSource()).getName());
}
};
List<JButton> buttons = new ArrayList<JButton>();
for (int i = 0; i < 200; i++) {
JButton button = new JButton("Button " + (i + 1));
button.setName("Button " + (i + 1));
button.addActionListener(theActionListener);
buttons.add(button);
}
于 2012-11-17T09:23:19.770 に答える
1
JButton#putClientProperty
具体的な JButton の識別に使用
buttons[i][j].putClientProperty("column", i);
buttons[i][j].putClientProperty("row", j);
buttons[i][j].addActionListener(new MyActionListener());
から取得しますActionListener
(たとえば)
public class MyActionListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
JButton btn = (JButton) e.getSource();
System.out.println("clicked column " + btn.getClientProperty("column")
+ ", row " + btn.getClientProperty("row"));
}
- ただし、適切な方法は、 ActionListenerの代わりにSwing Action
JButton
を使用することです。
于 2012-11-17T09:24:05.523 に答える