fuin.org
Small Open Source Java Tools and Libraries
Simple MVC example
This example shows you how to prevent UI methods from being called outside the Swing EDT (Event Dispatching Thread) and also how to decouple the controller from the view without using a SwingWorker
View source:
package org.fuin.jaddr; import javax.swing.JPanel; import javax.swing.JTextField; import org.fuin.aspects4swing.InvokeAndWait; public class MyView extends JPanel { private MyController ctrl; // ... @InvokeAndWait public void setAddress(final Address address) { // If the calling code isn't already running inside the EDT (Event // Dispatching Thread) the thread will be switched using // "SwingUtilities.invokeAndWait(..)" before calling this method. // ... Set data in UI controls ... } private void buttonLoadPressed() { final String idStr = getTextFieldId().getText(); final Integer id = Integer.parseInt(idStr); ctrl.loadAddress(id); } }Controller source:
package org.fuin.jaddr; import org.fuin.aspects4swing.StartNewThread; public class MyController { private MyView view; private Address address; // ... @StartNewThread public void loadAddress(final Integer id) { // A new thread will always be started before calling this method // Load address from database // ... // Set data in view view.setAddress(address); } }
Usage with Maven (Configuration)
Maven Dependency:<dependency> <groupId>org.fuin</groupId> <artifactId>aspects4swing</artifactId> <version>0.1.3</version> </dependency>AspectJ Maven Plugin:
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.1</version> <executions> <execution> <goals> <goal>compile</goal> <goal>test-compile</goal> </goals> </execution> </executions> <configuration> <source>1.5</source> <target>1.5</target> <aspectLibraries> <aspectLibrary> <groupId>org.fuin</groupId> <artifactId>aspects4swing</artifactId> </aspectLibrary> </aspectLibraries> </configuration> </plugin>