2013-04-23 142 views
2

我有下面的代码,它会在按钮单击时创建一个JButton数组。 Ope[]已在课堂上公开申报。我有问题,我得到空指针。也就是说,它不打印第二个循环,即。不会进入内部迭代。 请告诉我如何处理数组的侦听器。提前致谢。将监听器添加到JButton数组;

for(int i=0,y=30; i<counter;i++,y+=15) 
{ 

     open[i]=new JButton("Open"); 
     open[i].setBounds(380, y, 70, 15); 
     open[i].addActionListener(this); 
     panelDisplay.add (open[i]); 

     System.out.println(""+i); 
} 

事件中的actionPerformed功能处理如下:

for(int j=0; j<open.length; j++) 
{ 
    System.out.println("1st in a loop"+j); 

    if(ae.getSource() != null) 
    { 
     if(ae.getSource() == open[j]) 
     { 
      System.out.println("2nd in a loop" +j); 
      int id; 
      String stringid; 
      System.out.println("open of"+j+"is clicked"); 

      stringid = ""+table.getValueAt(j, 0); 
      id = Integer.parseInt(stringid); 
      fetchData(id); 
      //ae.getSource().equals(null); 
     } 
    } 

} 
+0

不要使用'的setBounds('。使用布局管理器布置按钮。发布证明问题的SSCCE。 – camickr 2013-04-23 15:38:40

回答

0

JButton的继承自Component “的setName” 方法。所以,如果你在初始化

 open[i]=new JButton("Open"); 
     open[i].setBounds(380, y, 70, 15); 
     open[i].setName("Button"+i); 
     open[i].addActionListener(this); 
     panelDisplay.add (open[i]); 

     System.out.println(""+i); 

你可以找到至极按钮,按钮设置一个名字)压在eventhandling

int buttonNumber = Integer.parseInt(ae.getSource().getName().replace("Button","")) 
    //... do eventhandling for Button["buttonNumber"] 
+1

最好使用getName.equals(“Button”+ i) – jogabonito 2013-04-23 15:24:29

+0

-1,这样就不需要setName()方法。这是额外的工作,这是没有必要的。如果此代码有效,那么原始代码应该可以工作。尽管永远不建议使用if/else或循环类型逻辑来确定哪个对象生成事件,但如果确实使用了这个逻辑,那么您应该检查实际对象,或者可能是对象的“操作命令”,而不是对象的名称。 – camickr 2013-04-23 15:35:22