一组动态的按钮 产生和存放在一个Map中,遍历按钮的过程中定义每个按钮的动作。问题为什么我只实现了最后一个按钮,是我遍历出错了吗??代码如下:
         HashMap<String,JButton> Var =  new   HashMap<String,JButton>();
        for(int i=0;i<10;i++)
        {
         // Var的key是0到9,value是按钮"0"到"90"
                Var.put(String.valueOf(i),new JButton(String.valueOf(i*10)));        }        for (Iterator iter = Var.keySet().iterator(); iter.hasNext();) 
        {
            Object key = iter.next();
            // 打印按钮的名字
            System.out.println(Var.get(key).getText());
            tempB = Var.get(key);
            // 添加在frame上
            frame.add(tempB);
            // 在各按钮上添加动作 简单打印 按钮名字 + "actionPerformed()"
            tempB.addActionListener(new java.awt.event.ActionListener()
    {
public void actionPerformed(java.awt.event.ActionEvent e)
{
System.out.println(tempB.getText()+"  actionPerformed()"); 
}
    });        }
为什么按每个按钮被点击后,都是执行处最后一个动作 80 actionPerformed()?     
    

解决方案 »

  1.   

    System.out.println(tempB.getText()+"  actionPerformed()");  问题可能出现在这个tempB 里面了。
    你仔细看看吧! 她好像只能由一个哦!
      

  2.   

    修改成这样看看,呵呵!
            public void actionPerformed(java.awt.event.ActionEvent e) {
              JButton b = (JButton)e.getSource();
              System.out.println(b.getText() + "  actionPerformed()");
            }
      

  3.   

    我已经解决了,把tempB定义成final的就可以了3楼的方法也可以,谢谢
      

  4.   

    定义成final?
    tempB = Var.get(key); 
    这句话会编译错误! 估计你修改了几个地方吧!
      

  5.   

    定义成 final JButton tempB = Var.get(key); 没提示错误而且定义的按钮动作会设计别的资源,只是利用按钮的名字来确定。
    并且资源来源于外部,不能从event.getSource()获得.如下protected void buildOutputPanel(HashMap<String, Variable> OutputVariables) {
    for (Iterator iter = OutputVariables.keySet().iterator(); iter.hasNext();) {            Object key = iter.next();            System.out.println(OutputVariables.get(key).getName());
                final HashMap<String, Variable> tempOutputVariables = OutputVariables;
                tempB = new JButton(OutputVariables.get(key).getName());
                getJPanel2().add(tempB);
                tempB.addActionListener(new java.awt.event.ActionListener()
         {
    public void actionPerformed(java.awt.event.ActionEvent e)
    {
    JButton b=(JButton)e.getSource();
    tempOutputVariables.get(b.getText()).chart(true);//按钮后做相应的图
    System.out.println(tempB.getText()+"  actionPerformed() ");
    }
    });        }
    }用3楼的办法,tempB不用定义为final,但是tempOutputVariables必须是final的才能被访问,动作的定义有什么访问限制吗???