【问题标题】:Adding ActionListeners to a new JButton created in a loop将 ActionListeners 添加到在循环中创建的新 JButton
【发布时间】:2014-04-09 17:39:00
【问题描述】:

我正在尝试将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: ");
        }
    }
}

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

【问题讨论】:

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


【解决方案1】:

问题似乎是你从来没有创建一个新的BrowseMediaPlayerListsControlListener(),而那个方法的构造函数就是调用addPlayListener()

如果将此行添加到createButton,您将获得所需的功能:

play_lists_btn.addActionListener(new ActionListener() {
   @Override
   public void actionPerformed(ActionEvent e) {
       System.out.println("play is: ");
   }
} );

【讨论】:

  • 我明白你的意思@david,但我希望能够从另一个类访问按钮侦听器,即 BrowseMediaPlayerListsControlListener() 类。我正在尝试遵循 MVC 模式。我不知道这是否可能。
猜你喜欢
  • 1970-01-01
  • 2020-07-09
  • 1970-01-01
  • 2016-01-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多