GUI and Event-driven Programming in Java

By Bradley Simmons,2014-04-24 11:50
8 views 0
GUI and Event-driven Programming in Java

GUI and Event-driven Programming in Java

    We illustrate basic GUI design and event-driven programming in Java through an

    escalating series of examples. The key examples are:

Class-1: & system environment to compile/run the programs in TextPad

    or dos prompt.

Class-2: TestPanelExample & panelExample3 done from scratch [as class &

    class] through: event handling, incrementally developed/compiled, separate

    main driver class, imports needed for various methods & objects, frame extension, event

    interface [registration of GUI objects as event generators, event handler, import class,

    event interface].

Class-3: Compare the development of a calculator in Java versus its development in

    Html + JavaScript. Compare the graphical interface specification in Java versus how it is

    done in Html. Compare the event handling in Java versus how it is done using Javscript

    working with Html elements. Compare how data conversion is done in Java versus

    Javascript. Develop incrementally from scratch as class X & TestX for Java; as X.html

    for Html & Javascript.

    Class-1 Designing and running simple Java graphics programs.

In-class Lab Frames - Make a Java program that creates a window and controls

    its size & visibility.

    See under Java-examples link. It defines a blueprint for a Java object - a so-called class - called MyFrame, which has a main program that creates an instance of a frame (window) object. To compile and execute the program, save it as

    MyFrame [ actually ] where the class name matches the file name.

    Compile and execute the file using the TextPad Tools menu, or the shortcuts Ctrl+1

    [compile] & Ctrl+2 [run application]. A Dos command prompt appears. The window

    has been already created by the Java program, but an input request MyInput.readString()

    blocks execution of a statement making the window visible, until you enter a string and

     in the dos prompt.

    Program Structure save program in file

    import …

    public class Mine


     public static void main (String[ ] args) { JFrame f = new JFrame ("…") ; … }


    Syntax summary:

    import imports Java classes used in the program

    public class Mine { } encompassing class - saved in file of same name

    public static void main(String[ ] args)

     signature for main program

    JFrame ("…") constructor for frame object

    f.setSize (x, y) JFrame method sets width & height of frame

    f.setVisible (boolean) JFrame method sets frame's visibility

    MyInput.readString( ) waits/reads string from dos prompt

In-class Lab Frames - Monitor window's dynamic properties.

    See which shows how frame properties can be dynamically

    altered. The frame dimensions are returned by getSize method in a Dimension object.

    An input statement stalls execution. At the first stall, use the mouse to resize frame, then

    enter in dos prompt to un-block the stall and note the new dimensions displayed.

    Similarly for the next effect which flips frame from invisible to visible.

    Two import statements are required to use JFrame and Dimension objects. The

    MyInput class 'static' method readString ( ) does not require an import statement because its defining class is in the current directory such classes are automatically available.

    Syntax summary:

    f.getSize() JFrame method returns Dimension object for window

    Dimension d Dimension object containing height & width

In-class Lab ContentPanes - Add buttons and other GUI components to frames.

    See program. This adds GUI components

    specifically button objects to the frame. The frame consists of a title bar at the window

    top and a so-called ContentPane below that into which the buttons are placed or added. To get the pane use the f.getContentPane( ) method. If you try to add components

    directly to the frame, rather than to the ContentPane, a run-time error occurs with an error

    message indicating the need for the ContentPane. Nor is the ContentPane itself quite

    satisfactory as a display case because objects added to the pane latter overlay objects

    added earlier.

    Syntax summary:

     f.getContentPane() returns pane where GUI components are placed

     add(X) JFrame method that puts object X in frame's pane

    JButton ("…") JButton constructor with label parameter

In-class Lab Define a layout structure for objects added to a pane.

Objects added to a pane overlap unless a layout organization is defined for the pane. See program. To establish a Layout for a ContentPane it


     f.getContentPane( ).setLayout (new BorderLayout ( ) )

This lets objects be placed east, west, north, south, or center in a pane. The following

    adds a button to the center of a pane:

     add (new JButton("OK"), BorderLayout.CENTER )

