Title: Creating Graphical User Interfaces GUIs in Java
1Creating Graphical User Interfaces (GUIs) in Java
- CSE301
- University of Sunderland
- Harry R Erwin, PhD
2Graphical User Interfaces
- Are based on a real-world (typically desktop)
metaphor. - Apples user interface guidelines are a good
starting point for understanding the semantics. - Programming a GUI is very strange and wonderful
and often difficult. - We will learn how to do this in Java.
3Smalltalk History(Goldberg and Robson)
- Xerox PARC during the 1970s was exploring how
computing power would be used in business. (Xerox
sells products for the office environment.) - They concentrated on two research areas
- A programming language to serve as an interface
between models in the mind and those in computing
hardware. - A user interface to match the human communication
system to that of the computer. - This resulted in the Smalltalk system.
4The Smalltalk Approach
- Smalltalk was a graphical, interactive
programming environment. - Smalltalk was a big system, built on a model of
communicating objects. - Smalltalks primary vocabulary was
- object,
- message,
- class,
- instance, and
- method. (Sounds familiar?)
5The Desktop Metaphor
- Xerox invented the desktop metaphor for
SmallTalk - The display screen contains one or more
rectangular areas called views. - Views may overlap.
- Each view has a title.
- The mouse has three buttons
- Leftselect.
- Middleaction menu popup.
- Rightview menu popup.
6Apples Guidelines (Apple 2002)
- Apple made the desktop metaphor more explicit
- File folders
- Documents
- Wastebasket
- Operations based on see and point
- The user selects an object on the screen, and
- Then applies a verb to it.
- Direct manipulation
- Objects remain visible
- Effects of actions are immediately visible.
7Apple Guidelines (II)
- User control
- The user, not the computer, initiates and
controls actions. - Feedback and communication
- Keep users informed about whats happening
- Progress indicators
- Immediate direct feedback
- Consistency
- Avoid forcing the user to retrain to use your
application. Take advantage of their task
knowledge.
8Apple Guidelines (III)
- What you see is what you get (WYSIWYG)
- No significant differences between what is seen
on the screen and what is printed by the printer.
Applies to all data. - All commands should be easily found.
- Forgiveness
- Make most actions easily reversible.
- Perceived stability
- Be consistent.
- Aesthetic integrity
- Make your displays pleasant to view over time.
9Apple Guidelines (IV)
- Modelessness
- Let the user do what she wants most of the time.
- Knowledge of your audience
- Understand the user and the users expectations.
- Worldwide compatibility
- Cultural values
- Language differences
- Text display/editing
- Accessibility for persons with disabilities
10Then Why is Programming a GUI so Hard?
- In doing this, Apple decided that ease of use was
more important than ease of programming. - The GUI programming model was very different from
most programmers previous experience in the
1980s. - Very similar approaches (and implementations) are
also present in most later systems - X11
- Windows
- Java
- As a result, GUI programming is not easy in any
of these systems.
11General Approach
- All applications have an event-handling loop that
receives asynchronous events from the GUI and
services them. - Events may trigger other events to be serviced.
- Display is asynchronous with event handling, but
event servicing may change the display. - Organizing this system to support multiple views
or windows and both high and low-level events
leads to a number of design approaches. We will
study how Java does it.
12Java GUI Frameworks
- Abstract Window Toolkit (java.awt)
- The original set of windowing components designed
for Java. These were implemented as separate
processes using the GUI features of the
underlying operating system. - Swing (or Java Foundation Classesjavax.swing)
- A second generation set of light-weight
windowing components introduced in Java 1.2.
These were implemented as Java threads and so
avoided the overhead of process context switches
and enforced a common look and feel. - SWT (part of Eclipse)
- Discussed at http//java.sun.com/docs/books/tutor
ial/uiswing/index.html
13AWT
- The foundation of GUI in Java
- Implemented in separate processes
- Rudimentary
- Supported by most web browsers, so that most
applets should use AWT instead of Swing.
14AWT Features
- Basic facilities for creating a graphical user
interface - Drawing graphics (not covered in this module)
15Using AWT
- Import
- java.awt.
- java.awt.event.
- Everything inherits from java.awt.Component
- The AWT GUI is organized by containers,
inheriting from java.awt.Container (which
inherits from Component). - The arrangement of controls is managed by various
layout managers. - Notification of changes is handled by events and
event listeners that run in a GUI thread.
16Swing
- Built on AWT
- Written in pure Java
- Uses less classes and is faster
- Common look and feel
- Designed to explicitly support the
Model-View-Controller pattern (future lecture). - Supports handicapped accessibility.
- Not supported by all web browsers 8(
17To Use Swing
- You must import the following
- java.awt.
- java.awt.event.
- javax.swing.
- javax.swing.event.
- javax.swing.border.
- javax.swing.text.
- These are stored in
- swing.jar
- swingall.jar
- windows.jar
- Point to these using your CLASSPATH.
18Creating the Graphical User Interface
- This is a four-step process (see Flanagan, Java
Foundation Classes in a Nutshell) - Create and configure the components. This uses
the standard Java syntax for reference types. - Add the components to a container. Containers
are subclasses of java.awt.Container. - Arrange or lay out the components. Do it
yourself, or use a LayoutManager. - Handle the events generated by the components.
You add event listeners to do this. - We will explore this.
19Creating the Components
- These are the building blocks of your interface.
- Flanagans Java Foundation Classes in a Nutshell
is a good reference. Study it to understand what
components are available to you and how to use
them. Remember the role inheritance plays in
this. - The names of Components often tell you exactly
what they do. - Every component has properties that can be used
to configure it. The JavaBeans specification
formalizes this.
20AWT Component List
- Button
- Canvas
- Checkbox
- CheckboxMenuItem
- Choice
- Component
- FileDialog
- Label
- List
- Menu
- MenuBar
- MenuComponent
- MenuItem
- PopupMenu
- Scrollbar
- TextArea
- TextComponent
- TextField
21Swing Component List
- JAWT-name for most AWT components
- JColorChooser
- JComboBox
- JEditorPane
- JFileChooser
- JOptionPane
- JPasswordField
- JProgressBar
- JRadioButton
- JRadioButtonMenuItem
- JSeparator
- JSlider
- JTable
- JTextPane
- JToggleButton
- JToolBar
- JToolTip
- JTree
22How to Add Components to a Container
- See Flanagan (Java Foundation Classes in a
Nutshell) for the details. - Most Container classes are specialized. You will
most frequently use - Applet (or JApplet)
- JFrame
- JDialog
- JDesktopPane (with JInternalFrame)
- JPanel
- You use the add() method to add Components to a
Container. Since Containers are also Components,
you can create a hierarchy of Containers, all
displayed within a JFrame, JDesktopPane, or
JApplet.
23AWT Containers
- Applet
- Container
- Dialog
- Frame
- Panel
- ScrollPane
- Window
24Swing Containers
- JAWT-name for AWT containers
- Box
- JDesktopPane
- JInternalFrame
- JLayeredPane
- JRootPane
- JSplitPane
- JTabbedPane
- JViewport
25Laying out the Components
- You can design your own layout or use one of the
LayoutManagers that Java provides. - LayoutManager classes include
- BorderLayout
- CardLayout
- FlowLayout
- GridBagLayout
- GridLayout
- BoxLayout (nice)
- OverlayLayout
- ScrollPaneLayout
- ViewPortLayout
26Event Handling
- The part of the project many students dont get
around to doing. To do anything, you have to
handle events. - java.awt and javax.swing use the event-handling
API defined by the JavaBeans component model.
This is based on events and event listeners. - events extend java.util.EventObject.
- event listeners extend java.util.EventListener.
- Applets may have to use an older API for browser
compatibility. 8(
27Warnings
- java.awt.event and javax.swing.event mostly
define interfaces and event adapters. Event
adapters are empty classes implementing specific
interfaces that you can subclass very easily for
your specific needs. - You must define your own implementations, since
this is the code that modifies your model. - Events are dispatched by an automatically created
thread called the event dispatch thread. You must
synchronize with it if other threads modify your
model. (See Lecture 20.)
28Event Listeners
- The object notified of an event is an event
listener. - An event listener can handle several types of
events, and more than one event listener can
monitor a specific event. - One of the most important things to know about a
Component is what events it can generate, so read
the documentation. - Event listeners can register themselves with
multiple components and can have other functions,
as well. - Event listener interfaces with more than one
method generally have associated event adapters
that you can use.
29Component Events
- Low-level events reflect things like keypresses
and mouse clicks. Avoid handling these unless you
must. - Individual Components can handle low-level events
for you. For example a JButton handles mouse
clicks and releases. Take advantage of this. - Components generate higher-level ActionEvents for
you to handlee.g., button pushes. Sometimes,
these events can also be handled for you. Your
GUI initialization code needs to tell the system
what events you want it to handle transparently
in this way. - See Chapter 10 of Java Examples in a Nutshell.
30Using Inner Classes in your GUI
- To handle an event, you must implement the
corresponding event listener. 8( - It is quite common to create special classes to
handle these events. 8( - Inner classes were invented to simplify this. 8)
- An inner class can implement an event listener
interface or extend an event adapter class. 8) - See Chapter 2 of Flanagan, Java Foundation
Classes in a Nutshell for lots of examples. 8))
31Example
import java.awt.BorderLayout import
java.awt.Container import java.awt.HeadlessExcept
ion import java.awt.event.WindowAdapter import
java.awt.event.WindowEvent import
java.util.Observable import java.util.Observer i
mport javax.swing.JFrame public class
NavalCRTGUI extends JFrame implements Observer
/ _at_throws java.awt.HeadlessException
/ public NavalCRTGUI() throws HeadlessException
super("ASW Results Analyzer") final
NavalCRTGUI theGUI this // Handle window
close requests (inner class) this.addWindowListe
ner( new WindowAdapter() public void
windowClosing(WindowEvent e)
System.exit(0) )
32Example (II)
// All content of a JFrame (except for the
menubar) goes in the // Frame's internal
"content pane", not in the frame itself. // The
same is true for JDialog and similar top-level
containers. Container contentPane
this.getContentPane() contentPane.setLayout(new
BorderLayout()) / (non-Javadoc)
_at_see java.util.Observerupdate(java.util.Observabl
e, java.lang.Object) / public void
update(Observable o, Object arg) // focus
events will be used to update // the ASW state
of the system // changes to the outputs will be
reported as observables public static void
main(String args) NavalCRTGUI display new
NavalCRTGUI() display.setSize(1000,
800) display.setVisible(true)
33Adding Content andSetting Up the Observer
Box thePanel Box.createVerticalBox() // set
up situation pane thePanel.add(new JLabel("The
Situation")) Box theSituationPanel
createSituationPanel() // creates a typical
component thePanel.add(theSituationPanel) ((O
bservable)theBattle).addObserver((Observer)this)
// this is the JFrame being built. update(theBat
tle,null) // the JFrame is an Observer and has
an update // method. This // will result in the
GUI being initialized // from the domain class.
That is good.
34Typical Component Constructor
private JTextField createAShip() final
JTextField bFactors new JTextField() // gets
preserved bFactors.setText(String.valueOf(theBatt
le.getABomber(3).getFactors())) FocusAdapter
bFactorsAdapter new FocusAdapter() // inner
class public void focusLost(java.awt.event.Focus
Event event) String s bFactors.getText()
try int f Integer.parseInt(s) if
(f lt 0) f 0 else if (f gt 99) f
99 theBattle.getABomber(3).setFactors(f)//
the model bFactors.setText(String.valueOf(f))
catch (NumberFormatException e)
bFactors.setText("0") theBattle.getABom
ber(3).setFactors(0)// the model theBattl
e.recompute()// telling the model to
recompute // end of inner class
definition bFactors.addFocusListener(bFactorsAdap
ter)// event handler return bFactors
35Summary
- First create and configure your components.
Create methods keep this clean. - Add the components to containers. Remember,
containers are also components, so you can nest
them. - Arrange or lay out the components. Do it
yourself, or use a LayoutManager. Box layout is
easy to use. - Handle the events generated by the components.
You must create event listeners to do this. These
should usually be built using inner classes. (I
usually do this in the Create methods.) These are
the important hidden parts of the GUI that affect
the rest of the system.