Event-based Programming

Event loop

The basic structure of event based programs is shown below in pseudo-code.


        ...set up application data structures...

        ...set up GUI....

	// enter  event loop
	   Event e = get_event();
	   process_event(e);    // event dispatch routine

Notes on event handlers

Java 2 Event Model


Event Handlers

Event loops and Java

Handler Programming and Inner Classes

Final Word (almost)

We have covered the basic paradigm of the event-based programming and seen on overview of how Java implements it in it's WIndow system. While we have covered the essence, there are many more details about the Event subclasses and Listener interfaces for Keyboard, WindowEvents, etc. The book is a good start for more information. After that, the online doc and experimentation, as always.

In the next lecture we will talk out GUI components that provide higher-level functionality, such as buttons, scrollbars, etc. These are windows that internally process mouse and window events behind the curtains and issue other types of event to communicate with the larger application.


Appendex: COmplex text of FrameTest.java from class

import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.event.*;

 * Main class for game. Does window stuff and display

class MyFrame extends JFrame{

    public MyFrame(){
	setSize(200,200);        // size in pixels


class MyPanel extends JPanel{

    Color current = Color.red;

    // Handler for Mouse presses and clicks
    //  Extends MouseAdapator 
    //      (which implements MouseListener with empty methods)
    // We use an inner class so we can access to data on JPanel
    class MouseHandler extends MouseAdapter{
	// call on  mouse button down
	public void mousePressed(MouseEvent ev){
	    int x = ev.getX();
	    int y = ev.getY();
	    System.out.println("Pressed at " + x + "," + y);

	public void mouseClicked(MouseEvent ev){
	    int x = ev.getX();
	    int y = ev.getY();
	    System.out.println("Clicked at " + x + "," + y);
		current = Color.blue;
		current = Color.red;


	addMouseListener(new MouseHandler());

    public void paintComponent(Graphics g){

	//	    System.out.println("paintComponent");
	g.drawString("Hello World",50,50);


public class FrameTest{

    // OK let's have our main() create a frame.
    public static void main(String[] args){
	MyFrame myframe = new MyFrame();
	MyPanel mypanel = new MyPanel();
	// Random stuff we just have to do (the book explains, kind of)
	Container contentPane = myframe.getContentPane();
	// add panel