How do I give buttons action listeners as I am creating buttons?

时间:2016-04-15 10:59:25

标签: jbutton actionlistener

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.

buttons

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");
        }
    });

1 个答案:

答案 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
            }
        });
    }

}