Reputation: 23
I have a dynamic number of JButtons in a list and need help to connect them to the actionListener
I first create the buttons based on a list called alt:
for(int i =0;i<alt.size();i++) {
JButton button = new JButton (alt.get(i));
button.addActionListener(this);
buttonList.add(button);
}
Later I add the buttons like this
private void gui(List<JButton> bList) {
f = new JFrame("window");
f.setLayout(new BorderLayout());
f.setVisible(true);
JPanel buttonPane = new JPanel();
buttonPane.setLayout(new BoxLayout(buttonPane, BoxLayout.PAGE_AXIS));
for(int i =0;i<bList.size();i++) {
buttonPane.add(bList.get(i));
}
f.add(buttonPane, BorderLayout.SOUTH);
}
I know there will never be more than 4 buttons. So how can I connect to the right button in the ActionListener ? without them being declared outside the scope of gui or individually named?
public void actionPerformed(ActionEvent e) {
if(e.getSource() == ?) {
} else if (e.getSource() == ?) {
} else if (e.getSource() == ?){
}else if (e.getSource() == ?){
}
}
Upvotes: 1
Views: 26
Reputation: 1860
If your buttons are doing actions, you should implement separate Action Listeners for each button, otherwise in your e.getSource() == ?
the ?
should be a JButton instance, for example : e.getSource() == bList.get(0)
Upvotes: 1