繁体   English   中英

传递JFrame中组件List的ActionListener

[英]Passing ActionListener of a List of components in a JFrame

我很困惑,我见过的许多例子只涉及一个按钮监听器被传递。 我希望能够将View类的所有组件(JFrame)传递给Controller类,它可以轻松访问这些组件的侦听器。 我怎么能这么容易做到 这是我到目前为止用JMenuItem做的,但是在JFrame中我有更多的按钮,不想每次都在构造函数中重复。

 public class EventController implements ActionListener {
    private EventModel model;
    private EventView view;



    public EventController(){
        model = new EventModel(); 

    }


    @Override
   public void actionPerformed(ActionEvent e) {
       if (e.getActionCommand().equals("add")) {
       JOptionPane.showMessageDialog(null, "add button clicked");
   }   else if (e.getActionCommand().equals("edit")) {
       JOptionPane.showMessageDialog(null, "edit button clicked");
   }   else if (e.getActionCommand().equals("delete")) {
       JOptionPane.showMessageDialog(null, "delete button clicked");
  }


    }   

//类视图

  public class EventView extends javax.swing.JFrame {
Connection conn = JavaConnect.ConnectDB();
PreparedStatement pst = null; 
ResultSet rs = null; 


    public EventView() {
        initComponents();
        updateEventTable();
        addEvent.addActionListener(new EventController());
        addEvent.setActionCommand("add");
        editEvent.addActionListener(new EventController());
        editEvent.setActionCommand("edit");
        deleteEvent.addActionListener(new EventController());
        deleteEvent.setActionCommand("delete");
    }
    public void updateEventTable() {
        try {
            String sql = "SELECT date as 'Date',eventName as 'Name', time as 'Start Time' FROM Event";
             pst = conn.prepareStatement(sql); 
             rs = pst.executeQuery();
             tableEvent.setModel(DbUtils.resultSetToTableModel(rs));
             tableEvent.getColumnModel().getColumn(0).setPreferredWidth(80);
             tableEvent.getColumnModel().getColumn(1).setPreferredWidth(170);
             tableEvent.getColumnModel().getColumn(2).setPreferredWidth(110);  
    }
        catch (Exception e ) {
                     JOptionPane.showMessageDialog(null, e);
        } finally {
            try {
                rs.close(); pst.close();conn.close();;
            } catch(SQLException e){}
        }


    }

只创建一次侦听器实例并重用它。 像这样

    EventController lst=new EventController();
    addEvent.addActionListener(lst);
    addEvent.setActionCommand("add");
    editEvent.addActionListener(lst);
    editEvent.setActionCommand("edit");
    deleteEvent.addActionListener(lst);
    deleteEvent.setActionCommand("delete");

添加如下方法:

private void setListener(AbstractButton button, ActionListener listener, String command) {
  button.addActionListener(listener);
  button.setActionCommand(command);
}

构建一个EventController实例。

EventController controller = new EventController();

然后,为每个按钮调用它:

setListener(addEvent, controller, "add");
...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM