Mediator在Swing中可以充当MVC中的Controller的角色,例如:
public class FrmUserManager extends JFrame {
private UserManagerMediator mediator;
private JButton addBtn = new JButton();
private JButton delBtn = new JButton();
private JComboBox userComboBox = new JComboBox();
// 下面是其他一些控件
public FrmUserManager() {
mediator = new UserManagerMediator(this);
initComponent();
}
private initComponent() {
addBtn.addActionListener(mediator.addAction());
delBtn.addActionListener(mediator.deleteAction());
userComboBox.setModel(mediator.userComboBoxModel());
// other operation
}
public JComboBox getUserComboBox() {
return userComboBox;
}
}
public class UserManagerMediator {
private FrmUserManager frmUserManager;
public UserManagerMediator(FrmUserManager frmUserManager) {
this.frmUserManager = frmUserManager;
}
public ActionListener addAction() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox userComboBox = frmUserManager.getUserComboBox();
DefaultComboBoxModel model = (DefaultComboBoxModel)userComboBox.getModel();
model.addElement(......);
}
};
}
public ActionListener deleteAction() {
return new ActionListener() {
public void actionPerformed(ActionEvent e) {
JComboBox userComboBox = frmUserManager.getUserComboBox();
DefaultComboBoxModel model = (DefaultComboBoxModel)userComboBox.getModel();
model.removeElement(......);
}
};
}
public DefaultComboBoxModel userComboBoxModel() {
// 比如:查询数据库得到数据
DefaultComboBoxModel model = new DefaultComboBoxModel();
// 添加数据
model.addListDataListener(new ListDataListener() {
// 实现一些方法
});
return model;
}
}
View--FrmUserManager,Controller--UserManagerMediator,Model--在控制器中调用
当View的状态改变(如:点击按钮,选择下拉框),调用Mediator中相应方法来更新Model;当Model改变(如:下拉框增加一项),会通过Mediator,更新视图。