You are on page 1of 2

Java Events and the MVC Architecture

There was a major change in Java 1.0 and 1.1 regarding event
handling. To understand the use of events with their corresponding
listeners there are a number of sources. Java in a Nutshell, 2nd edition
addresses the issue on pages 150- 157. Core Java, Volume 1 has Event
Handling in Chapter 8 which uses this Delegation Event Model.
It is a good design tool to be familiar with the MVC pattern

• model (the application code)


• view (the GUI code)
• controller (the interface between the GUI and the application software)

which is the abstraction of this methodology. When using advanced Java tools one can
use this idea extensively.
Following is some sample code that uses the model: This is taken from
the Java AWT: Delegation Event Model page at java.sun.com
The main focus is to see

• how an application and its user-interface are as disjoint as possible.


• the only thing in the main method is instantiation.
• A GUI (with the application passed) does the following:
o instantiates its Frame (if an application)
o sets its Layout Manager
o instantiates its Interface(s)
o instantiates and adds various components (buttons, etc)
 adds Listener(s) (to appropriate Interface(s))

import java.awt.*;
import java.awt.event.*;

public class App {


public void search() {
/* do search operation ...*/
System.out.println("Searching...");
}
public void sort() {
/* do sort operation ...*/
System.out.println("Sorting....");
}

static public void main(String args[]) {


App app = new App();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener {
static final int SEARCH = 0;
static final int SORT = 1;
int id;
App app;

public Command(int id, App app) {


this.id = id;
this.app = app;
}

public void actionPerformed(ActionEvent e) {


switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break; }
}
}
class GUI {

public GUI(App app) {


Frame f = new Frame();
f.setLayout(new FlowLayout());

Command searchCmd = new Command(Command.SEARCH, app);


Command sortCmd = new Command(Command.SORT, app);

Button b;
f.add(b = new Button("Search"));
b.addActionListener(searchCmd);
f.add(b = new Button("Sort"));
b.addActionListener(sortCmd);

List l;
f.add(l = new List());
l.add("Alphabetical");
l.add("Chronological");
l.addActionListener(sortCmd);
f.pack();

f.show();
}
}

You might also like