Java 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方法。

java-swing-mva-app-init

这里的顺序很简单。 首先,构建基础框架,然后构建三个主要组件,初始化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依次运行两个子命令PrepViewCommandPrepModelCommand 。 其他两个命令DeleteUserCommandAddRoleResultCommand只是代理帮助程序类。

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 );}}

视图层

该应用程序具有三个协作组件。 UserListUserFormRolePanel 。 每个组件都包含所有必需的子组件,属性和操作,以独立于外部组件运行和管理状态,并通过messaging adapter interfacemediator通信,并直接从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

java-swing-mva-user

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

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/357257.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

程序员跳槽指南

找工作是件非常重要的事情,它直接影响你1~2年,间接影响你3~5年的人生。⼀个潜在的机会会让你少奋斗很多年,而一次冲动的离职,会让你和千万财富错失交臂。 忘掉那些随地乱扔的小广告,还有从几十个样本做出来的所谓调查报告,换工作不是⼀场说走就走的旅行,而是⼀个深思熟虑…

netbeans 源文件_具有NetBeans,WebLogic 12c,JPA和MySQL数据源的Arquillian

netbeans 源文件您可能已关注我的文章&#xff0c;该文章介绍了如何使用嵌入式GlassFish测试更复杂的场景&#xff08; 第I部分/第II部分 &#xff09;。 在我要做的事情上&#xff0c;下一步是使此设置与最新的WebLogic 12c一起使用。 入门 按照我的前两个帖子的入门部分中的…

程序员外包避坑指南?

为什么我不建议你去外包? 外包的分类 外包公司一般有两类,一类是驻场外包,一类是非驻场外包。二者的区别为是否需要被外派到甲方公司上班。如果需要,那么就属于驻场外包,否则就是非驻场外包。 虽然都是外包,但是两者的区别还是挺大的。 先说说驻场外包。由于需要被外派到…

数据库设计三大范式

数据库设计三大范式 为了建立冗余较小、结构合理的数据库&#xff0c;设计数据库时必须遵循一定的规则。在关系型数据库中这种规则就称为范式。范式是符合某一种设计要求的总结。要想设计一个结构合理的关系型数据库&#xff0c;必须满足一定的范式。 在实际开发中最为常见的设…

在各个PC端应用使用表情的快捷键,王大妈都开始用这个表情啦

很多人像在文章或者聊天使用表情&#xff0c;但是不知道如何输入&#xff0c;下面孙叫兽就来带你体验一下吧 快捷键 win. 比如在微信聊天框使用win. 就可以输入表情符号&#xff0c;颜文字及符号。 你们学废了&#xff1f;

扩展Java EE应用程序的基础

老实说&#xff0c;“可扩展性”是一个详尽的主题&#xff0c;并且通常没有被很好地理解。 通常&#xff0c;它被假定与高可用性相同。 我已经看到新手程序员和“经验丰富”的建筑师都建议将“ 集群 ”作为可伸缩性和HA的解决方案。 它实际上没有任何问题&#xff0c;但是问题在…

史上最全wireshark使用教程,8万字整理总结,建议先收藏再耐心研读

目录 第 1 章 介绍... 1 1.1. 什么是Wireshark. 1 1.1.1. 主要应用... 1

小白自学前端,轻松月入过万哦!

第一、 前端的入门操作 首先是要熟悉前端的基础操作。 前端的基础&#xff1a;JavaScript&#xff0c;HTML&#xff0c;CSS&#xff0c;然后可以深入学习jQuery。 如果你是想 1.专攻网页&#xff0c;那你就学习HTML。 2.专攻层叠样式表&#xff0c;就学习CSS&#xff0c;它可以…

netbeans代码提示_Java代码现代化的七个NetBeans提示

netbeans代码提示在“ 七个不可或缺的NetBeans Java提示”一文中 &#xff0c;我谈到了一般使用NetBeans提示的问题&#xff0c;然后重点介绍了七个提示。 接下来列出了该帖子中强调的七个提示&#xff1a; 可疑方法调用 使用或&#xff01; AND字符串构造函数比较字符串 构造…

史上最全SVN使用总结,建议先收藏后观看

最近在公司又开始玩SVN啦&#xff0c;这里给大家总结一下&#xff0c;基本上在公司不是用git就是用SVN进行代码管理&#xff0c;作为程序员&#xff0c;这些工具的使用还是需要熟悉了解一下的&#xff0c;本期孙叫兽给大家分享一下SVN相关的知识点&#xff0c;做到会用即可。不…

