gpt4 book ai didi

java - 在 JFrame 中传递组件列表的 ActionListener

转载 作者:行者123 更新时间:2023-11-29 03:38:18 26 4
gpt4 key购买 nike

我很困惑,我看到的很多例子只处理一个按钮监听器被传递。我希望能够将 View 类 (JFrame) 的 ALL 组件传递给 Controller ​​类, 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");
}


}

//类 View

  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");
...

关于java - 在 JFrame 中传递组件列表的 ActionListener,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14377262/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com