Alternatives like grid layouts arrange objects in a checkerboard pattern.

    Syntax summary:

     setLayout(new BorderLayout ( ) ) pane method to define NSEW Layout

    add(X, BorderLayout.CENTER ) pane method to put X in center of layout

    In-class Lab Extend JFrame to a new class one which contains a so-called

    panel with embedded textfields.


     title bar

    content pane

     panel text field

    See the program. The outer class panelExample extends the

    concept of a JFrame and 'inherits' all its methods. A constructor panelExample ( ) defines the blueprint for objects of the class. A main program executes the class constructor to create a new instance of the object. This is a canonical example of how to

    extend an existing class like JFrame. The program structure (with name changed to Mine)


    public class Mine extends JFrame


     private JTextField Num1, Num2;

     public Mine ( ) { JPanel p1 = new JPanel ( ) ; … }

     public static void main(String[ ] args)

     { Mine f = new Mine ( );

     f.setTitle("f"); f.pack(); f.setVisible(true);



    The constructor Mine( ) for the new Mine class adds a Java panel object to a

    frame's pane, then adds fields to the panel - which provides a default layout for objects so

    they do not overlap. The added textfield objects are made global so they can be referred to anywhere in the class but private so they are inaccessible outside the class.

    The variation shows how the main program can create multiple instances of this new class. TextFieldDemo4b is another variation which adds

    an additional button object to the panel and colors the panel's background red.

    Program Structure:

    public class Mine extends JFrame

    { private type a, b;

     public Mine ( ) { }

     public static void main(String[ ] args) { Mine f = new Mine ( ) ; … }


    Syntax summary:

    class Mine extends JFrame Mine expands JFrame's methods & properties

    public Mine ( ) {… } constructor for class Mine

    JPanel ( ) panel constructor

    JTextField (length) textField constructor

    private JTextField tF private declaration

    add (tF) adds tF to panel with default flowLayout

    f.pack( ) shrink-wraps f to enclose embedded objects

    An alternative program organization (see TestPanelExample & the associated

    class which has to be saved as is to define the

    extended class in a separate file - without a main program. A separate main class

    (TestPanelExample) is then used to create instances of the new object just like created a JFrame object.

In-class Lab Make a program that recognizes & handles different events on

    objects that have been registered as event-listeners - including data

    access & conversion for the objects.

    See to see how to sensitize GUI objects like buttons and fields to events like mouse-clicks and carriage-returns. Objects are 'sensitized' to events

    by being registered as ActionListeners. An event-handler method - actionPerformed

whose invocation signature is pre-defined, but whose contents are determined by the

    programmer, recognizes the event source & specifies the response to the event.

    The event-handling is done as follows. When the source of the event is

    recognized as a button-click on 'Simon', the handler gets the text from the Num textfield,

    prepends the phrase "Simon says" to its contents, and stores the modified phrase back in

    the textfield. When the source of the event is recognized as a in the Num textfield,

    the handler gets text from the field, converts it to floating point form, takes the square

    root, converts the result to a string again, then stores that string back in the text field.

    Notice how in an event-driven framework, an event on a sensitized object triggers

    event processing. The key programming concepts are registering graphic objects as

    listeners for events - which events this corresponds to depends on the object - and

    defining an event-handling method which distinguishes between different event sources

    and adapts its response accordingly.

    Program Structure:

    public class Mine extends JFrame

    { private type x, y ;

     public Mine ( ) {… x.addActionListener (this) …}

     public void actionPerformed(ActionEvent e) { if (e.getSource() == x ) { … } }

     public static void main(String[ ] args) { Mine f = new Mine ( ) … }


    Syntax summary:

    register object Num.addActionListener (this);

     event-handler signature public void actionPerformed (ActionEvent e){…}

    recognize event source if (e.getSource() == Num )

    data conversions Num.setText ( String.valueOf(

     Math.sqrt(Double.parseDouble(Num.getText( ))) ));

In-class Lab

     Modify TextFieldDemo3c2b to be a calculator. The calculator should three fields

    and two buttons: two fields for operand input, a third for the result of the calculation, one

    button for addition, one for multiplication.

Technical notes:

To run in dos:

1. Change directory to where program is located such as:

     cd C:\MyStuff\AA-IT202\IT202\A-Java

    2. To compile:


    3. To run the program:

     java TextField

    4. If the current directory is not in the environment's classpath use:

     javac classpath .


     java classpath . TextFieldDemo

    5. To include the current directory in the classpath if not already there update environment variable with:


    which concatenated the existing classpath with the current directory (denoted by ".").

To run in Textpad:

    1. If the compile/run options do not appear in the Tools menu, then go to Configure>Preferences>Tools>Add and add the jdk.

    2. If the MyInput file in the same [current] directory as the main class being compile is not recognized/found by the compiler, then the current directory may not be in the so-called 'classpath' one of the system environment variables. Refer to items 4/5 above.

Report this document

For any questions or suggestions please email