swing 状态视图分离_Java Swing模型视图适配器介体

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

swing 状态视图分离

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

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

相关文章

超级炫酷的C语言技巧!

点击蓝字关注我们C语言常常让人觉得它所能表达的东西非常有限。它不具有类似第一级函数和模式匹配这样的高级功能。但是C非常简单&#xff0c;并且仍然有一些非常有用的语法技巧和功能&#xff0c;只是没有多少人知道罢了。一、指定的初始化很多人都知道像这样来静态地初始化数…

webgl 基础渲染demo_WebGL + ThreeJS 实现实时水下焦散 Part 1

知乎视频​www.zhihu.com采用 WebGL 和 ThreeJS 运行实时焦散运算&#xff0c;需要一点相关基础。本文主要介绍焦散的原理以及计算方法原作者https://github.com/martinRenou​github.com代码和原文https://github.com/martinRenou/threejs-caustics​github.com由于本人的笔电…

超硬核C++BestPractices翻译与阅读笔记

点击蓝字关注我们硬货开始这本书的副标题是&#xff1a;45ish Simple Rules with Specific Action items for better C ,这本书是由大佬推荐的&#xff0c; C学习有必要掌握一下这45条最佳实践&#xff0c; 可以很大程度上提升代码的可读性和健壮性&#xff0c; 而且这本书也不…

diskgenius单文件专业版_金蝶KIS专业版系列——系统工具六(业务套打工具)

导读&#xff1a;&#xff08;一&#xff09;问一问1.1.套打的作用1.2.举例&#xff08;二&#xff09;怎么进入套打设计器2.1.入口12.2.入口2&#xff08;三&#xff09;怎么使用套打设计器打开套打模板3.1.打开系统标准套打模板3.2.新建一个空白的套打模板3.3.保存套打模板3.…

面试常问的16个C语言问题,你全会吗?

点击蓝字关注我们金三银四不少小伙伴在找工作&#xff0c;这里我给大家分享一下面试中经常会遇到的一些嵌入式C语言问题&#xff0c;你看看能做到全会吗&#xff1f;1、用预处理指令#define 声明一个常数&#xff0c;用以表明1年中有多少秒&#xff08;忽略闰年问题&#xff09…

高性能 高可用 可弹性伸缩_性能,可伸缩性和活力

高性能 高可用 可弹性伸缩本文是我们名为Java Concurrency Essentials的学院课程的一部分。 在本课程中&#xff0c;您将深入探讨并发的魔力。 将向您介绍并发和并发代码的基础知识&#xff0c;并学习诸如原子性&#xff0c;同步和线程安全性的概念。 在这里查看 &#xff01;…

iptables命令_程序员最有用的linux命令汇总

总结程序员在工作中&#xff0c;最有用的linux命令如下&#xff1a;1、vi/vim 我们须要在服务器上代码一些代码时候&#xff0c;就用vi/vim命令就可以&#xff0c;vim是vi的升级&#xff0c;本色自带代码高亮工具&#xff0c;利于查看。dd 删除光标所在行o 向光标所在行向下增加…

详解C++异常

点击蓝字关注我们1、异常概念异常是一种处理错误的方式&#xff0c;当一个函数发现自己无法处理的错误时就可以抛出异常&#xff0c;让函数的直接或间接的调用者处理这个错误。throw: 当问题出现时&#xff0c;程序会抛出一个异常。这是通过使用 throw 关键字来完成的。catch: …

C语言基础知识:指针与数组的区别是什么

点击蓝字关注我们在C语言教程中我们使用通过数组名通过偏移和指针偏移都可以遍历数组&#xff0c;那么指针和数组到底有什么区别&#xff1f;&#xff1f;由于数组中的数据在内存中都是连续存放的&#xff0c;数组名默认就是数组的首地址&#xff0c;也是一个特殊的指针&#x…

java java se_Java 8 SE可选,严格的方法

java java se大约两周前&#xff0c;Stephen Colebourne提出了使用Optional的实用方法 。 如果您阅读了它&#xff0c;您可能会从我以前的建议中猜到我不同意。 总览 我必须以免责声明开头&#xff0c;然后我将直接解释为什么我认为他的方法不那么理想。 所有不归因于他人的报…

std::thread 还有哪些使用“姿势”?

