Programming Languages
Lecture 9
Graphical User Interface
R. Pełka – Wojskowa Akademia Techniczna
R. Pełka: Programming Languages
2
Guido van Rossum
Designer of Python
Dutch computer programmer, now at Google
Some facts
Development began in 1996
Interpreted scripting language descended
from ABC
Predecessor, ABC, was inspired by SETL
Lambert Meertens spent year with SETL group
at NYU
Popular and successful, influential at Google
About the origin of Python, Van Rossum wrote in 1996: Over six years ago, in December
1989, I was looking for a "hobby" programming project that would keep me occupied
during the week around Christmas. My office … would be closed, but I had a home
computer, and not much else on my hands. I decided to write an interpreter for the new
scripting language I had been thinking about lately: a descendant of ABC that would appeal
to Unix/C hackers. I chose Python as a working title for the project, being in a slightly
irreverent mood and a big fan of Monty Python's Flying Circus
R. Pełka: Programming Languages
3
Outline
Graphical User Interface
Idea and properties
Containers
Components
Events
Tools for GUI design
AWT – Application Windowing Toolkit
Swing – new Java GUI classes
SWT (Standard Widget Toolkit - Eclipse)
Simple GUI design
R. Pełka: Programming Languages
4
GUI Principles
GUI
– Graphical User Interface
GUI’s are a good target for OO design
GUI’s main elements
Components
: GUI building blocks.
buttons, menus, sliders, etc.
Layout
: arranging components to
form a usable GUI.
using layout managers.
Events
: reacting to user input.
button presses, menu selections, etc.
There are some tools for convenient GUI-based design
JBuilder, Eclipse, NetBeans
R. Pełka: Programming Languages
5
Java GUI classes
AWT
(Abstract Window Toolkit) (java.awt.*)
old GUI framework for Java (Java 1.1)
some reliance on native code counterparts
platform independence problems
Swing
(javax.swing.*)
new GUI framework first introduced in Java 1.2
includes AWT features plus many enhancements
pure Java components (no reliance on native code)
pluggable look and feel architecture
SWT
(Standard Widget Toolkit; from Eclipse)
R. Pełka: Programming Languages
6
AWT and Swing
AWT
was the original platform-dependent
layer of Java to build GUI’s.
Swing
(platform independent layer) was
added later. Swing is part of JFC (
Java
Framework Collection
).
R. Pełka: Programming Languages
7
Event-driven programming
GUIs are
event-driven programs
: external events
cause methods to be executed
Components
: objects we create which have a
screen presence (e.g. controls, window panes),
and with which the user interacts (e.g. buttons).
Events
: when a user interacts with a component,
Java creates an event object (which records the
source)
Listeners
: Objects we create which respond to
events. A listener has a handler method, which
Java invokes when the event occurs.
R. Pełka: Programming Languages
8
Components
Components include buttons, textfields, scrollbars,
windows, pop-up menus, menu items, etc
Example:
javax.swing.JButton
constructor, e.g.:
JButton btn =
new
JButton("Click here!");
instance methods, e.g.:
String
str = btn.getText();
btn.setText("Click again!");
Containers
are components that contain others
instance methods allowing you to add (and position)
components (e.g. button) to the container (e.g. window)
R. Pełka: Programming Languages
9
Event Objects
different user actions correspond to different event
classes (both low level and high level)
example:
java.awt.event.ActionEvent
created by Java when (e.g.) a user clicks a button
instance methods:
getSource() – returns a reference to the source of the event
(i.e.the button, textfield etc that generated it)
getActionCommand() – returns a String associated with the
source (e.g. the button's text)
constructor methods exist, but it is unlikely that we would
call them
R. Pełka: Programming Languages
10
Listener Objects
we delegate to Listener objects the task of
responding to certain events for certain
components
objects contain handler methods that run in
response – we do not normally invoke the handlers
ourselves; Java does it for us when the events occur
Listeners can be any class of object we like, but
must implement certain interfaces to guarantee
inclusion of appropriately named handlers
e.g. "listening" for button clicks
implements ActionListener
must include a definition of actionPerformed method
R. Pełka: Programming Languages
11
Registering Listeners
how does Java know which listener object will
respond to a component's events?
we must register one or more listeners with the
component
e.g. if
btn
is a
JButton
and
lstnr1
and
lstnr2
are
listeners (both
implements ActionListener
)
btn.addActionListener(lstnr1);
btn.addActionListener(lstnr2);
...
btn.removeActionListener(lstnr2);
When the user interacts with the button, Java invokes
the handler methods in each registered listener.
R. Pełka: Programming Languages
12
Container (window) with
component (button)
All this for one button click ...
user
user clicks
button
event object
is generated
ae:ActionEvent
event is
queued
for action
Listener objects
... do something
event dispatch
loop: remove from
queue, invoke
handlers in
registered
listeners
R. Pełka: Programming Languages
13
... which requires:
In the program:
write a class that creates a window and a JButton, adds the
JButton to the window, makes the window visible
write listener classes (implements ActionListener) with
handler method (actionPerformed)
create listener objects and register them with the JButton
At runtime:
user clicks the button
Java creates the ActionEvent object
Java adds object to a queue of events
Java repeatedly
takes object from queue
identifies their listeners
invokes each listener's handler with event as input
R. Pełka: Programming Languages
14
A first GUI ...
import
java.awt.*;
import
java.awt.event.*;
import
javax.swing.*;
public
class
SimplePanel
extends
JPanel {
private
JButton btn;
public
SimplePanel() {
super
();
btn =
new
JButton("Click me!");
add(btn);
ActionListener lstnr =
new
SimpleButtonListener();
btn.addActionListener(lstnr);
}
import AWT, AWT.event
and Swing packages
import AWT, AWT.event
and Swing packages
call to JPanel constructor
call to JPanel constructor
create a button
create a button
add it to the panel
add it to the panel
create a listener
create a listener
register it with the button
register it with the button
R. Pełka: Programming Languages
15
public
static
void
main(String[] args) {
JFrame frm =
new
JFrame("A simple GUI");
Container contentPane = frm.getContentPane();
JPanel pnl =
new
SimplePanel();
contentPane.add(pnl);
frm.setBounds(100, 300, 400, 200);
frm.setVisible(true);
}
}
SimplePanel continued
create a frame
create a frame
get a handle on it
get a handle on it
create a panel
create a panel
add panel to frame
add panel to frame
position it on screen
position it on screen
make it visible!
make it visible!
R. Pełka: Programming Languages
16
SimpleButtonListener
import
java.awt.event.*;
public class
SimpleButtonListener
implements
ActionListener {
private
int
count;
public
SimpleButtonListener() {
}
public
void
actionPerformed(ActionEvent ae) {
count++;
System.out.println(count);
}
}
tell Java it
is a Listener
tell Java it
is a Listener
state what happens
when the button is
pressed
state what happens
when the button is
pressed
R. Pełka: Programming Languages
17
That’s it ...
try do it in BlueJ yourself
you can also use JDK ...
no changes in source code needed
after 10 clicks
R. Pełka: Programming Languages
18
Observations
no low level details (trapping the mouse
click, queuing the event object, etc.)
a component may have any number of
listeners attached to it, including zero
we did not need to invoke the handler
actionPerformed
– Java does it for us
handlers should not involve a lot of
computation
R. Pełka: Programming Languages
19
Converting Centigrade to
Fahrenheit
construct a simple GUI
allowing a user to
convert temperatures between
centigrade
and
fahrenheit
the user should be able to input
a temperature in fahrenheit, then click to convert, and
see the corresponding centigrade reading
a temperature in centigrade, then click to convert, and
see the corresponding fahrenheit reading
Suggestion – always display both readings in the
GUI, and provide two buttons for the user to
choose the conversion
R. Pełka: Programming Languages
20
Outline plan for GUI
a frame for the GUI ...
... containing a panel in its content pane ...
... which contains two buttons
... and two boxes for displaying
temperatures
... with appropriate labels
the buttons will need Listeners, which will
read the appropriate input
compute the appropriate conversion
write the result to the appropriate box
does the frame need a Listener?
R. Pełka: Programming Languages
21
Components in the GUI
the GUI needs 2
JButton
s, a subclass of
JPanel
, and
javax.swing.JTextField
allows display / entry / edit of a line of text
constructor specifies initial value (and number of
columns)
has methods
setText(...), getText(...),
etc.
javax.swing.JLabel
allows display of text / images
user cannot edit them
constructor supplies initial text
has methods
setText(...), getText(...),
etc.
R. Pełka: Programming Languages
22
JFrame
JPanel (in the ContentPane
of the JFrame)
JButton
JTextField
JLabel
Components in the GUI
R. Pełka: Programming Languages
23
GUI Containers
some components are
containers
can have other components added to them
JPanel
is a container – it has
JButton
s added to it
a container can have other containers added to it
JFrame
is a container – it has a
JPanel
added to it
(via its content pane)
(in fact, in Swing, all components are
containers)
R. Pełka: Programming Languages
24
Layout Managers
you can specify the position in a container at which a
component will be placed (e.g.
setLocation(...)
),
but this is not sensitive to resizing or to different
platforms
each container has an instance variables which holds
a layout manager object, which you can set and get
when you add components to the container, the
layout manager positions them and sizes them
automatically
the default for
JPanel
is
FlowLayout
, which places
them sequentially, left-to-right, top-to-bottom
others include
BorderLayout
,
CardLayout
,
GridLayout
,
GridBagLayout
and
BoxLayout
R. Pełka: Programming Languages
25
Implementation in BlueJ
R. Pełka: Programming Languages
26
class TempConversionGUI
import
javax.swing.*;
import
java.awt.*;
public class
TempConversionGUI
extends
JPanel {
// constants definition
public
static final String DEGREES_FAHRENHEIT = "Degrees Fahrenheit";
public
static final String DEGREES_CENTIGRADE = "Degrees Centigrade";
public
static final String COMPUTE_FAHRENHEIT = "Compute Fahrenheit";
public
static final String COMPUTE_CENTIGRADE = "Compute Centigrade";
private
static final String INIT_FAHR = "212";
private
static final String INIT_CENT = "100";
private
static final
int
TFCOLS = 6;
// components defininition
private
JLabel fahrLabel;
private
JTextField fahrField;
private
JLabel centLabel;
private
JTextField centField;
private
JButton compFahrBtn;
private
JButton compCentBtn;
...
R. Pełka: Programming Languages
27
class TempConversionGUI
ctnd.
// construct Frame and all components
public
TempConversionGUI() {
super
();
fahrLabel =
new
JLabel(DEGREES_FAHRENHEIT);
fahrField =
new
JTextField(INIT_FAHR, TFCOLS);
centLabel =
new
JLabel(DEGREES_CENTIGRADE);
centField =
new
JTextField(INIT_CENT, TFCOLS);
compFahrBtn =
new
JButton(COMPUTE_FAHRENHEIT);
compCentBtn =
new
JButton(COMPUTE_CENTIGRADE);
add(fahrLabel);
add(fahrField);
add(centLabel);
add(centField);
add(compFahrBtn);
add(compCentBtn);
// add Listeners
compFahrBtn.addActionListener(
new
CompFahrBtnLstnr(
this
));
compCentBtn.addActionListener(
new
CompCentBtnLstnr(
this
));
} ...
R. Pełka: Programming Languages
28
class TempConversionGUI
ctnd.
// methods for getting and setting values in TextFields
public void
setFahrField(
int
theFahr) {
fahrField.setText("" + theFahr);
}
public void
setCentField(
int
theCent) {
centField.setText("" + theCent);
}
public int
getFahrField() {
String str = fahrField.getText().trim();
return
Integer.parseInt(str);
}
public int
getCentField() {
String str = centField.getText().trim();
return
Integer.parseInt(str);
}
...
R. Pełka: Programming Languages
29
class TempConversionGUI
ctnd.
// main method
public static void
main(String[] args) {
TempConversionGUI gui =
new
TempConversionGUI();
JFrame frm =
new
JFrame("Temperature Conversions");
Container contentPane = frm.getContentPane();
contentPane.add(gui);
frm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frm.setBounds(50, 75, 300, 150);
frm.setVisible(true);
}
}
Class
TempConversionGUI
is ready !
R. Pełka: Programming Languages
30
class CompFahrBtnLstnr
import
java.awt.event.*;
public class
CompFahrBtnLstnr
implements
ActionListener {
// private variable gui
private
TempConversionGUI gui;
// constructor
public
CompFahrBtnLstnr(TempConversionGUI theGUI) {
gui = theGUI;
}
// method for cent to fahr conversion
public void
actionPerformed(ActionEvent ae) {
int
cent = gui.getCentField();
int
fahr = (
int
) Math.round(cent * 9.0 / 5.0 + 32);
gui.setFahrField(fahr);
}
}
R. Pełka: Programming Languages
31
class CompCentBtnLstnr
import
java.awt.event.*;
public class
CompCentBtnLstnr
implements
ActionListener {
// private variable gui
private
TempConversionGUI gui;
// constructor
public
CompCentBtnLstnr(TempConversionGUI theGUI) {
gui = theGUI;
}
// method for fahr to cent conversion
public void
actionPerformed(ActionEvent ae) {
int
fahr = gui.getFahrField();
int
cent = (
int
) Math.round((fahr - 32) * 5.0 / 9.0);
gui.setCentField(cent);
}
}
R. Pełka: Programming Languages
32
class GenericWindowLstnr
import
java.awt.event.*;
public class
GenericWindowLstnr
implements
WindowListener {
// constructor
public
GenericWindowLstnr() { }
// methods
public void
windowOpened(WindowEvent we) { }
public void
windowActivated(WindowEvent we) { }
public void
windowDeactivated(WindowEvent we) { }
public void
windowIconified(WindowEvent we) { }
public void
windowDeiconified(WindowEvent we) { }
public void
windowClosing(WindowEvent we) {
System.exit(0);
}
public void
windowClosed(WindowEvent we) { }
}
verify this project
yourself in BlueJ !!
R. Pełka: Programming Languages
33
Discussion
in our program, the buttons have listeners, but the
textfields do not
they could have listened for an 'Enter' and then invoked a
handler method
there is a clean separation between the GUI class,
which handles the I/O, and the classes that do the real
processing
the listeners are given a reference to the GUI class so
that they can send messages
we have ignored problems with illegal input
JFrame also has a listener
now, we will consider 7 possible improvements of our
GUI
R. Pełka: Programming Languages
34
1. The Window Listener
we mentioned that we could associate a listener
with the JFrame
the WindowListener interface specifies 7 methods,
which respond to changes in a window's state:
windowActivated(...)
: window is set to be active
windowClosed(...)
: window is closed by program
windowClosing(...)
: window closed by user
windowDeactivated(...)
: window is no longer active
windowDeiconified(...)
: window is restored to normal
windowIconified(...)
: window is minimised
windowOpened(...)
: window opened for first time
R. Pełka: Programming Languages
35
2. Using WindowAdapter
instead of laboriously typing default methods for
the
WindowListener
, we can instead inherit from
WindowAdapter
:
implements
WindowListener
supplies 7 default methods
all we need to do is override the particular methods
we want
R. Pełka: Programming Languages
36
Nested classes
a
nested class
is one defined
inside
another
use if the inside class only makes sense in the
context of the outer one, or if it must have access to
the outer class variables in order to work
public class Outer {
//constructors, variables, methods etc for Outer
class NestedClass {
//constructors, variables, methods, etc
//for NestedClass
}
}
R. Pełka: Programming Languages
37
3(a). WindowListener as nested
class
Nested classes can be static or non-static
public class TempConversionGui {
//...
static class MyAdapter extends WindowAdapter {
public void windowClosing(WindowEvent we) {
System.exit(0);
}
}
public static void main(String[] args) {
//...
frm.addWindowListener(new MyAdapter());
//...
R. Pełka: Programming Languages
38
3(b). … or as Anonymous class
we only used the nested class in a single line
instead of giving a full named class definition, we can use an
anonymous
class:
is defined at same point instance is created
extends a superclass or implements an interface
has no name or constructor of its own
listeners are commonly implemented as anonymous classes
frm.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we)
{
System.exit(0);
}
}
);
R. Pełka: Programming Languages
39
4. Combining the listeners
use a single listener to responds to either
button click
need to determine which button has been
clicked
the event is passed in as an
ActionEvent ae
use
ae.getActionCommand()
to get the text of the
button
decide which computation to do, and which textfield
to update
fewer classes, but the code is more complex
and less cohesive
R. Pełka: Programming Languages
40
5. Make the GUI its own
listener
make the GUI class implement
ActionListener
provide its own
actionPerformed
method
the
actionPerformed
method is simpler – it
has direct access to the variables of the GUI
no need for separate
BtnLstnr
classes
R. Pełka: Programming Languages
41
6. Responsive Text Fields
instead of having fields to enter and display
text, and buttons to initiate action, we could
have the text fields respond to the "Enter" key
the ActionEvent ae is then the "Enter" key
use
ae.getActionCommand()
to report which
text field, and then update the appropriate
field
no need for buttons on the GUI, so should
change the initial size.
R. Pełka: Programming Languages
42
Discussion
we have seen 7 different version of the
temperature conversion program (and the
first 6 give identical GUIs)
these are different design decisions that
you the programmer must make
more classes means a slower start-up to the
program
(but anonymous classes are still classes!)
a single class has less coupling, but less
cohesion in its methods
which version is easiest to design, implement
and maintain?
R. Pełka: Programming Languages
43
Good news for GUI developers
Even simple GUI seems to be very complicated to
develop in Java
Fortunetely, we have a number of IDEs
(
Integrated Development Environments
) to do it
using a mouse and „drag and pop” method
Eclipse
NetBeans (
Oracle
)
R. Pełka: Programming Languages
44
NetBeans
R. Pełka: Programming Languages
45
Summary
Graphical User Interface
Idea and properties
Containers
Components
events
Tools for GUI design
AWT – Application Windowing Toolkit
Swing – new Java GUI classes
SWT (Standard Widget Toolkit - Eclipse)
Simple GUI design