1

我很困惑,我见过的许多例子只处理一个按钮监听器被传递。我希望能够将视图类(JFrame)的所有组件传递给控制器​​类,控制器类可以轻松访问这些组件的侦听器。我怎样才能轻松做到这一点。这是我到目前为止所做的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){}
        }


    }
4

2 回答 2

2

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

    EventController lst=new EventController();
    addEvent.addActionListener(lst);
    addEvent.setActionCommand("add");
    editEvent.addActionListener(lst);
    editEvent.setActionCommand("edit");
    deleteEvent.addActionListener(lst);
    deleteEvent.setActionCommand("delete");
于 2013-01-17T10:47:56.897 回答
2

添加这样的方法:

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

构建单个EventController实例。

EventController controller = new EventController();

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

setListener(addEvent, controller, "add");
...
于 2013-01-17T10:49:51.697 回答