Simple MVC desktop example wanted

Hi,
I've been looking and can't find a good example of MVC in a desktop application. I don't mean MVC as it is used in component development (I've seen some examples relating to Swing and Buttonmodels, for instance), but more business-object level. I'm not a Java or Swing expert, but I have been programming for a while and and am pretty comfortable writing non-UI Java classes and simple Swing apps. But I want to know how to do this right.
Here's the simplest example I can think of to explain my confusion:
Suppose I have a class called Customer with fields FirstName and LastName. Suppose further I want to create a desktop GUI that allows the customer to edit that model in two separate windows in such a way that changes in one edit window are immediately reflected in the other, and I want clean separation of presentation and logic.
The example doesn't have to be in Swing, but it shouldn't require a server.
Thanks for any help you can give on this - and, if this isn't the right place to post this query, I'd appreciate a pointer to a more appropriate forum.

There are many ways but here is a simple example of how I do it.
******************************* CustomerModel.java
import java.beans.PropertyChangeSupport;
import java.beans.PropertyChangeListener;
public class CustomerModel
    /** Change Support Object */
    private PropertyChangeSupport propertyChangeSupport = new PropertyChangeSupport(this);
    /** bound property names */
    public static final String FIRST_NAME_CHANGED = "firstname";
    public static final String LAST_NAME_CHANGED = "lastname";
    /** First Name Element */
    private String firstName;
    /** Last Name Element */
    private String lastName;
    /** Blank Constructor */
    public CustomerModel()
        super();
     * Sets the first name element.  If value changed a notification is
     * sent to all listeners of this property
     * @param newFirstName String
    public void setFirstName(String newFirstName)
        String oldFirstName = this.firstName;
        this.firstName = newFirstName;
        propertyChangeSupport.firePropertyChange(FIRST_NAME_CHANGED, oldFirstName, newFirstName);
     * @return String
    public String getFristName()
        return firstName;
     * Sets the last name element.  If value changed a notification is
     * sent to all listeners of this property
     * @param newFirstName String
    public void setLastName(String newLastName)
        String oldLastName = this.lastName;
        this.lastName = newLastName;
        propertyChangeSupport.firePropertyChange(LAST_NAME_CHANGED, oldLastName, newLastName);
     * @return String
    public String getLastName()
        return lastName;
    /** Passthrough method for property change listener */
    public void addPropertyChangeListener(String str, PropertyChangeListener pcl)
        propertyChangeSupport.addPropertyChangeListener(str, pcl);       
    /** Passthrough method for property change listener */
    public void removePropertyChangeListener(String str, PropertyChangeListener pcl)
        propertyChangeSupport.removePropertyChangeListener(str, pcl);
}******************************* CustomerFrame.java
import javax.swing.*;
import java.awt.event.*;
import java.awt.GridLayout;
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeEvent;
public class CustomerFrame extends JFrame implements ActionListener, PropertyChangeListener
    /** Customer to view/control */
    private CustomerModel customer;
    private JLabel firstNameLabel = new JLabel("First Name: ");
    private JTextField firstNameEdit = new JTextField();
    private JLabel lastNameLabel = new JLabel("Last Name: ");
    private JTextField lastNameEdit = new JTextField();
    private JButton updateButton = new JButton("Update");
     * Constructor that takes a model
     * @param customer CustomerModel
    public CustomerFrame(CustomerModel customer)
       // setup this frame
       this.setName("Customer Editor");
       this.setTitle("Customer Editor");
       this.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
       this.getContentPane().setLayout(new GridLayout(3, 2));
       this.getContentPane().add(firstNameLabel);
       this.getContentPane().add(firstNameEdit);
       this.getContentPane().add(lastNameLabel);
       this.getContentPane().add(lastNameEdit);
       this.getContentPane().add(updateButton);
       // reference the customer locally
       this.customer = customer;
       // register change listeners
       this.customer.addPropertyChangeListener(CustomerModel.FIRST_NAME_CHANGED, this);
       this.customer.addPropertyChangeListener(CustomerModel.LAST_NAME_CHANGED, this);
       // setup the initial value with values from the model
       firstNameEdit.setText(customer.getFristName());
       lastNameEdit.setText(customer.getLastName());
       // cause the update button to do something
       updateButton.addActionListener(this);
       // now display everything
       this.pack();
       this.setVisible(true);
     * Update the model when update button is clicked
     * @param e ActionEvent
    public void actionPerformed(ActionEvent e)
        customer.setFirstName(firstNameEdit.getText());
        customer.setLastName(lastNameEdit.getText());
        System.out.println("Update Clicked " + e);
     * Update the view when the model has changed
     * @param evt PropertyChangeEvent
    public void propertyChange(PropertyChangeEvent evt)
        if (evt.getPropertyName().equals(CustomerModel.FIRST_NAME_CHANGED))
            firstNameEdit.setText((String)evt.getNewValue());
        else if (evt.getPropertyName().equals(CustomerModel.LAST_NAME_CHANGED))
            lastNameEdit.setText((String)evt.getNewValue());
}******************************* MainFrame.java
import javax.swing.JFrame;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JButton;
public class MainFrame extends JFrame implements ActionListener
    /** Single customer model to send to all spawned frames */
    private CustomerModel model = new CustomerModel();
    /** Button to click to spawn new frames */
    private JButton newEditorButton = new JButton("New Editor");
    /** Blank Constructor */
    public MainFrame() {
        super();
    /** Create and display the GUI */
    public void createAndDisplayGUI()
        this.setName("MVC Spawner");
        this.setTitle("MVC Spawner");
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.newEditorButton.addActionListener(this);
        this.getContentPane().add(newEditorButton);
        this.pack();
        this.setVisible(true);
    /** Do something when the button is clicked */
    public void actionPerformed(ActionEvent e)
        new CustomerFrame(model);
     * Creates the main frame to spawn customer edit frames from.
     * @param args String[] ignored
    public static void main(String[] args) {
        MainFrame mainframe = new MainFrame();
        mainframe.createAndDisplayGUI();
}

Similar Messages

  • Simple Java DB example

    I am using Java 1.6 and Eclipse Galelio on Vista, Do I need to configure anything is there any story of setting path?
    How to check my Java DB is working or not or everything is fine or not?
    I found many totorial with simple Java DB example but they seem dealing with previous version of JDK, I guess SUN too on http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javadb/ , kindly provide me the simplest example which uses Java DB.
    I am not able to figure out the whole thing of JAVA DB , how it works, in plain language I want to know is there any way of interacting with database from Command prompt? If so how?

    When I am running a simpleApp.java
    I am getting this error:
    Unable to load the JDBC driver org.apache.derby.jdbc.EmbeddedDriver
    Please check your CLASSPATH.
    java.lang.ClassNotFoundException: org.apache.derby.jdbc.EmbeddedDriver
         at java.net.URLClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at java.net.URLClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(Unknown Source)
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at SimpleApp.loadDriver(SimpleApp.java:414)
         at SimpleApp.go(SimpleApp.java:125)
         at SimpleApp.main(SimpleApp.java:93)
    ----- SQLException -----
    SQL State: 08001
    Error Code: 0
    Message: No suitable driver found for jdbc:derby:derbyDB;create=true
    SimpleApp starting in embedded mode
    SimpleApp finished

  • I am going to buy a Mac desktop and want to know how to transfer all my purchases and uploaded music from my PC. How can I do this to ensure all videos and music transfer over and not just purchases?

    I am going to buy a Mac desktop and want to know how to transfer all my purchases and uploaded music from my PC. I originally started using iTunes on my PC so it has everything I have ever purchased or uploaded from my own collection of music.
    How can I do this to ensure all videos and music transfer over and not just purchases? Do they do it at the Apple Store or at Best Buy? help!

    Move iTunes Library from PC to MAC
    http://www.macworld.com/article/146958/2010/03/move_itunes_windows_mac.html
    Also, See here if you need to...  iTunes to an External Drive
    http://support.apple.com/kb/HT1751

  • Error in Simple Input Form Example for CE 7.1?

    Hi @,
    I am trying to execute Simple Input form example in sdn for CE 7.1. But its not working as per the functionality.
    Can anyone suggest what is the issue ?
    Regards,

    hi,
    This particular example is given in the sdn and is for ce 7.1 but its not working .
    Regards

  • I have one folder on my desktop, i want to copy it on external hard drive so how can i do this?

    I have one folder on my desktop, i want to copy it on external hard drive so how can i do this?

    Welcome to Apple Support Communities
    Connect the external drive and open a Finder window pressing the Finder icon in Dock. Then, drag the folder to Finder, so it will be copied to this external disk.
    If you can't copy this folder, probably you have to format the external disk or use an app that allows you to write in that external drive. Mac OS X can't write in NTFS external disks

  • Simple XML DOM Example Needed.

    I need a simple XML DOM Example that reads in the XML and makes objects out of the elements. The tutorial from sun is very sketchy and seems to good far too quickly.
    Thanks,
    Dave.

    You can find some examples:
    http://java.sun.com/xml/jaxp/dist/1.0.1/examples/#building
    http://newinstance.com/writing/javaxml2/javaxml2_examples.html
    http://www.docuverse.com/domsdk/index.html#tutorial
    http://www.devx.com/sourcebank/search.asp

  • Im not very tech savvy. I use firefox on my desktop, and want to run on my new Asus netbook with Windows Starter. Will FF run faster then IE? What version of FF should I install?

    Im not very tech savvy. I use firefox on my desktop, and want to run on my new Asus netbook with Windows Starter. Will FF run faster then IE? What version of FF should I install? in English
    == This happened ==
    Not sure how often
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MAAU; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MAAU)

    Im not very tech savvy. I use firefox on my desktop, and want to run on my new Asus netbook with Windows Starter. Will FF run faster then IE? What version of FF should I install? in English
    == This happened ==
    Not sure how often
    == User Agent ==
    Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; MAAU; OfficeLiveConnector.1.3; OfficeLivePatch.0.0; MAAU)

  • Hi, I can not delete files Film / video from the desktop it wants my password I write but Ando I can not float to Trash

    Hi, I can not delete files Film / video from the desktop it wants my password I write but Ando I can not float to Trash

    This topic has a fix for that problem: Desktop to Trash Problem: "Finder wants...: Apple Support Communities
    OT

  • I have Lion 7 on my desktop, and want to put the same on laptop

    I have Mac Lion 7 on my desktop and want it on my currently 6.8 laptop so I can use stuff like mission control, do I have to purchase an upgrade, and if so why not just go to Mountain Lion on both?
    Help

    If both Macs qualify to upgarde to Mountain Lion you only need to purchase Mountain Lion one time. You can re download Mountain Lion on the laptop using the same Apple ID for free.
    See Step 1 here  >  Apple - Upgrade your Mac to OS X Mountain Lion.

  • Want a simple but complete example of JavaFX.

    Hey, I want a complete but very simple example written in JFX. If it is written in step-by-step way then it will be better. (Without NetBeans will be preferred). Thanx in advance. Any suggestion will be welcomed. New to JFX.

    println("Hello World!");or
    import javafx.stage.Stage;
    import javafx.scene.Scene;
    import javafx.scene.text.Text;
    import javafx.scene.text.Font;
    Stage {
        title: "My App"
        width: 250
        height: 80
        scene: Scene {
            content: Text {
                x: 10, y: 30
                font : Font { size : 24 }
                content: "Hello World!"
    }

  • So simple. I just want to put a link on my desktop. How do i do that, please

    Just want to put my favourite jazz radio station where i can get to it real quick. Can't figure out how to put a link right on my desktop.

    https://support.mozilla.com/en-US/kb/Creating+a+desktop+shortcut+to+a+web+page

  • Can anyone solve this simple MVC problem with ArrayCollection

    I have very simple application trying to understand how to apply MVC without any framework. There are quite a few exemples on the net but most do not deal with complex data.
    here is my application with 4 files: MVCtest.mxml, MyController.as, MyModel.as and MyComponent.as
    first the Model MyModel.as
    package model
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import mx.collections.ArrayCollection;
    [Event(name="ArrayColChanged", type="flash.events.Event")]
    [Bindable]
    public class MyModel extends EventDispatcher
      private static var instance:MyModel;
      public static const ARRAYCOL_CHANGED:String = "ArrayColChanged";
      private var _myArrayCol:ArrayCollection;
      public function MyModel(target:IEventDispatcher=null)
       super(target);
       instance = this;
      public static function getInstance():MyModel
       if(instance == null)
        instance = new MyModel();
       return instance;
      public function get myArrayCol():ArrayCollection
       return _myArrayCol;
      public function set myArrayCol(value:ArrayCollection):void
       _myArrayCol = new ArrayCollection(value.source);
       dispatchEvent(new Event(ARRAYCOL_CHANGED));
    then the controller: MyController.as
    package controller
    import components.MyComponent;
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.IEventDispatcher;
    import model.MyModel;
    import mx.collections.ArrayCollection;
    import mx.controls.Alert;
    import mx.rpc.events.FaultEvent;
    import mx.rpc.events.ResultEvent;
    import mx.rpc.remoting.RemoteObject;
    public class MyController extends EventDispatcher
      [Bindable]
      public var view:MVCtest;
      [Bindable]
      public var componentView:MyComponent;
      private var _model:MyModel = MyModel.getInstance();
      public function MyController(target:IEventDispatcher=null)
       super(target);
       _model.addEventListener("ArrayColChanged", onArrayColChange);
      public function initialise(event:Event):void
       getData();
      public function getData():void
       var dataRO:RemoteObject = new RemoteObject;
       dataRO.endpoint = "gateway.php";
       dataRO.source = "MytestdbService";
       dataRO.destination = "MytestdbService";
       dataRO.addEventListener(ResultEvent.RESULT, dataROResultHandler);
       dataRO.addEventListener(FaultEvent.FAULT, dataROFaultHandler);
       dataRO.getAllMytestdb();   
      public function dataROResultHandler(event:ResultEvent):void
       _model.myArrayCol = new ArrayCollection((event.result).source);
      public function dataROFaultHandler(event:FaultEvent):void
       Alert.show(event.fault.toString());
      public function onArrayColChange(event:Event):void
       componentView.myDataGrid.dataProvider = _model.myArrayCol;
    This is the main application: MVCtest.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Application xmlns:fx="http://ns.adobe.com/mxml/2009"
          xmlns:s="library://ns.adobe.com/flex/spark"
          xmlns:mx="library://ns.adobe.com/flex/mx"
          xmlns:controller="controller.*"
          xmlns:components="components.*"
          width="600" height="600"
          creationComplete="control.initialise(event)">
    <fx:Declarations>
      <controller:MyController id="control" view = "{this}"/>
    </fx:Declarations>
    <fx:Script>
      <![CDATA[
       import model.MyModel;
       import valueObjects.MyVOorDTO;
       [Bindable]
       private var _model:MyModel = MyModel.getInstance();
      ]]>
    </fx:Script>
    <s:VGroup paddingTop="10" paddingLeft="10" paddingRight="10" paddingBottom="10">
      <s:Label fontSize="20" fontWeight="bold" text="MVC Test with components"
         verticalAlign="middle"/>
      <components:MyComponent/>
    </s:VGroup>
    </s:Application>
    And this is the component: MyComponent.mxml
    <?xml version="1.0" encoding="utf-8"?>
    <s:Group xmlns:fx="http://ns.adobe.com/mxml/2009"
       xmlns:s="library://ns.adobe.com/flex/spark"
       xmlns:mx="library://ns.adobe.com/flex/mx" width="400" height="300">
    <s:layout>
      <s:VerticalLayout paddingBottom="10" paddingLeft="10" paddingRight="10" paddingTop="10"/>
    </s:layout>
    <fx:Declarations>
      <!-- Place non-visual elements (e.g., services, value objects) here -->
    </fx:Declarations>
    <s:Label fontSize="16" fontWeight="bold" text="My Component " verticalAlign="bottom"/>
    <s:DataGrid id="myDataGrid" width="100%" height="100%" requestedRowCount="4">
      <s:columns>
       <s:ArrayList>
        <s:GridColumn dataField="mystring" headerText="String"></s:GridColumn>
        <s:GridColumn dataField="myinteger" headerText="Integer"></s:GridColumn>
        <s:GridColumn dataField="myreal" headerText="Real"></s:GridColumn>
        <s:GridColumn dataField="mydate" headerText="Date"></s:GridColumn>
       </s:ArrayList>
      </s:columns>
    </s:DataGrid>
    </s:Group>
    Here is the code to generate the database:
    CREATE DATABASE mytest;
    CREATE TABLE myTestDB
          myid INT UNSIGNED NOT NULL AUTO_INCREMENT,
          mystring CHAR(15) NOT NULL,
          myinteger INT NOT NULL,
          myreal DECIMAL(6,2) NOT NULL,
          mydate DATE NOT NULL,
          PRIMARY KEY(myid)
    ) ENGINE = InnoDB;
    INSERT INTO myTestDB (mystring, myinteger, myreal, mydate) VALUES ('Test', 123, 45.67, '2012-01-01'), ('Practice', 890, 12.34, '2012-02-01'), ('Assay', 567, 78.90, '2011-10-01'), ('Trial', 111, 22.22, '2009-09-09'), ('Experiment', 333, 44.44, '1999-04-15'), ('Challenge', 555, 66.66, '2012-12-21');
    And finally here is the PHP script.
    <?php
    class myVOorDTO
      var $_explicitType = "valueObjects.myVOorDTO";
      public $myid;
      public $mystring;
      public $myinteger;
      public $myreal;
      public $mydate;
      public function __construct()
        $this->myid = 0;
        $this->mystring = "";
        $this->myinteger = 0;
        $this->myreal = 0.0;
        $this->mydate = date("c");
    class MytestdbService
      var $username = "yourusername";
      var $password = "yourpassword";
      var $server = "yourserver";
      var $port = "yourport";
      var $databasename = "mytest";
      var $tablename = "mytestdb";
      var $connection;
      public function __construct()
        $this->connection = mysqli_connect(
        $this->server, $this->username, $this->password, $this->databasename, $this->port);
    * Returns all the rows from the table.
    * @return myVOorDTO
      public function getAllMytestdb()
        $query = "SELECT * from $this->tablename";
        $result = mysqli_query($this->connection, $query);
        $results = array();
        while ($obj = mysqli_fetch_assoc($result))
          $row = new myVOorDTO();
          $row->myid = $obj['myid'] + 0;
          $row->mystring = $obj['mystring'];
          $row->myinteger = $obj['myinteger'] + 0;
          $row->myreal = $obj['myreal'] + 0.0;
          $row->mydate = new Datetime($obj['mydate']);
          array_push($results, $row);
        return $results;
    ?>
    My understanding as to what is going on is: (1) on creation complete the application launch the initialise() function of the controller (2) this function starts the remoteObject which get the data (3) once the results arrive the resultHandler store the data into the ArrayCollection of the model ***this does not work*** (4) even if part 3 did not work, the setter of the ArrayCollection in the model send an event that it has been changed (5) the controller receive this event and assigns the ArrayCollection of the model as the dataprovider for the datagrid in the compoent.
    Of course, since the ArrayCollection is null, the application gives an error as the dataProvider for the datagrid is null.
    What is missing in this application to make it work properly? I believe this is an example that could help a lot of people.
    Even if I change the setter in the model to _myArrayCol = ObjectUtil.copy(value) as ArrayCollection; it still does not work.
    Also, it seems that the remoteObject does not return a typed object (i.e. myVOorDTO) but rather generic objects. I am usually able to make this works but in this particular application I have not managed to do it. Again what's missing?
    Thanks for any help with this!

    Calendar c = GregorianCalendar.getInstance();
    c.set(Calendar.YEAR,2000);
    System.out.println(c.getActualMaximum(Calendar.WEEK_OF_YEAR));
    c.set(Calendar.YEAR,2001);
    System.out.println(c.getActualMaximum(Calendar.WEEK_OF_YEAR));But it says that 2000 has 53 weeks and 2001 has 52.

  • LR & SlideShowPro Examples Wanted

    I was looking at the SlideShowPro plugin for LR Web photo Galleries.  The site doesn't offer aceeptable examples of galleries made through LR.  Does anyone have a gallery built with this software, which I could look at?  Thanks - Steven
    BTW;  I like the Airtight viewers, but I may want something with more pizzazz.  I'm open to suggestions for other LR plugins as well.

    I really like the SSP plug-in and have used it a lot in recent weeks:
    http://www.stephenetnier.com/gallery.html
    (embedded in an HTML page: full use of fullscreen mode and popup images)
    http://www.thesameband.com/gallery.html
    (audio playback controlled in the slideshow)
    http://www.chronicjazz.com/photos.html
    (audio embedded in the html file after the fact)
    http://www.pilatesportland.com/
    (embedded in an HTML page: a simple slideshow with no controller or thumbnails, a bit down the page)

  • Simple bitmapdata animation example

    all this bitmapdata stuff blows my mind.
    I wonder if anyone has a really simple example I can look at to get to grips with it.
    I have 10 jellybeans that I want to gradually reduce in size. DOing this as a tween or actionscript results in poor performance on the iphone and iPad of course so I want to imporve this using the bitmapdata method,
    any help would be appreciated

    THANKS !!!
    Most Excellent !
    I downloaded the SDK and this is exactly what I was looking for...
    If you have time... would you take a look at my other posts... as I have a few customizations that I would like to implement.

  • Trouble with simple Query by Example

    Hey all, I am well aware that similar topics are all over the forums. I've exhausted myself fishing around for just the right thread.
    I am new to APEX. I have this book "Easy Oracle HTML-DB". It is somewhat helpful, but its examples are hard to follow - possibly because the product keeps moving along.
    I have a simple single table listing report. I wanted to add some selection criteria and was attempting to do so in a new region on the same page as outlined in this book. I added a few text fields and tied them into the query without issue. To submit the criteria, I added a "Go" button (just like the book says) and tied a "Reset Pagination" process to it.
    The book example doesn't specify button branching conditions. Without any though, clicking "Go" causes an error: "ERR-1777: Page XX provided no page to branch to." . So I added a branch back to the same page. Now it appears to be working, but it resets all my selection field values and runs the same report over again.
    I think a workaround is simply to put the criteria in a separate page altogether. I'm just about resigned to taking this approach. It sure looks like people do this all the time though. What did I miss ?
    Thanks in advance,
    Snake

    Rene said: "It's also nice to add : onKeyPress="checkEnter(event)"
    to the HTML Form Element Attributes of the items in the search region. This way you can also start the search by pressing Enter in the item."
    Hi Rene,
    I'd like to include the feature, but the action is no different with or without this attribute. When you press enter, it just stays there in the field.
    Nice to note though that most every behavior I've checked is the same whether using Firefox or IE. I like browser independence.
    Snake

Maybe you are looking for