swing 状态视图分离
通常,我基于Spring Framework构建Java应用程序。 但是,最近有人要求我使用与语言无关的MVC框架PureMVC为客户端实现Java桌面应用程序,因此以下是我在Java Swing中为PureMVC进行员工管理展示的演示实现。 如果您想继续学习,可以在GitHub上找到可运行的演示。 Java Swing MVA演示
建筑总结
此应用程序使用了一个有趣的通用MVC模式的变体,称为模型视图适配器 (MVA)模式。 Model View Adapter模式最引人注目的是它通过引入一个间接层来分离关注点并通过介体和简单的适配器接口提供消息传递,从而巧妙地促进了视图组件之间的松散耦合。 通过使用值对象和代理对象,介体可以将消息更改引导到模型层,而无需直接绑定到域对象。 即使此实现需要更多样板代码,但这种混合设计仍促进了易于理解和易于维护的模块化样式。
实施应用程序设计
如果您不熟悉在Swing中构建桌面应用程序,那么Swing教程可以帮助您快速掌握核心概念,或者您可以下载示例应用程序并在进行过程中对其进行回顾。
由于这是一个经典的Java Swing应用程序,因此我将以构建基本框架作为包含三个主面板的入口点开始,并使用经过修饰的startup
方法初始化ApplicationFacade
,以使应用程序线程与GUI的Event Dispatch Thread分开。
下面的对象图说明了EmployeeAdmin
类如何构造三个主要组件,然后调用startup
方法。
这里的顺序很简单。 首先,构建基础框架,然后构建三个主要组件,初始化ApplicationFacade,然后运行基础框架。
package employeeadmin;import api.Utils.GBC;
import employeeadmin.view.components.RolePanel;
import employeeadmin.view.components.UserForm;
import employeeadmin.view.components.UserList;import javax.swing.*;
import javax.swing.plaf.nimbus.NimbusLookAndFeel;
import java.awt.GridBagLayout;/*** @author Edward Beckett*/
public class EmployeeAdmin extends JFrame implements Runnable {private UserList userList;private UserForm userForm;private RolePanel rolePanel;public EmployeeAdmin() {build();}private void build() {setTitle( "Java Swing Model View Adapter (MVA) Demo" );setLayout( new GridBagLayout() );setDefaultCloseOperation( WindowConstants.EXIT_ON_CLOSE );setResizable( false );buildComponents();startup();pack();setLocationRelativeTo( null );setVisible( true );}private void buildComponents() {JPanel basePanel = new JPanel( new GridBagLayout() );userList = new UserList();userForm = new UserForm();rolePanel = new RolePanel();GBC userListConstraints = new GBC( 0, 0, 2, 1 ).setWeight( 1, 1 ).setAnchor( GBC.NORTH ).setFill( GBC.BOTH ).setInsets( 0, 0, 0, 0 ).setIpad( 0, 0 );basePanel.add( userList, userListConstraints );GBC userFormConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, .5 ).setAnchor( GBC.LINE_START ).setFill( GBC.BOTH ).setInsets(0, 0, 0, 0 ).setIpad( 0, 0 );basePanel.add( userForm, userFormConstraints );GBC rolePanelConstraints = new GBC( 1, 1, 1, 1 ).setWeight( 1, .5 ).setAnchor( GBC.LINE_END ).setFill( GBC.BOTH ).setInsets( 0, 0, 0, 0 ).setIpad( 0, 0 );basePanel.add( rolePanel, rolePanelConstraints );GBC basePanelConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 ).setFill( GBC.BOTH ).setAnchor( GBC.CENTER ).setInsets( 0, 0, 0, 0 ).setIpad( 0, 0 );add( basePanel, basePanelConstraints );}protected void startup() {ApplicationFacade.getInstance().startup( this );}public static void main( String... args ) {try {UIManager.setLookAndFeel( new NimbusLookAndFeel() );} catch( UnsupportedLookAndFeelException e ) {e.printStackTrace();}new EmployeeAdmin().run();}@Overridepublic void run() {SwingUtilities.invokeLater( () -> {//go.} );}public UserList getUserList() {return userList;}public UserForm getUserForm() {return userForm;}public RolePanel getRolePanel() {return rolePanel;}}
启动框架后,ApplicationFacade负责初始化命令控制器,该控制器注册多个命令以完全初始化应用程序。
package employeeadmin;import employeeadmin.controller.AddRoleResultCommand;
import employeeadmin.controller.DeleteUserCommand;
import employeeadmin.controller.StartupCommand;
import org.puremvc.java.multicore.patterns.facade.Facade;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/7/2015*/
public class ApplicationFacade extends Facade {public static final String STARTUP = "startup";public static final String NEW_USER = "newUser";public static final String DELETE_USER = "deleteUser";public static final String CANCEL_SELECTED = "cancelSelected";public static final String USER_SELECTED = "userSelected";public static final String USER_ADDED = "userAdded";public static final String USER_UPDATED = "userUpdated";public static final String USER_DELETED = "userDeleted";public static final String INIT_USERS = "initUsers";public static final String ADD_ROLE = "addRole";public static final String ADD_ROLE_RESULT = "addRoleResult";private static ApplicationFacade instance;public static final String NAME = "ApplicationFacade";public static ApplicationFacade getInstance() {if( instance == null ) {instance = new ApplicationFacade();}return instance;}protected ApplicationFacade() {super( NAME );}public void startup( Object app ) {sendNotification( STARTUP, app );}@Overrideprotected void initializeController() {super.initializeController();registerCommand( STARTUP, new StartupCommand() );registerCommand( DELETE_USER, new DeleteUserCommand() );registerCommand( ADD_ROLE_RESULT, new AddRoleResultCommand() );}}
第一个命令StartupCommand
依次运行另外两个子命令PrepViewCommand
和PrepModelCommand
。 另外两个命令DeleteUserCommand
和AddRoleResultCommand
只是代理帮助程序类。
package employeeadmin.controller;import org.puremvc.java.multicore.patterns.command.MacroCommand;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/2/2015*/
public class StartupCommand extends MacroCommand {@Overridepublic final void initializeMacroCommand() {addSubCommand( new PrepViewCommand() );addSubCommand( new PrepModelCommand() );}}
PrepViewCommand
注册所有视图组件的介体。
package employeeadmin.controller;import employeeadmin.EmployeeAdmin;
import employeeadmin.view.RolePanelMediator;
import employeeadmin.view.UserFormMediator;
import employeeadmin.view.UserListMediator;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/5/2015*/
public class PrepViewCommand extends SimpleCommand {@Overridepublic final void execute( INotification notification ) {EmployeeAdmin employeeAdmin = (EmployeeAdmin) notification.getBody();getFacade().registerMediator( new UserListMediator( employeeAdmin.getUserList() ) );getFacade().registerMediator( new UserFormMediator( employeeAdmin.getUserForm() ) );getFacade().registerMediator( new RolePanelMediator( employeeAdmin.getRolePanel() ) );}}
PrepModelCommand
构建初始域模型,注册DAO代理对象,然后完成应用程序启动生命周期。
package employeeadmin.controller;import employeeadmin.ApplicationFacade;
import employeeadmin.model.RoleProxy;
import employeeadmin.model.UserProxy;
import employeeadmin.model.enums.Department;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.command.SimpleCommand;import java.util.Arrays;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/5/2015*/
public class PrepModelCommand extends SimpleCommand {@Overridepublic final void execute( final INotification notification ) {UserProxy userProxy = new UserProxy();RoleProxy roleProxy = new RoleProxy();//@formatter:offRoleVO larryRoles = new RoleVO( "lstooge", Arrays.asList( Role.PAYROLL, Role.EMP_BENEFITS ) );RoleVO moeRoles = new RoleVO( "mstooge",Arrays.asList( Role.INVENTORY, Role.PRODUCTION, Role.SALES, Role.SHIPPING ) );RoleVO curlyRoles = new RoleVO( "cstooge", Arrays.asList( Role.ACCT_PAY, Role.ACCT_RCV, Role.GEN_LEDGER ) );userProxy.addUser(new UserVO( "lstooge", "Larry", "Stooge", "larry@stooges.com", "ijk456", Department.ACCT.getValue() ) );userProxy.addUser(new UserVO( "mstooge", "Moe", "Stooge", "moe@stooges.com", "abc123", Department.PLANT.getValue() ) );userProxy.addUser(new UserVO( "cstooge", "Curly", "Stooge", "curly@stooges.com", "xyz987", Department.SALES.getValue() ) );//@formatter:onroleProxy.addRole( larryRoles );roleProxy.addRole( moeRoles );roleProxy.addRole( curlyRoles );getFacade().registerProxy( userProxy );getFacade().registerProxy( roleProxy );getFacade().sendNotification( ApplicationFacade.INIT_USERS, userProxy, "UserProxy" );getFacade().removeCommand( ApplicationFacade.STARTUP );}}
视图层
该应用程序具有三个协作组件。 UserList
, UserForm
和RolePanel
。 每个组件都包含所有必需的子组件,属性和操作,以独立于外部组件运行和管理状态,并通过messaging adapter interface
与mediator
通信,并直接从mediator
接收消息。 我将在“消息传递适配器”部分中介绍有关此主题的更多信息。
package employeeadmin.view.components;import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.UserListMessage;import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/3/2015*/
public class UserList extends JPanel implements ActionListener, ListSelectionListener {public static final String NEW_USER = "New";public static final String NEW_USER_LABEL = "New";public static final String DELETE_USER = "Delete";public static final String DELETE_USER_LABEL = "Delete";UserListMessage message;private UserTable userTable;private JPanel buttonPanel;private JButton newUserButton;private JButton deleteUserButton;private JScrollPane userPane;private JTableHeader header;private ArrayList users;private UserVO user;public UserList() {setLayout( new GridBagLayout() );setBorder( new BorderBuilder( "Users", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );initComponents();}public class UserTable extends JTable {public UserTable() {super( new UserListModel() );setBackground( new Color( 235, 235, 235 ) );}@Overridepublic UserListModel getModel() {return (UserListModel) super.getModel();}}public static class UserListModel extends AbstractTableModel {private final String[] columnName = { "Username", "First Name", "Last Name", "Email", "Department" };private final Class<?>[] columnType = { String.class, String.class, String.class, String.class, String.class };private ArrayList users;private static final int COLUMN_USERNAME = 0;private static final int COLUMN_FIRST_NAME = 1;private static final int COLUMN_LAST_NAME = 2;private static final int COLUMN_EMAIL = 3;private static final int COLUMN_DEPARTMENT = 4;public UserListModel() {}public void reload( ArrayList users ) {this.users = users;fireTableDataChanged();}@Overridepublic Class<?> getColumnClass( int column ) {return columnType[column];}@Overridepublic int getColumnCount() {return columnName.length;}@Overridepublic String getColumnName( int column ) {return columnName[column];}@Overridepublic int getRowCount() {if( users == null ) {return 0;}return users.size();}@Overridepublic Object getValueAt( int row, int column ) {if( users.get( row ) != null ) {UserVO user = users.get( row );switch( column ) {case COLUMN_USERNAME:if( user.username != null ) {return user.username;}case COLUMN_FIRST_NAME:if( user.firstName != null ) {return user.firstName;}case COLUMN_LAST_NAME:if( user.lastName != null ) {return user.lastName;}case COLUMN_EMAIL:if( user.email != null ) {return user.email;}case COLUMN_DEPARTMENT:if( user.department != null ) {return user.department;}default:return null;}}return null;}@Overridepublic boolean isCellEditable( int rowIndex, int columnIndex ) {return false;}}private void initComponents() {userTable = new UserTable();userTable.getSelectionModel().addListSelectionListener( this );buttonPanel = new JPanel();deleteUserButton = new JButton();deleteUserButton.addActionListener( this );newUserButton = new JButton();newUserButton.addActionListener( this );userPane = new JScrollPane();userPane.getViewport().setBackground( new Color( 241, 241, 241 ) );userTable.getColumnModel().getColumn( 0 ).setPreferredWidth( 100 );userTable.getColumnModel().getColumn( 1 ).setPreferredWidth( 100 );userTable.getColumnModel().getColumn( 2 ).setPreferredWidth( 100 );userTable.getColumnModel().getColumn( 3 ).setPreferredWidth( 100 );userTable.getColumnModel().getColumn( 4 ).setPreferredWidth( 100 );userTable.setRowHeight( 16 );userTable.setShowGrid( true );userTable.setVisible( true );userTable.setFillsViewportHeight( true );userTable.setGridColor( Color.LIGHT_GRAY );userTable.setShowHorizontalLines( true );userTable.setShowVerticalLines( true );userTable.setFont( new Font( "Segoe UI", Font.PLAIN, 12 ) );userTable.setAutoResizeMode( JTable.AUTO_RESIZE_ALL_COLUMNS );userTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );header = userTable.getTableHeader();header.setFont( new Font( "Segoe UI", Font.BOLD, 12 ) );userPane.setPreferredSize( new Dimension( 600, 200 ) );userPane.setViewportView( userTable );//@formatter:offGBC userPaneConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.CENTER ).setFill( GBC.BOTH ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( userPane, userPaneConstraints );GBC buttonPanelConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.BOTH ) .setInsets( 0, 0, 0, 0 ) .setIpad( 0, 0 );add( buttonPanel, buttonPanelConstraints );//@formatter:onbuttonPanel.setLayout( new FlowLayout( FlowLayout.LEADING ) );newUserButton.setText( NEW_USER_LABEL );newUserButton.setToolTipText( "Click to add a new user." );deleteUserButton.setText( DELETE_USER_LABEL );deleteUserButton.setToolTipText( "Click to delete the selected user" );buttonPanel.add( newUserButton );buttonPanel.add( deleteUserButton );}@Overridepublic void actionPerformed( ActionEvent e ) {switch( e.getActionCommand() ) {case NEW_USER:cancelSelection();message.onNew();break;case DELETE_USER:if( getUser() != null ) {if( JOptionPane.showConfirmDialog( null, "Delete User?", "Delete User?",JOptionPane.OK_CANCEL_OPTION, JOptionPane.WARNING_MESSAGE ) == 0 ) {message.onDelete( user );}}break;default:throw new UnhandledException( "Error Unhandled event [" + e.getID() + "]" );}}@Overridepublic void valueChanged( ListSelectionEvent e ) {if( userTable.getSelectedRow() > -1 && !e.getValueIsAdjusting() ) {UserVO user = getUsers().get( userTable.getSelectedRow() );setUser( user );message.onSelect( user );}}public void cancelSelection() {this.user = null;userTable.getSelectionModel().clearSelection();deleteUserButton.setEnabled( false );}public void reloadUsers( ArrayList users ) {this.users = users;userTable.getModel().reload( users );cancelSelection();}public void addUser( UserVO user ) {getUsers().add( user );userTable.getModel().reload( users );}public void setUser( UserVO user ) {this.user = user;deleteUserButton.setEnabled( true );}public UserVO getUser() {return ( this.user == null ? new UserVO() : this.user );}public ArrayList getUsers() {return users;}public void setMessage( UserListMessage message ) {this.message = message;}
}
package employeeadmin.view.components;import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.enums.Department;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.UserFormMessage;import javax.swing.*;
import javax.swing.border.TitledBorder;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 1/29/2015*/
public class UserForm extends JPanel implements ActionListener {public static final int MODE_ADD = 1;public static final int USER_SELECTED = 2;public static final int MODE_UPDATE = 3;public static final int DELETE_USER = 4;public static final int FORM_ENABLED = 5;public static final int FORM_DISABLED = 6;private static final String FIRST_NAME = "First Name";private static final String LAST_NAME = "Last Name";private static final String EMAIL = "Email";private static final String USERNAME = "Username *";private static final String PASSWORD = "Password *";private static final String CONFIRM = "Confirm Password *";private static final String DEPARTMENT = "Department *";private static final String SAVE_PROFILE = "Save Profile";private static final String UPDATE_PROFILE = "Update Profile";private static final String CANCEL = "Cancel";private JLabel firstNameLabel;private JLabel lastNameLabel;private JLabel emailLabel;private JLabel userNameLabel;private JLabel passwordLabel;private JButton cancelButton;private JLabel passwordConfirmLabel;private JLabel departmentLabel;private JTextField firstNameField;private JTextField lastNameField;private JTextField emailField;private JTextField userNameField;private JPasswordField passwordField;private JPasswordField passwordConfirmField;private DefaultComboBoxModel departmentListModel;private JComboBox departmentList;private JButton updateUserButton;private UserVO user;private RoleVO roles;private UserFormMessage message;public UserForm() {setLayout( new GridBagLayout() );setBorder(new BorderBuilder( "User Profile", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );initComponents();}private void initComponents() {firstNameLabel = new JLabel( FIRST_NAME );lastNameLabel = new JLabel( LAST_NAME );emailLabel = new JLabel( EMAIL );userNameLabel = new JLabel( USERNAME );passwordLabel = new JLabel( PASSWORD );passwordConfirmLabel = new JLabel( CONFIRM );departmentLabel = new JLabel( DEPARTMENT );firstNameField = new JTextField();firstNameField.addActionListener( this );lastNameField = new JTextField();lastNameField.addActionListener( this );emailField = new JTextField();emailField.addActionListener( this );userNameField = new JTextField();userNameField.addActionListener( this );passwordField = new JPasswordField();passwordField.addActionListener( this );passwordConfirmField = new JPasswordField();passwordConfirmField.addActionListener( this );departmentListModel = new DefaultComboBoxModel<>();Department.list().stream().map( Department:: getValue ).forEach( departmentListModel:: addElement );departmentList = new JComboBox<>( departmentListModel );updateUserButton = new JButton();updateUserButton.addActionListener( this );cancelButton = new JButton( CANCEL );cancelButton.addActionListener( this );//@formatter:offGBC firstNameLabelConstraints = new GBC( 0, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( firstNameLabel, firstNameLabelConstraints );GBC lastNameLabelConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( lastNameLabel, lastNameLabelConstraints );GBC emailLabelConstraints = new GBC( 0, 2, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( emailLabel, emailLabelConstraints );GBC userNameLabelConstraints = new GBC( 0, 3, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( userNameLabel, userNameLabelConstraints );GBC passwordLabelConstraints = new GBC( 0, 4, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( passwordLabel, passwordLabelConstraints );GBC passwordConfirmLabelConstraints = new GBC( 0, 5, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ) .setFill(GBC.NONE ) .setInsets( 0, 0, 0, 10 ) .setIpad( 0, 0 );add( passwordConfirmLabel, passwordConfirmLabelConstraints );GBC departmentLabelConstraints = new GBC( 0, 6, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 10 ) .setIpad( 0, 0 );add( departmentLabel, departmentLabelConstraints );GBC firstNameFieldConstraints = new GBC( 1, 0, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( firstNameField, firstNameFieldConstraints );GBC lastNameFieldConstraints = new GBC( 1, 1, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( lastNameField, lastNameFieldConstraints );GBC emailFieldConstraints = new GBC( 1, 2, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( emailField, emailFieldConstraints );GBC userNameFieldConstraints = new GBC( 1, 3, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( userNameField, userNameFieldConstraints );GBC passwordFieldConstraints = new GBC( 1, 4, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( passwordField, passwordFieldConstraints );GBC passwordConfirmFieldConstraints = new GBC( 1, 5, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( passwordConfirmField, passwordConfirmFieldConstraints );GBC departmentListConstraints = new GBC( 1, 6, 1, 1 ).setWeight( 1, 1 ).setAnchor( GBC.WEST ).setFill( GBC.HORIZONTAL ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( departmentList, departmentListConstraints );GBC updateUserButtonConstraints = new GBC( 0, 7, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( updateUserButton, updateUserButtonConstraints );GBC cancelButtonConstraints = new GBC( 1, 7, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( cancelButton, cancelButtonConstraints );//@formatter:on}@Overridepublic void actionPerformed( ActionEvent e ) {if( Arrays.asList( SAVE_PROFILE, UPDATE_PROFILE, CANCEL ).contains( e.getActionCommand() ) ) {switch( e.getActionCommand() ) {case SAVE_PROFILE:getUserDetails( user );if( !user.isValid() ) {invalidUser();return;}message.onAdd( user );break;case UPDATE_PROFILE:getUserDetails( user );if( !user.isValid() ) {invalidUser();return;}message.onUpdate( user );break;case CANCEL:cancel();message.onCancel();break;default:throw new UnhandledException( "Error Unhandled event [" + e.getSource() + "]" );}}}public void newUser() {UserVO newUser = new UserVO();clearForm();setState( FORM_ENABLED );setMode( MODE_ADD );setUser( newUser );}public void setUser( UserVO user ) {this.user = user;}public void selectUser( UserVO selectedUser ) {clearForm();setState( FORM_ENABLED );setMode( MODE_UPDATE );setUser( selectedUser );refreshForm();}public void getUserDetails( UserVO currentUser ) {currentUser.firstName = firstNameField.getText();currentUser.lastName = lastNameField.getText();currentUser.email = emailField.getText();currentUser.username = userNameField.getText();currentUser.password = Arrays.toString( passwordField.getPassword() );currentUser.department = (String) departmentList.getSelectedItem();}public void cancel() {clearForm();setUser( null );setMode( MODE_ADD );setState( FORM_DISABLED );}public void refreshForm() {firstNameField.setText( user.firstName );lastNameField.setText( user.lastName );emailField.setText( user.email );userNameField.setText( user.username );passwordField.setText( user.password );passwordConfirmField.setText( user.password );departmentList.setSelectedItem( user.department );}public void clearForm() {firstNameField.setText( "" );lastNameField.setText( "" );emailField.setText( "" );userNameField.setText( "" );passwordField.setText( "" );passwordConfirmField.setText( "" );departmentList.setSelectedItem( Department.NONE_SELECTED.getValue() );}public void setMode( int mode ) {switch( mode ) {case MODE_ADD:firstNameField.requestFocus();updateUserButton.setText( SAVE_PROFILE );break;case MODE_UPDATE:updateUserButton.setText( UPDATE_PROFILE );setState( FORM_ENABLED );break;default:break;}}public void setState( int state ) {boolean enabled = ( state == FORM_ENABLED );firstNameField.setEnabled( enabled );lastNameField.setEnabled( enabled );emailField.setEnabled( enabled );userNameField.setEnabled( enabled );passwordField.setEnabled( enabled );passwordConfirmField.setEnabled( enabled );departmentList.setEnabled( enabled );updateUserButton.setEnabled( enabled );cancelButton.setEnabled( enabled );}public void invalidUser(){JOptionPane.showMessageDialog( null, "All fields are required.","Invalid User",JOptionPane.WARNING_MESSAGE );}public void setMessage( UserFormMessage message ) {this.message = message;}}
package employeeadmin.view.components;import api.Utils.BorderBuilder;
import api.Utils.GBC;
import api.Utils.UnhandledException;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.interfaces.RolePanelMessage;import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.util.Arrays;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/3/2015*/
public class RolePanel extends JPanel implements ActionListener, ListSelectionListener, ItemListener {public static final int MODE_ADD = 1;public static final int MODE_ACTIVE = 2;public static final int MODE_UPDATE = 3;public static final int FORM_ENABLED = 4;public static final int FORM_DISABLED = 5;private static final String ADD_ROLE = "Add";private static final String REMOVE_ROLE = "Remove";private JList roles;private DefaultListModel roleModel;private DefaultComboBoxModel roleListModel;private JComboBox roleList;private JButton addButton;private JButton removeButton;private List userRoles;private UserVO user;private Role role;private String roleValue;private RolePanelMessage message;public RolePanel() {setLayout( new GridBagLayout() );//@formatter:offsetBorder(new BorderBuilder( "User Roles", TitledBorder.LEFT, TitledBorder.DEFAULT_POSITION, 2, Font.BOLD, 12 ) );//@formatter:oninitComponents();}private void initComponents() {roleModel = new DefaultListModel<>();roles = new JList<>( roleModel );roles.setPreferredSize( new Dimension( 260, 200 ) );roles.addListSelectionListener( this );roleListModel = new DefaultComboBoxModel<>();for(Role role : Role.list()) {roleListModel.addElement( role.getValue() );}roleList = new JComboBox<>( roleListModel );roleList.addItemListener( this );addButton = new JButton( ADD_ROLE );addButton.addActionListener( this );removeButton = new JButton( REMOVE_ROLE );removeButton.addActionListener( this );//@formatter:offGBC rolesConstraints = new GBC( 0, 0, 3, 1 ).setWeight( 1, 1 ).setAnchor( GBC.NORTH ).setFill( GBC.BOTH ) .setInsets(0, 0, 0, 0 ) .setIpad( 0, 0 );add( roles, rolesConstraints );GBC roleListConstraints = new GBC( 0, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 2 ) .setIpad( 0, 0 );add( roleList, roleListConstraints );GBC addButtonConstraints = new GBC( 1, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets(0, 0, 0, 2 ) .setIpad( 0, 0 );add( addButton, addButtonConstraints );GBC removeButtonConstraints = new GBC( 2, 1, 1, 1 ).setWeight( 0, 0 ).setAnchor( GBC.LINE_START ).setFill( GBC.NONE ) .setInsets( 0, 0, 0, 0 ) .setIpad( 0, 0 );add( removeButton, removeButtonConstraints );//@formatter:on}@Overridepublic void actionPerformed( ActionEvent e ) {if( Arrays.asList( ADD_ROLE, REMOVE_ROLE ).contains( e.getActionCommand() ) ) {switch( e.getActionCommand() ) {case ADD_ROLE:onAdd( user, roleValue );break;case REMOVE_ROLE:onRemove( user, roleValue );break;default:throw new UnhandledException( "Error Unhandled event [" + e.getSource() + "]" );}}}private void onRemove( UserVO user, String roleValue ) {setUser( user );setRole( roleValue );message.onRemove( user, role );}private void onAdd( UserVO user, String roleValue ) {setUser( user );setRole( roleValue );message.onAdd( user, role );}@Overridepublic void valueChanged( ListSelectionEvent e ) {if( !roles.isSelectionEmpty() && !e.getValueIsAdjusting() ) {this.roleValue = roles.getSelectedValue();setMode( MODE_UPDATE );}}@Overridepublic void itemStateChanged( ItemEvent e ) {if( e.getStateChange() == ItemEvent.SELECTED ) {this.roleValue = (String) e.getItem();setMode( roleValue.equals( Role.NONE_SELECTED.getValue() ) ? MODE_UPDATE : MODE_ADD );}}public void setUser( UserVO selectedUser ) {this.user = selectedUser;}public void reloadRoles() {for(Role role : userRoles) {roleModel.addElement( role.getValue() );}}public void setRole( String selectedValue ) {Role.list().stream().filter( role -> role.getValue().equals( selectedValue ) ).forEach( role -> {this.role = role;} );}public void setMode( int mode ) {switch( mode ) {case MODE_ADD:roles.getSelectionModel().clearSelection();roleList.setEnabled( true );addButton.setEnabled( true );removeButton.setEnabled( false );break;case MODE_ACTIVE:roles.getSelectionModel().clearSelection();roleListModel.setSelectedItem( Role.NONE_SELECTED.getValue() );roleList.setEnabled( true );addButton.setEnabled( false );removeButton.setEnabled( false );break;case MODE_UPDATE:roleList.setEnabled( true );addButton.setEnabled( false );removeButton.setEnabled( true );break;default:break;}}public void setState( int state ) {boolean enabled = ( state == FORM_ENABLED );roles.setEnabled( enabled );roleList.setEnabled( enabled );addButton.setEnabled( enabled );removeButton.setEnabled( enabled );}public void setMessage( RolePanelMessage message ) {this.message = message;}public void refreshPanel() {roleModel.clear();}public void setRoles( List userRoles ) {this.userRoles = userRoles;}public UserVO getUser() {return user;}public void selectUser( UserVO user ) {refreshPanel();setState( RolePanel.FORM_ENABLED );setUser( user );setMode( MODE_ACTIVE );reloadRoles();}public void cancel() {refreshPanel();setState( RolePanel.FORM_DISABLED );}
}
消息传递适配器
如所解释的,每个组件都包含其适配器接口的实例,该接口允许组件将消息发送到其介体。 然后,调解员将消息广播到感兴趣的观察者的任意列表。
下面的对象图说明了UserList
协作者如何在整个应用程序中进行通信。 请注意UserListMediator
如何充当Mediator/Controller
并如何通过UserListMessage
适配器接口将消息引导到UserList
。
package employeeadmin.view.interfaces;import employeeadmin.model.vo.UserVO;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/8/15*/
public interface UserListMessage {void onNew();void onSelect( UserVO user );void onDelete( UserVO user );}
package employeeadmin.view.interfaces;import employeeadmin.model.vo.UserVO;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/8/2015*/
public interface UserFormMessage {void onAdd( UserVO user );void onUpdate( UserVO user );void onCancel();}
package employeeadmin.view.interfaces;import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.UserVO;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/8/2015*/
public interface RolePanelMessage {void onAdd( UserVO user, Role role );void onRemove( UserVO user, Role role );
}
调解员控制器
每个mediator
充当mediating controller
,处理其视图组件的注册,注册要通知的应用程序事件并处理通知实现。
package employeeadmin.view;import employeeadmin.ApplicationFacade;
import employeeadmin.model.UserProxy;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.UserList;
import employeeadmin.view.interfaces.UserListMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;import java.util.ArrayList;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/4/2015*/
public class UserListMediator extends Mediator implements UserListMessage {public static final String NAME = "UserListMediator";private UserProxy userProxy;public UserListMediator( UserList viewComponent ) {super( NAME, viewComponent );}@Overridepublic void onRegister() {getUserList().setMessage( this );}public String[] listNotificationInterests() {return new String[]{ApplicationFacade.INIT_USERS,ApplicationFacade.USER_ADDED,ApplicationFacade.USER_UPDATED,ApplicationFacade.USER_DELETED,ApplicationFacade.USER_SELECTED,ApplicationFacade.CANCEL_SELECTED};}@Overridepublic void handleNotification( final INotification note ) {userProxy = (UserProxy) getFacade().retrieveProxy( "UserProxy" );final ArrayList users = userProxy.getUsers();switch( note.getName() ) {case ApplicationFacade.INIT_USERS:getUserList().reloadUsers( users );break;case ApplicationFacade.USER_ADDED:getUserList().reloadUsers( users );getUserList().addUser( (UserVO) note.getBody() );break;case ApplicationFacade.USER_UPDATED:getUserList().reloadUsers( users );break;case ApplicationFacade.USER_SELECTED:getUserList().setUser( userProxy.getUser( (UserVO) note.getBody() ) );break;case ApplicationFacade.CANCEL_SELECTED:getUserList().cancelSelection();break;case ApplicationFacade.USER_DELETED:getUserList().reloadUsers( users );getUserList().cancelSelection();break;}}@Overridepublic void onNew() {sendNotification( ApplicationFacade.NEW_USER );}@Overridepublic void onSelect( UserVO user ) {sendNotification( ApplicationFacade.USER_SELECTED, user );}@Overridepublic void onDelete( UserVO user ) {sendNotification( ApplicationFacade.DELETE_USER, user );}private UserList getUserList() {return (UserList) viewComponent;}}
package employeeadmin.view;import employeeadmin.ApplicationFacade;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.UserForm;
import employeeadmin.view.interfaces.UserFormMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/5/2015*/
public class UserFormMediator extends Mediator implements UserFormMessage {public static String NAME = "UserFormMediator";public UserFormMediator( UserForm viewComponent ) {super( NAME, viewComponent );setViewComponent( viewComponent );}public String[] listNotificationInterests() {return new String[]{ApplicationFacade.NEW_USER,ApplicationFacade.USER_SELECTED,ApplicationFacade.USER_DELETED};}@Overridepublic void onRegister() {getUserForm().setMessage( this );getUserForm().setMode( UserForm.MODE_ADD );getUserForm().setState( UserForm.FORM_DISABLED );}@Overridepublic void handleNotification( INotification note ) {switch( note.getName() ) {case ApplicationFacade.NEW_USER:getUserForm().newUser();break;case ApplicationFacade.USER_SELECTED:getUserForm().selectUser( (UserVO) note.getBody() );break;case ApplicationFacade.USER_DELETED:getUserForm().setState( UserForm.FORM_DISABLED );getUserForm().clearForm();break;}}@Overridepublic void onAdd( UserVO user ) {sendNotification( ApplicationFacade.USER_ADDED, user );}@Overridepublic void onUpdate( UserVO user ) {sendNotification( ApplicationFacade.USER_UPDATED, user );}@Overridepublic void onCancel() {sendNotification( ApplicationFacade.CANCEL_SELECTED );}private UserForm getUserForm() {return (UserForm) viewComponent;}
}
package employeeadmin.view;import employeeadmin.ApplicationFacade;
import employeeadmin.model.RoleProxy;
import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import employeeadmin.view.components.RolePanel;
import employeeadmin.view.interfaces.RolePanelMessage;
import org.puremvc.java.multicore.interfaces.INotification;
import org.puremvc.java.multicore.patterns.mediator.Mediator;import java.util.ArrayList;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/5/2015*/
public class RolePanelMediator extends Mediator implements RolePanelMessage {public static String NAME = "RolePanelMediator";private RoleProxy roleProxy;public RolePanelMediator( RolePanel viewComponent ) {super( NAME, viewComponent );setViewComponent( viewComponent );}@Overridepublic void onRegister() {getRolePanel().setMessage( this );getRolePanel().setState( RolePanel.FORM_DISABLED );}@Overridepublic String[] listNotificationInterests() {return new String[]{ApplicationFacade.NEW_USER,ApplicationFacade.USER_ADDED,ApplicationFacade.USER_UPDATED,ApplicationFacade.USER_DELETED,ApplicationFacade.CANCEL_SELECTED,ApplicationFacade.USER_SELECTED,ApplicationFacade.ADD_ROLE_RESULT};}public void handleNotification( INotification note ) {roleProxy = (RoleProxy) getFacade().retrieveProxy( "RoleProxy" );switch( note.getName() ) {case ApplicationFacade.NEW_USER:break;case ApplicationFacade.USER_ADDED:getRolePanel().setUser( (UserVO) note.getBody() );roleProxy.addRole( new RoleVO( ( (UserVO) note.getBody() ).username, new ArrayList<>() ) );break;case ApplicationFacade.USER_UPDATED:break;case ApplicationFacade.USER_DELETED:break;case ApplicationFacade.CANCEL_SELECTED:getRolePanel().cancel();break;case ApplicationFacade.USER_SELECTED:List roles = roleProxy.getUserRoles( ( (UserVO) note.getBody() ).username );getRolePanel().setRoles( roles );getRolePanel().selectUser( (UserVO) note.getBody() );break;case ApplicationFacade.ADD_ROLE_RESULT:break;default:break;}}@Overridepublic void onAdd( UserVO user, Role role ) {List roles = roleProxy.getUserRoles( user.username );roleProxy.addRoleToUser( user, role );getRolePanel().refreshPanel();getRolePanel().reloadRoles();sendNotification( ApplicationFacade.ADD_ROLE, user );}@Overridepublic void onRemove( UserVO user, Role role ) {roleProxy.removeRoleFromUser( user, role );getRolePanel().refreshPanel();getRolePanel().reloadRoles();sendNotification( ApplicationFacade.USER_UPDATED, user );}public RolePanel getRolePanel() {return (RolePanel) viewComponent;}}
模型层
此应用程序的模型层由两个枚举,两个值对象和两个代理对象组成。 值对象在视图组件中用于通过委派模型层对代理对象的访问来支持关注点分离–它们创建重复的代码,但它们有很好的用途。 代理对象本质上负责所有数据访问。
package employeeadmin.model.enums;import org.apache.commons.lang3.builder.ToStringBuilder;import java.util.ArrayList;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/9/2015*/
public enum Department {NONE_SELECTED( "--None Selected--", -1 ),ACCT( "Accounting", 0 ),SALES( "Sales", 1 ),PLANT( "Plant", 2 ),SHIPPING( "Shipping", 3 ),QC( "Quality Control", 4 );private final String value;private final Integer ordinal;Department( String value, Integer ordinal ) {this.value = value;this.ordinal = ordinal;}public static List list() {ArrayList list = new ArrayList<>();list.add( NONE_SELECTED );list.add( ACCT );list.add( SALES );list.add( PLANT );return list;}public String getValue() {return value;}public Integer getOrdinal() {return ordinal;}@Overridepublic String toString() {return ToStringBuilder.reflectionToString( this );}
}
package employeeadmin.model.enums;import java.util.ArrayList;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/9/2015*/
public enum Role {/*** Roles.*/NONE_SELECTED( "--None Selected--", -1 ),ADMIN( "Administrator", 0 ),ACCT_PAY( "Accounts Payable", 1 ),ACCT_RCV( "Accounts Receivable", 2 ),EMP_BENEFITS( "Employee Benefits", 3 ),GEN_LEDGER( "General Ledge", 4 ),PAYROLL( "Payroll", 5 ),INVENTORY( "Inventory", 6 ),PRODUCTION( "Production", 7 ),QUALITY_CTL( "Quality Control", 8 ),SALES( "Sales", 9 ),ORDERS( "Orders", 10 ),CUSTOMERS( "Customers", 11 ),SHIPPING( "Shipping", 12 ),RETURNS( "Returns", 13 );private final Integer ordinal;private final String value;Role( String value, Integer ordinal ) {this.value = value;this.ordinal = ordinal;}public static List list() {ArrayList list = new ArrayList<>();list.add( NONE_SELECTED );list.add( ADMIN );list.add( ACCT_PAY );list.add( ACCT_RCV );list.add( EMP_BENEFITS );list.add( GEN_LEDGER );list.add( PAYROLL );list.add( INVENTORY );list.add( PRODUCTION );list.add( QUALITY_CTL );list.add( SALES );list.add( ORDERS );list.add( CUSTOMERS );list.add( SHIPPING );list.add( RETURNS );return list;}public Integer getOrdinal() {return ordinal;}public String getValue() {return value;}
}
package employeeadmin.model.vo;import employeeadmin.model.enums.Department;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;import java.io.Serializable;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/2/2015*/
public class UserVO implements Serializable {public static final long serialVersionUID = 1L;public String username;public String firstName;public String lastName;public String email;public String password;public String department;public UserVO() {}public UserVO( final String userName, final String firstName, final String lastName, final String email,final String password, final String department ) {this.username = userName;this.firstName = firstName;this.lastName = lastName;this.email = email;this.password = password;this.department = department != null ? department : Department.NONE_SELECTED.getValue();}public final boolean isValid() {return( !"".equals( username ) ) &&( !"".equals( firstName ) ) &&( !"".equals( lastName ) ) &&( !"".equals( email ) ) &&( !"".equals( password ) ) &&( !Department.NONE_SELECTED.getValue().equals( department ) );}@Overridepublic boolean equals( Object o ) {if( this == o ) { return true; }if( !( o instanceof UserVO ) ) { return false; }UserVO userVO = (UserVO) o;return new EqualsBuilder().append( username, userVO.username ).append( firstName, userVO.firstName ).append( lastName, userVO.lastName ).append( email, userVO.email ).append( password, userVO.password ).append( department, userVO.department ).isEquals();}@Overridepublic int hashCode() {return new HashCodeBuilder( 17, 37 ).append( username ).append( firstName ).append( lastName ).append( email ).append( password ).append( department ).toHashCode();}@Overridepublic String toString() {return ToStringBuilder.reflectionToString( this, ToStringStyle.JSON_STYLE );}
}
package employeeadmin.model.vo;import employeeadmin.model.enums.Role;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/2/2015*/
public class RoleVO implements Serializable {public static final long serialVersionUID = 1L;public String username;public List roles = new ArrayList<>();public RoleVO( final String username, final List roles ) {if( username != null ) {this.username = username;}if( roles != null ) {this.roles = new ArrayList<>( roles );}}@Overridepublic boolean equals( Object o ) {if( this == o ) { return true; }if( !( o instanceof RoleVO ) ) { return false; }RoleVO roleVO = (RoleVO) o;return new EqualsBuilder().append( username, roleVO.username ).append( roles, roleVO.roles ).isEquals();}@Overridepublic int hashCode() {return new HashCodeBuilder( 17, 37 ).append( username ).append( roles ).toHashCode();}@Overridepublic String toString() {return ToStringBuilder.reflectionToString( this, ToStringStyle.JSON_STYLE );}
}
package employeeadmin.model;import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.patterns.proxy.Proxy;import java.util.ArrayList;
import java.util.List;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/2/2015*/
public class UserProxy extends Proxy {public static final String NAME = "UserProxy";public static List USERS = new ArrayList<>();public UserProxy() {super( NAME, USERS );}@SuppressWarnings( "unchecked" )public final ArrayList getUsers() {return (ArrayList) this.getData();}public final UserVO getUser( UserVO userVO ) {for(UserVO user : getUsers()) {if( userVO == user ) {return user;}}return null;}public final void addUser( final UserVO user ) {getUsers().add( user );}public final void updateUser( final UserVO user ) {for(int i = 0; i < getUsers().size(); i++) {if( getUsers().get( i ).username.equals( user.username ) ) {getUsers().set( i, user );}}}public final void deleteUser( final UserVO user ) {if( getUsers().contains( user ) ) {getUsers().remove( user );}}
}
package employeeadmin.model;import employeeadmin.model.enums.Role;
import employeeadmin.model.vo.RoleVO;
import employeeadmin.model.vo.UserVO;
import org.puremvc.java.multicore.patterns.proxy.Proxy;import java.util.ArrayList;
import java.util.List;import static employeeadmin.ApplicationFacade.ADD_ROLE_RESULT;/*** @author Edward Beckett :: <Edward@EdwardBeckett.com>* @since :: 6/2/2015*/
public class RoleProxy extends Proxy {public static final String NAME = "RoleProxy";private static final List ROLES = new ArrayList<>();public RoleProxy() {super( NAME, ROLES );}@SuppressWarnings( "unchecked" )public final List getRoles() {return (List) this.getData();}public final void addRole( final RoleVO role ) {getRoles().add( role );}public final void deleteRole( final UserVO user ) {for(int i = 0; i < getRoles().size(); i++) {if( getRoles().get( i ).username.equals( user.username ) ) {getRoles().remove( i );}}}public final boolean userHasRole( final UserVO user, final Role role ) {boolean hasRole = false;for(int i = 0; i < getRoles().size(); i++) {if( getRoles().get( i ).username.equals( user.username ) ) {List userRoles = getRoles().get( i ).roles;for(Role userRole : userRoles) {if( role.equals( userRole ) ) {hasRole = true;break;}}break;}}return hasRole;}public final void addRoleToUser( final UserVO user, final Role role ) {boolean result = false;if( !userHasRole( user, role ) ) {for(int i = 0; i < getRoles().size(); i++) {if( getRoles().get( i ).username.equals( user.username ) ) {List userRoles = getRoles().get( i ).roles;userRoles.add( role );result = true;break;}}}sendNotification( ADD_ROLE_RESULT, result );}public final void removeRoleFromUser( final UserVO user, final Role role ) {if( userHasRole( user, role ) ) {for(int i = 0; i < getRoles().size(); i++) {if( getRoles().get( i ).username.equals( user.username ) ) {List userRoles = getRoles().get( i ).roles;for(int j = 0; j < userRoles.size(); j++) {if( userRoles.get( j ).equals( role ) ) {userRoles.remove( j );break;}}break;}}}}public final List getUserRoles( final String username ) {List userRoles = new ArrayList<>();for(int i = 0; i < getRoles().size(); i++) {if( getRoles().get( i ).username.equals( username ) ) {userRoles = getRoles().get( i ).roles;break;}}return userRoles;}}
翻译自: https://www.javacodegeeks.com/2015/09/java-swing-model-view-adapter-mediator.html
swing 状态视图分离