Personal tools
You are here: Home Classes Fall 2004 - Spring 2005 Old CS 160 GUI Design
Navigation
Log in


Forgot your password?
« May 2008 »
Su Mo Tu We Th Fr Sa
123
456789 10
11121314151617
18192021222324
25262728293031
 
Document Actions

GUI Design

by admin last modified 2005-05-25 15:40

GUI Design

Programs which use graphical user interfaces are event driven programs, in contrast to procedure-based programs.
  • Procedure-based programming:  Control resides with the running program.  I/O occurs at the request of the running program.
  • Event-driven programming:  Control resides with the interactive user.  The program responds to spontaneous I/O events.
Events are based on interaction between a user (through the mouse and keyboard or other devices) and graphical components (buttons, text fields, etc.)

Programmer's responsibilities:
  • Defining GUI components.
  • Arranging the components in a window or frame.
  • Connecting components to program actions.


Packages

  • java.awt
    • Abstract Windowing Toolkit
    • Original GUI package
    • "heavyweight" components
  • javax.swing  Updated GUI package
    • "lightweight" components
    • uses awt event model
  • java.awt.event
    • event-handling classes

Components

Swing components can be classified as top-level, intermediate-level, and low-level.

Top-level components

  • JFrame  the topmost window of an application
  • JApplet  Applets are created by extending JApplet.
  • JDialog  A popup window or message box used as a temporary I/O window

Middle-level components

  • JPanel
    • A blank area in a window
    • Acts as both a component and a container
    • Used to create the containment hierarchy of an application or applet

Low-level (atomic) components

  • JLabel
  • JTextArea
  • JButton
  • JRadioButton
  • JCheckBox
  • JList
  • JMenu
  • JComboBox
  • JScrollBar
  • JScrollPane
Go to http://java.sun.com/docs/books/tutorial/uiswing/components/components.html for an overview (with pictures) of the low-level Swing components.

example  A minimal GUI application can be constructed by creating a frame and making it visible:

import javax.swing.*;

class GUITest {

    JFrame frame = new JFrame("GUI Test");

    GUITest(){
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(500,300);
        frame.setVisible(true);
    }

    static public void main(String[] args){
        new GUITest();
    }

}


Constructing a GUI

To construct a GUI, the programmer must create a group of components and arrange them in a containment hierarchy.  Every component (except the top-level components) must be placed in some java.awt.Container.

Each of the top-level components possesses a container called its content pane.  Every component in the top-level component must be placed in its content pane, or in some container nested within its content pane.  The root of the containment hierarchy is the content pane of a JFrame or JApplet.

For each component,
  • Instantiate the component.
  • Customize it by setting properties, such as background color, font, minimum size, etc.
  • Add it to a container.
For each container,
  • Instantiate the container.
  • Customize it by setting properties.
  • Choose its layout manager (or else use the default layout manager).
  • Add it to a container.

Layout Managers

Each Container has a layout manager, whose job it is to arrange the components visually within the container.
  • The user does not specify exact pixel locations for components.
  • Instead, the user selects a LayoutManager which follows general guidelines for placing components.
  • Hints may be given to the LayoutManager, such as a preferred size for a component, but the LayoutManager need not obey them.
  • When a component is added to a container, the user may specify a constraint object which may be used by the LayoutManager.  For example, BorderLayout recognizes the constraints BorderLayout.NORTH, BorderLayout.SOUTH, BorderLayout.CENTER, BorderLayout.WEST, and BorderLayout.EAST.
The idea is to free the user from low-level details of component placement, which may be difficult to get exactly right or to modify.  This makes the GUI more adaptable to different platforms, screen sizes, etc.

The user still has a great deal of control by
  • structuring the containment hierarchy
  • choosing the layout manager of each container
  • specifying component attributes
  • passing constraints to the layout manager
Layout managers supplied by Swing:
  • FlowLayout
    • Most basic layout manager
    • Components placed left to right in order added
    • When edge of container reached, continues on next line
    • Components can be left-aligned, centered (default), or right-aligned
  • BorderLayout
    • Default manager for content pane
    • Arrange components into 5 regions
    • North, south, east, west, center
    • Up to 5 components can be added directly, one for each region
    • Components placed in
      • North/South - Region is as tall as component
      • East/West - Region is as wide as component
      • Center - Region expands to take all remaining space
  • GridLayout
    • Divides container into a rectangular grid
    • Components placed in rows and columns
    • All components have same width and height
    • Added starting from top left, then from left to right
    • When row full, continues on next row, left to right
  • CardLayout
  • BoxLayout
  • GridBagLayout
Go to http://java.sun.com/docs/books/tutorial/uiswing/layout/visual.html for an overview (with pictures) of the Swing layout managers.

Event Handling

Events in a GUI are actions such as a timer ticking or a user typing a character, moving a mouse, or pushing a mouse button.  GUI programs are designed to operate in response to events.

Java AWT event handling is based on the principle of delegation.  Responsibility for handling events for a particular GUI component is delegated to an event handler ("listener") object.  The listener is responsible for responding to events which are associated with that component.  This model is an example of the Observer-Observable design pattern.

To write code for a particular event, say a user entering a word in a text field, the user must
  • Write code for an event handler class.  The event handler class will contain methods to respond to one or more events.
  • Create an instance of the class.
  • Register the listener object with the component.
This can be done in a single statement by making use of an anonymous class.

example  Create a text field and give it an action listener.  (The code to add the name field to a container is not given here.)

JTextField nameField = new JTextField();
String name;

nameField.addActionListener(
    new ActionListener(){
        public void actionPerformed(ActionEvent e){
            name = nameField.getText();
        }
    }
);



All events are subclasses of java.awt.AWTEvent.  All listeners are subinterfaces of java.util.EventListener.  Here is a summary of events and listeners used in GUI programs:

Event Class
Listener Interface
Listener Methods
ActionEvent
ActionListener
actionPerformed
WindowEvent
WindowListener
windowClosing
windowOpened
windowIconified
windowDeiconified
windowClosed
windowActivated
windowDeactivated
ContainerEvent
ContainerListener
componentAdded
componentRemoved
ComponentEvent
ComponentListener
componentMoved
componentHidden
componentResized
componentShown
FocusEvent
FocusListener
focusGained
focusLost
TextEvent
TextListener
textValueChanged
KeyEvent
KeyListener
keyPressed
keyReleased
keyTyped
MouseEvent
MouseListener
mousePressed
mouseReleased
mouseEntered
mouseExited
mouseClicked
MouseMotionListener
mouseDragged
mouseMoved

Painting

You can draw a picture on any JComponent.  To do so, override the component's paintComponent method, adding your own calls to drawing methods.  Here's an example:


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

class GraphicsTest {

  class MyPanel extends JPanel {
    public void paintComponent(Graphics g){
      super.paintComponent(g);
      GraphicsTest.this.drawOnPanel(g);
    }
  }

  JFrame frame = new JFrame("GUI Test");
  JPanel panel = new MyPanel();

  GraphicsTest(){
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(500,300);
      Container c = frame.getContentPane();
      c.add(panel);
      frame.setVisible(true);
  }

  void drawOnPanel(Graphics g){
      g.drawOval(10, 20, 30, 40);
  }

  static public void main(String[] args){
      new GraphicsTest();
  }

}






 

Powered by Plone CMS, the Open Source Content Management System

This site conforms to the following standards: