Right now I have a while loops that loops and creates the buttons. I would like to know how to access the buttons and give them action listeners.
int i = 0;
while (i < presenter.listOfTabemono.size()) {
buttonPanel.add(new JButton(presenter.listOfTabemono.get(i) + " $" + presenter.listOfOkane.get(i)));
i++;
}
To something like this.
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 :(得分: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
}
});
}
}