我很困惑,我见过的许多例子只处理一个按钮监听器被传递。我希望能够将视图类(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){}
}
}