将ActionListeners添加到循环中创建的新JButton

时间:2014-04-09 17:39:01

标签: java swing model-view-controller jbutton actionlistener

我正在尝试将ActionListener添加到循环中创建的JButton,然后从另一个类(控制器类)调用ActionListener,但它无法正常工作。这是第一堂课:

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

以下是调用按钮动作侦听器的控制器类,并为按钮创建动作事件:

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

似乎没有任何效果,打印声明永远不会出现。

1 个答案:

答案 0 :(得分:0)

问题似乎是你从不创建新的BrowseMediaPlayerListsControlListener(),而该方法的构造函数就是调用addPlayListener()

如果将此行添加到createButton

,您将获得所需的功能
play_lists_btn.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
       System.out.println("play is: ");
   }
} );
相关问题