2013-04-23 109 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