Hopefully the title explains my problem relatively well. I have a JToolBar, dateBar, and I want to add buttons to it like so:
for (Day d : newCal.getDateList()) {
dateBar.add(new JButton(d.toString()));
}
ie for every one of some object in a collection, add a new Button to the JToolBar. This works, except that I don't know how / if I can add an actionListener to the buttons so I can perform some computation once one of them is clicked.
Many thanks, hopefully I've been clear enough.
Ps - I should add that
JButton button = new JButton(d.toString());
button.addActionListener(this);
dateBar.add(button);
Does not seem to work, even if the class the method is contained in implements actionListener also
Add the actionListener in the same loop that you create the buttons.
Example:
for (Day d : newCal.getDateList()) {
JButton button = new JButton(d.toString());
button.addActionListener(todo);
dateBar.add(button);
}
Alternatively you could pass an Action object to the button in the constructor.
for (Day d : newCal.getDateList()) {
dateBar.add(new JButton(new CalendarAction(d.toString()))));
}
Try this..
for (Day d : newCal.getDateList()) {
JButton button = new JButton(d.toString());
button.addActionListener(this);
dateBar.add(button);
}
public void actionPerformed(ActionEvent e){
if(e.getActionCommand().equals("your button label"){
// do your action
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.