点击蓝字关注我们C11 线程创建每一个 C11 程序都包含一个主线程即 main() 函数。在 C11 中我们可以通过创建 std::thread 对象来创建新的线程。每个 std::thread 对象都可以与一个线程相关联。需要引用的头文件&#xff1a;1#include <thread>std::thread 的构造函数中接…

用python画皇冠_手把手教你用 Python 绘制酷炫的桑基图!

原标题&#xff1a;手把手教你用 Python 绘制酷炫的桑基图&#xff01;作者 | 周志鹏 责编 | 郭 芮 最近&#xff0c;不止一次收到小伙伴的截图追问&#xff1a;“这个图叫什么&#xff1f;&#xff1f;&#xff1f;” “这个图真好看&#xff01;&#xff01;&#xff01;怎么…

为啥电脑从C盘开始?A、B盘去哪了?

点击蓝字关注我们前些天硬盘坏了&#xff0c;幸好不是系统盘&#xff0c;不然那些软件安装配置会把我折腾坏&#xff0c;或许这也是在暗示我该换电脑了。重要的数据部分没有遭到损坏&#xff0c;数据是无价的&#xff0c;还是要勤备份。于是换上了一张新的硬盘&#xff0c;当时…

java 锁_Java之线程并发的各种锁、锁、锁

因为两周没更新了...也不是懒&#xff0c;这两周确实有些忙&#xff0c;赶项目进度赶的不亦乐乎...终于赶在工期前&#xff0c;可以进入内测了&#xff0c;我也有了些时间&#xff0c;可以更新啦...线程并发锁是很常见的问题&#xff0c;而且在Java中锁的类型、概念、使用场景等…

C语言编程中错误异常该如何统一处理?1.8万字总结

点击蓝字关注我们本文主要总结嵌入式系统C语言编程中&#xff0c;主要的错误处理方式。一、错误概念1.1 错误分类从严重性而言&#xff0c;程序错误可分为致命性和非致命性两类。对于致命性错误&#xff0c;无法执行恢复动作&#xff0c;最多只能在用户屏幕上打印出错消息或将其…

pycharm remote 远程项目 同步 本地_利器:PyCharm本地连接服务器搭建深度学习实验环境的三重境界...

作为实验室社畜&#xff0c;常需要在本地使用Pycharm写代码&#xff0c;然后将代码同步到服务器上&#xff0c;使用远程登录服务器并运行代码做实验。这其中有很多事情如果没有好的工具&#xff0c;做起来会非常麻烦。比如如何快速同步本地与服务器的代码&#xff1f;如何优雅地…

防御性编程技巧

点击蓝字关注我们在防御性编程的大框架之下&#xff0c;有许多常识性的规则。人们在想到防御性编程的时候&#xff0c;通常都会想到“断言”&#xff0c;这没有错。我们将在后面对此进行讨论。但是&#xff0c;还是有一些简单的编程习惯可以极大地提高代码的安全性。尽管看上去…

cookie无法读取bdstoken_第二章(第12节):cookie操作

有时候我们需要验证浏览器中 cookie 是否正确&#xff0c;因为基于真实 cookie 的测试是无法通过白盒和集成测试进行的。WebDriver 提供了操作 cookie 的相关方法&#xff0c;可以读取、添加和删除 cookie信息。WebDriver 操作 cookie 的方法&#xff1a;get_cookies()&#xf…

C++ 基本的输入输出

点击蓝字关注我们C 标准库虽然提供了一组丰富的输入/输出功能&#xff0c;但是本章只讨论 C 编程中最基本和最常见的 I/O 操作。C 的 I/O 发生在流中&#xff0c;流是字节序列。如果字节流是从设备&#xff08;如键盘、磁盘驱动器、网络连接等&#xff09;流向内存&#xff0c;…

http 和 https_HTTPS与HTTP区别

HTTPS与HTTP的认识&#xff1a;HTTP 加密 认证 完整性保护 HTTPSHTTP的全称是 Hypertext Transfer Protocol Vertion (超文本传输协议)HTTPS&#xff1a; HTTPS(Secure Hypertext Transfer Protocol)安全超文本传输协议。HTTPS和HTTP的区别&#xff1a;HTTPS协议需要到ca申…