MVC Pattern in Java 2 : MVC Pattern « Design Pattern « Java






MVC Pattern in Java 2

MVC Pattern in Java 2
//[C] 2002 Sun Microsystems, Inc.---
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.ArrayList;
import java.util.Iterator;

import javax.swing.BoxLayout;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
public class RunMVCPattern {
    public static void main(String [] arguments){
        System.out.println("Example for the MVC pattern");
        System.out.println();
        System.out.println("In this example, a Contact is divided into");
        System.out.println(" Model, View and Controller components.");
        System.out.println();
        System.out.println("To illustrate the flexibility of MVC, the same");
        System.out.println(" Model will be used to provide information");
        System.out.println(" to two View components.");
        System.out.println();
        System.out.println("One view, ContactEditView, will provide a Contact");
        System.out.println(" editor window and will be paired with a controller");
        System.out.println(" called ContactEditController.");
        System.out.println();
        System.out.println("The other view, ContactDisplayView, will provide a");
        System.out.println(" display window which will reflect the changes made");
        System.out.println(" in the editor window. This view does not support");
        System.out.println(" user interaction, and so does not provide a controller.");
        System.out.println();
        
        System.out.println("Creating ContactModel");
        ContactModel model = new ContactModel();
        
        System.out.println("Creating ContactEditView and ContactEditController");
        ContactEditView editorView = new ContactEditView(model);
        model.addContactView(editorView);
        createGui(editorView, "Contact Edit Window");
        
        System.out.println("Creating ContactDisplayView");
        ContactDisplayView displayView = new ContactDisplayView();
        model.addContactView(displayView);
        createGui(displayView, "Contact Display Window");
    }
    
    private static void createGui(JPanel contents, String title){
        JFrame applicationFrame = new JFrame(title);
        applicationFrame.getContentPane().add(contents);
        applicationFrame.addWindowListener(new WindowCloseManager());
        applicationFrame.pack();
        applicationFrame.setVisible(true);
    }
    
    private static class WindowCloseManager extends WindowAdapter{
        public void windowClosing(WindowEvent evt){
            System.exit(0);
        }
    }
}

//Model
class Contact{
    private String firstName;
    private String lastName;
    private String title;
    private String organization;
    
    private ContactView view;
    
    public Contact(ContactView v){
        
        firstName = "";
        lastName = "";
        title = "";
        organization = "";
        
        view = v;
    }
    
    public String getFirstName(){
        return firstName;
    }
    
    public String getLastName(){
        return lastName;
    }
    
    public String getTitle(){
        return title;
    }
    
    public String getOrganization(){
        return organization;
    }
    
    public void setFirstName(String newFirstName){
        firstName = newFirstName;
    }
    
    public void setLastName(String newLastName){
        lastName = newLastName;
    }
    
    public void setTitle(String newTitle){
        title = newTitle;
    }
    
    public void setOrganization(String newOrganization){
        organization = newOrganization;
    }
    
    public void updateModel(String newFirstName,
        String newLastName, String newTitle,
        String newOrganization){
        
        if ((newFirstName != null) && !newFirstName.equals("")){
            setFirstName(newFirstName);
        }
        
        if ((newLastName != null) && !newLastName.equals("")){
            setLastName(newLastName);
        }
        
        if ((newTitle != null) && !newTitle.equals("")){
            setTitle(newTitle);
        }
        
        if ((newOrganization != null) && !newOrganization.equals("")){
            setOrganization(newOrganization);
        }
        
        updateView();
    }
    
    private void updateView(){
        view.refreshContactView(firstName, lastName, title, organization);
    }
}


interface ContactView{
    public void refreshContactView(String firstName,
        String lastName, String title, String organization);
}

class ContactModel{
    private String firstName;
    private String lastName;
    private String title;
    private String organization;
    private ArrayList contactViews = new ArrayList();
    
    public ContactModel(){
        this(null);
    }
    public ContactModel(ContactView view){
        firstName = "";
        lastName = "";
        title = "";
        organization = "";
        if (view != null){
            contactViews.add(view);
        }
    }
    
    public void addContactView(ContactView view){
        if (!contactViews.contains(view)){
            contactViews.add(view);
        }
    }
    
    public void removeContactView(ContactView view){
        contactViews.remove(view);
    }
    
    public String getFirstName(){ return firstName; }
    public String getLastName(){ return lastName; }
    public String getTitle(){ return title; }
    public String getOrganization(){ return organization; }
    
    public void setFirstName(String newFirstName){ firstName = newFirstName; }
    public void setLastName(String newLastName){ lastName = newLastName; }
    public void setTitle(String newTitle){ title = newTitle; }
    public void setOrganization(String newOrganization){ organization = newOrganization; }
    
    public void updateModel(String newFirstName, String newLastName,
        String newTitle, String newOrganization){
        if (!isEmptyString(newFirstName)){
            setFirstName(newFirstName);
        }
        if (!isEmptyString(newLastName)){
            setLastName(newLastName);
        }
        if (!isEmptyString(newTitle)){
            setTitle(newTitle);
        }
        if (!isEmptyString(newOrganization)){
            setOrganization(newOrganization);
        }
        updateView();
    }
    
    private boolean isEmptyString(String input){
        return ((input == null) || input.equals(""));
    }
    
    private void updateView(){
        Iterator notifyViews = contactViews.iterator();
        while (notifyViews.hasNext()){
            ((ContactView)notifyViews.next()).refreshContactView(firstName, lastName, title, organization);
        }
    }
}


