I am trying to add an ActionListener
to a JButton
created in a loop, then call the ActionListener
from another class (the controller class), but it's not working. Here is the first class:
private void configurePanel() {
increment = 0;
while (increment < file_location.size() && increment < file_imglocation.size()) {
configureButtonPanel(increment, file_location, file_imglocation);
increment++;
}
}
private void configureButtonPanel(int increment, ArrayList<String> file_location, ArrayList<String> file_imglocation) {
File f = new File(file_location.get(increment));
int video_no = increment;
String str = video_no + 1 + " " + f.getName();
str = str.substring(0, str.lastIndexOf("."));
btn_control_pnl = new JPanel();
btn_control_pnl.setLayout(new FlowLayout(FlowLayout.CENTER));
//jbutton created in a loop
btn_control_pnl.add(createButton(increment, file_imglocation.get(increment), str));
btn_control_pnl.setBackground(Color.BLACK);
main_pnl.add(btn_control_pnl);
}
private JButton createButton(final int i, String img_loc, String file_name) {
File f = new File(img_loc);
play_lists_btn = new JButton();
play_lists_btn.setFont(new Font("SansSerif", Font.BOLD, 12));
play_lists_btn.setText(file_name);
play_lists_btn.setVerticalTextPosition(SwingConstants.TOP);
play_lists_btn.setHorizontalTextPosition(SwingConstants.CENTER);
String fname = "Images\\" + f.getName();
return play_lists_btn;
}
public void addPlayListener(ActionListener play) {
play_lists_btn.addActionListener( play);
}
Here is the controller class that calls the button action listener, and creates an action event for the button:
public class BrowseMediaPlayerListsControlListener {
private BrowseMediaPlayerListsPanel browse_video_pnl;
public BrowseMediaPlayerListsControlListener(BrowseMediaPlayerListsPanel browse_video_pnl) {
this.browse_video_pnl = browse_video_pnl;
this.browse_video_pnl.addPlayListener(new PlayListener());
}
private class PlayListener implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("play is: ");
}
}
}
Nothing seems to work, the print statement never show up.
The problem seems to be that you never create a new BrowseMediaPlayerListsControlListener()
, and the constructor of that method is what calls addPlayListener()
.
You will get your desired functionality if you add this line to createButton
:
play_lists_btn.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
System.out.println("play is: ");
}
} );
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.