2016-04-15 56 views
1

現在我有一個循環循環,並創建按鈕。我想知道如何訪問按鈕並給他們動作監聽器。我在創建按鈕時如何給按鈕動作偵聽器?

buttons

int i = 0; 
    while (i < presenter.listOfTabemono.size()) { 
     buttonPanel.add(new JButton(presenter.listOfTabemono.get(i) + " $" + presenter.listOfOkane.get(i))); 
     i++; 
    } 

爲了這樣的事情。

JButton cancel = new JButton("Cancel Order"); 
    cancel.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
      // TODO: Add the function to handle cancel order 
      // Think about where you will store order and who should 
      // manipulate. 
      orderDetails.setText("Order cancelled"); 
     } 
    }); 

回答

0

這個怎麼樣?

Components[] components = buttonPanel.getComponents(); 
for(int i=0; i< components.length; i++){ 

    Components c = components[i]; 
    if(c instanceof JButton){ 
     JButton button = (JButton)c; 
     button.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
      // TODO: Add the function to handle event 
      } 
     }); 
    } 

} 

或者

int i = 0; 
while (i < presenter.listOfTabemono.size()) { 
    JButton button = new JButton(presenter.listOfTabemono.get(i) + " $" + presenter.listOfOkane.get(i)); 
    button.addActionListener(new ActionListener() { 
     public void actionPerformed(ActionEvent e) { 
     // TODO: Add the function to handle event 
     } 
    }); 
    buttonPanel.add(button); 
    i++; 
} 

或者

List<JButton> buttons = new ArrayList<JButton>(); 
while (i < presenter.listOfTabemono.size()) { 
    JButton button = new JButton(presenter.listOfTabemono.get(i) + " $" + presenter.listOfOkane.get(i)); 
    buttonPanel.add(button); 
    buttons.add(button); 
    i++; 
} 

for(int i=0; i<buttons.size(); i++){ 
    JButton button = buttons.get(i); 
    button.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent e) { 
      // TODO: Add the function to handle event 
      } 
     }); 
    } 

}