class ContactEditView extends JPanel implements ContactView{
    private static final String UPDATE_BUTTON = "Update";
    private static final String EXIT_BUTTON = "Exit";
    private static final String CONTACT_FIRST_NAME = "First Name  ";
    private static final String CONTACT_LAST_NAME = "Last Name  ";
    private static final String CONTACT_TITLE = "Title  ";
    private static final String CONTACT_ORG = "Organization  ";
    private static final int FNAME_COL_WIDTH = 25;
    private static final int LNAME_COL_WIDTH = 40;
    private static final int TITLE_COL_WIDTH = 25;
    private static final int ORG_COL_WIDTH = 40;
    private ContactEditController controller;
    private JLabel firstNameLabel, lastNameLabel, titleLabel, organizationLabel;
    private JTextField firstName, lastName, title, organization;
    private JButton update, exit;
    
    public ContactEditView(ContactModel model){
        controller = new ContactEditController(model, this);
        createGui();
    }
    public ContactEditView(ContactModel model, ContactEditController newController){
        controller = newController;
        createGui();
    }
    
    public void createGui(){
        update = new JButton(UPDATE_BUTTON);
        exit = new JButton(EXIT_BUTTON);
        
        firstNameLabel = new JLabel(CONTACT_FIRST_NAME);
        lastNameLabel = new JLabel(CONTACT_LAST_NAME);
        titleLabel = new JLabel(CONTACT_TITLE);
        organizationLabel = new JLabel(CONTACT_ORG);
        
        firstName = new JTextField(FNAME_COL_WIDTH);
        lastName = new JTextField(LNAME_COL_WIDTH);
        title = new JTextField(TITLE_COL_WIDTH);
        organization = new JTextField(ORG_COL_WIDTH);
        
        JPanel editPanel = new JPanel();
        editPanel.setLayout(new BoxLayout(editPanel, BoxLayout.X_AXIS));
        
        JPanel labelPanel = new JPanel();
        labelPanel.setLayout(new GridLayout(0, 1));
        
        labelPanel.add(firstNameLabel);
        labelPanel.add(lastNameLabel);
        labelPanel.add(titleLabel);
        labelPanel.add(organizationLabel);
        
        editPanel.add(labelPanel);
        
        JPanel fieldPanel = new JPanel();
        fieldPanel.setLayout(new GridLayout(0, 1));
        
        fieldPanel.add(firstName);
        fieldPanel.add(lastName);
        fieldPanel.add(title);
        fieldPanel.add(organization);
        
        editPanel.add(fieldPanel);
        
        JPanel controlPanel = new JPanel();
        controlPanel.add(update);
        controlPanel.add(exit);
        update.addActionListener(controller);
        exit.addActionListener(new ExitHandler());
        
        setLayout(new BorderLayout());
        add(editPanel, BorderLayout.CENTER);
        add(controlPanel, BorderLayout.SOUTH);
    }
    
    public Object getUpdateRef(){ return update; }
    public String getFirstName(){ return firstName.getText(); }
    public String getLastName(){ return lastName.getText(); }
    public String getTitle(){ return title.getText(); }
    public String getOrganization(){ return organization.getText(); }
    
    public void refreshContactView(String newFirstName,
        String newLastName, String newTitle,
        String newOrganization){
        firstName.setText(newFirstName);
        lastName.setText(newLastName);
        title.setText(newTitle);
        organization.setText(newOrganization);
    }
    
    private class ExitHandler implements ActionListener{
        public void actionPerformed(ActionEvent event){
            System.exit(0);
        }
    }
}

class ContactEditController implements ActionListener{
    private ContactModel model;
    private ContactEditView view;
    
    public ContactEditController(ContactModel m, ContactEditView v){
        model = m;
        view = v;
    }
    
    public void actionPerformed(ActionEvent evt){
        Object source = evt.getSource();
        if (source == view.getUpdateRef()){
            updateModel();
        }
    }
    
    private void updateModel(){
        String firstName = null;
        String lastName = null;
        if (isAlphabetic(view.getFirstName())){
            firstName = view.getFirstName();
        }
        if (isAlphabetic(view.getLastName())){
            lastName = view.getLastName();
        }
        model.updateModel( firstName, lastName,
            view.getTitle(), view.getOrganization());
    }
    
    private boolean isAlphabetic(String input){
        char [] testChars = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0'};
        for (int i = 0; i < testChars.length; i++){
            if (input.indexOf(testChars[i]) != -1){
                return false;
            }
        }
        return true;
    }
}

class ContactDisplayView extends JPanel implements ContactView{
    private JTextArea display;
    
    public ContactDisplayView(){
        createGui();
    }
    
    public void createGui(){
        setLayout(new BorderLayout());
        display = new JTextArea(10, 40);
        display.setEditable(false);
        JScrollPane scrollDisplay = new JScrollPane(display);
        this.add(scrollDisplay, BorderLayout.CENTER);
    }
    
    public void refreshContactView(String newFirstName,
        String newLastName, String newTitle, String newOrganization){
        display.setText("UPDATED CONTACT:\nNEW VALUES:\n" +
            "\tName: " + newFirstName + " " + newLastName +
             "\n" + "\tTitle: " + newTitle + "\n" +
            "\tOrganization: " + newOrganization);
    }
}


           
       








Related examples in the same category

1.MVC LoopMVC Loop
2.MVC ImplementationMVC Implementation