我很困惑,我看到的许多例子只处理一个按钮侦听器被传递。我希望能够将视图类(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){}
}
}
添加如下方法:
private void setListener(AbstractButton button, ActionListener listener, String command) {
button.addActionListener(listener);
button.setActionCommand(command);
}
构建单个EventController
实例
EventController controller = new EventController();
然后,为每个按钮调用它:
setListener(addEvent, controller, "add");
...
只需创建一次侦听器实例并重用它。这样的
EventController lst=new EventController();
addEvent.addActionListener(lst);
addEvent.setActionCommand("add");
editEvent.addActionListener(lst);
editEvent.setActionCommand("edit");
deleteEvent.addActionListener(lst);
deleteEvent.setActionCommand("delete");