JS常用正则表达式

感谢水之原的整理&#xff0c;比较全得正则表达式 整数或者小数&#xff1a;^[0-9]\.{0,1}[0-9]{0,2}$只能输入数字&#xff1a;"^[0-9]*$"。只能输入n位的数字&#xff1a;"^\d{n}$"。只能输入至少n位的数字&#xff1a;"^\d{n,}$"。只能输入m~…

14万字面试题汇总整理,祝你顺利斩获大厂前端offer

导读&#xff1a;最近很多小伙伴私信我说&#xff0c;一般大厂的前端面试题都有哪些&#xff0c;应该如何准备&#xff0c;要不要刷题等等&#xff0c;这里孙叫兽简单给大家总结一下前端的高频面试题&#xff0c;如果对你有帮助&#xff0c;记得点赞评论收藏。现在很多大厂都比…

又见链表 --- 另一种Creat方式与反转

链表 作为一种数据结构&#xff0c;链表以其方便的增删查改功能&#xff0c;实现了无数经典有用的程序。 在之前的帖子里&#xff0c;我构建链表的方式是建立一个不储存数据的head节点&#xff0c;然后通过一边输入数据一边建立结点的方式构建整个链表。 与之前不同的是&#x…

现在抖音这么火,那么你知道如何用CSS实现抖音字体?

比如这种抖音字体是不是感觉很酷,它是如何实现的呢,下面孙叫兽就简单分享一下CSS的实现方法,记得点赞收藏。 老司机给大家的一些小建议,一定要敲代码敲代码敲代码(重要的事情说三遍),程序员是实战家,不是思想家和理论家,程序员都是工兵,这个排雷的经验很重要。 实现这…

史上最全关于苹果开发者账号及上架APPStore总结

很多人如果开发这种移动应用APP,上架到到APPStore难免会遇到一系列的问题,这里孙叫兽进行总结一下,如果本文对你有帮助,记得转发点赞收藏。 一: 开发者账号的介绍 1 个人开发者账号 申请费用: 99美元/年 介绍:一般由iOS开发者个人申请,上架开发者自己的APP作品到苹果商…

EK算法应用,构图(POJ1149)

题目链接&#xff1a;http://poj.org/problem?id1149 题意中有一点要注意&#xff0c;否则构图就会有问题&#xff0c;每个顾客走后&#xff0c;被打开过的那些猪圈中的猪都可以被任意的调换到其他开着的猪圈中。 这里的构图不是单一的相邻&#xff0c;以及容量了&#xff0c;…

平台代码检查工具:sonarLint+sonarqube安装教程

加强对代码质量的管控要求&#xff0c;不允许新增代码部分出现严重、重要、主要等sonar扫描问题。 大家按以下文档安装开发工具对应的代码检测插件&#xff0c;请大家务必重视、执行.这里只介绍前端开发VSCode,后端开发Eclipse,两种代表性的编译器安装sonarLintsonarqube方法,其…

程序员通过CSDN如何获取收益

大家好,我是孙叫兽 ,本期内容给大家分享如何使用CSDN一边学习,一遍赚取收益,这样学习的时候也会产生动力. 废话不多说,直接看近7天收益. 博主如何赚取收益 对于博主这些创作者来说,收益主要有付费专栏,VIP文章收益,活动收益,红包收益,问答收益,打赏收益,付费资源收益,下载VIP分…

《Windows驱动开发技术详解》之编程加载NT式驱动

之前我们加载驱动都是利用INSTDRV这个应用&#xff0c;其原理是在注册表中写入相应的字段&#xff0c;这一节我们手动编写代码去加载驱动&#xff0c;其原理类似&#xff1a; 设备驱动程序的动态加载主要由服务控制管理程序&#xff08;Service Control Manager,SCM&#xff09…

程序员如何快速成长为IT精英

很多程序员工作了很多年,仍然只学到了皮毛点的业务和技术,技术长时间没有提升,一直拖拖拉拉处于某个水平,没有接触到核心业务,也难于成为公司的中流砥柱和骨干。那么程序员该如何成长呢? 1.主动学习 时刻保持危机感,对知识保持好奇心,完善自己的职业规划和知识体系,掌…