JButton Array Action Listener仅适用于最后一个按钮

时间:2013-03-30 13:44:48

标签: java arrays swing jbutton actionlistener

我创建了一个按钮数组,并尝试向for循环中的每个按钮添加一个ActionListener,并使用for循环监听所有按钮,但事实是唯一的响应按钮是最后创建的按钮。我做错了什么?

nums = new JButton[13];
ListenForButton lfb = new ListenForButton();
for (int i = 1; i < 13; i++) {
    nums[i].addActionListener(lfb);
}

private class ListenForButton implements ActionListener{
    public void actionPerformed(ActionEvent e) {
        for(int i=0;i<13;i++){
            if( e.getSource() == nums[i]) {
                System.out.println("pressed");
            }
        }
    }
}

2 个答案:

答案 0 :(得分:1)

方法ActionEvent.getSource()返回一个Object类型的实例,你需要将它强制转换为JButton这个

if( e.getSource() == nums[i])

是真的,所以这样做而不是上面的陈述:

if( ((JButton)e.getSource()) == nums[i])

也试试这个:

nums = new JButton[13];

for (int i = 0; i < 13; i++) 
 {
    nums[i] = new JButton();
    nums[i].addActionListener(new ActionListener() {
       public void actionPerformed(ActionEvent ae)
       {
           System.out.println("pressed");
       }
    });
 }

或使用ActionCommand,如下所示:

nums = new JButton[13];

ListenerForButton lfb = new ListenerForButton();
for (int i = 0; i < 13; i++) 
 {
    nums[i] = new JButton();
    nums[i].setActionCommand("button"+i);
    nums[i].addActionListener(lfb);
 }

 private class ListenForButton implements ActionListener{

    public void actionPerformed(ActionEvent e) {

        for(int i=0;i<13;i++){

        if( e.getActionCommand().equals("button"+i)) {
               System.out.println("pressed" + i); //for  getting which button is actually clicked
           }
    }

答案 1 :(得分:0)

我认为你应该调用nums [i] .addActionListener(new ListenForButton()); 为每个按钮获取一个新的监听器