Drawing a Line - Villanova Computer Science

Download Report

Transcript Drawing a Line - Villanova Computer Science

1052 Series for Graphics
Graphics,
Applets
Graphical User Interfaces
1
CLH GUI slides
Outline - Chapter 2
Graphics
Applets
Drawing Shapes
2
CLH GUI slides
Introduction to Graphics

The last few sections of each chapter of the textbook
focus on graphics and graphical user interfaces

A picture or drawing must be digitized for storage on a
computer

A picture is made up of pixels (picture elements), and
each pixel is stored separately

The number of pixels used to represent a picture is
called the picture resolution

The number of pixels that can be displayed by a
monitor is called the monitor resolution
3
CLH GUI slides
Coordinate Systems

Each pixel can be identified using a two-dimensional
coordinate system

When referring to a pixel in a Java program, we use a
coordinate system with the origin in the top-left corner
(0, 0)
112
X
40
(112, 40)
Y
4
CLH GUI slides
The Coordinate System
<0, 0>
X
x
y
<x, y>
Y
<width-1,
height-1>
5
CLH GUI slides
Outline
Graphics
Applets
Drawing Shapes
6
CLH GUI slides
Applets

A Java application is a stand-alone program with a
main method (like the ones we've seen so far)

A Java applet is a program that is intended to
transported over the Web and executed using a web
browser

An applet doesn't have a main method

Instead, there are several special methods that serve
specific purposes
7
CLH GUI slides
Applets

An applet is a Panel that allows interaction with a Java
program.

A applet is typically embedded in a Web page and can
be run from a browser.

You need special HTML in the Web page to tell the
browser about the applet.

Applets run in a sandbox: they have no access to the
client’s file system.
8
CLH GUI slides
Applets

The paint method, for instance, is executed
automatically and is used to draw the applet’s contents

The paint method accepts a parameter that is an
object of the Graphics class

A Graphics object defines a graphics context on
which we can draw shapes and text

The Graphics class has several methods for drawing
shapes
9
CLH GUI slides
Applets

The class that defines an applet extends the Applet
class

This makes use of inheritance, which is explored in
more detail in Chapter 8

See Einstein.java (page 97)

An applet is embedded into an HTML file using a tag
that references the bytecode file of the applet

The bytecode version of the program is transported
across the web and executed by a Java interpreter that
is part of the browser
10
CLH GUI slides
HTML
<html>
<head>
<title> Hi World Applet </title>
</head>
<body>
<applet code="HiWorld.class”
width=300 height=200>
<param name=arraysize value=10>
</applet>
</body>
</html>
11
CLH GUI slides
The HTML applet Tag
<html>
<head>
<title>The Einstein Applet</title>
</head>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
12
CLH GUI slides
Java Applets
local computer
Java source
code
remote
computer
Java
compiler
Java
bytecode
Web browser
Java
interpreter
13
CLH GUI slides
Outline
Graphics
Applets
Drawing Shapes
14
CLH GUI slides
Drawing Shapes

Let's explore some of the methods of the Graphics
class that draw shapes in more detail

A shape can be filled or unfilled, depending on which
method is invoked

The method parameters specify coordinates and sizes

Shapes with curves, like an oval, are usually drawn by
specifying the shape’s bounding rectangle

An arc can be thought of as a section of an oval
15
CLH GUI slides
Sample Graphics methods

A Graphics context is something you can paint on.

g.drawString(“Hello, World”, 20, 20);
g.drawRect(x, y, width, height);

g.fillRect(x, y, width, height);





g.drawOval(x, y, width, height);
g.fillOval(x, y, width, height);
To set the color that will fill the Oval use:
g.setColor(Color.red);
16
CLH GUI slides
Drawing a Line
10
150
X
20
45
Y
page.drawLine (10, 20, 150, 45);
or
page.drawLine (150, 45, 10, 20);
17
CLH GUI slides
Drawing a Rectangle
50
X
20
40
100
Y
page.drawRect (50, 20, 100, 40);
Where 50,20 are the x and y values where
The rectangle will start
100 is the width
40 is the length
18
CLH GUI slides
Drawing an Oval
175
X
20
80
bounding
rectangle
Y
50
page.drawOval (175, 20, 50, 80);
We give values for the bounding rectangle –
Start the left side of oval at 175,20
19
CLH GUI slides
public class No_Parking extends applet
{
{
public void paintComponent (Graphics page)
page.drawString (Parking”, 50, 50);
page.drawOval (45, 24, 43, 43);
page.drawLine (82, 30, 51,61);
} //method paintComponent
} // class No_Parking
Appletviewer : No_Parking Class
Parking
Applet Started
20
CLH GUI slides
Drawing Shapes

Every drawing surface has a background color

Every graphics context has a current foreground color

Both can be set explicitly

See Snowman.java (page103)
21
CLH GUI slides
Representing Color

A black and white picture could be stored using one
bit per pixel (0 = white and 1 = black)

A colored picture requires more information; there are
several techniques for representing colors

For example, every color can be represented as a
mixture of the three additive primary colors Red,
Green, and Blue

Each color is represented by three numbers between 0
and 255 that collectively are called an RGB value
22
CLH GUI slides
The Color Class

A color in a Java program is represented as an object
created from the Color class

The Color class also contains several predefined
colors, including the following:
Object
RGB Value
Color.black
Color.blue
Color.cyan
Color.orange
Color.white
Color.yellow
0, 0, 0
0, 0, 255
0, 255, 255
255, 200, 0
255, 255, 255
255, 255, 0
23
CLH GUI slides
public class Snowman extends JApplet
{
public void paintComponent (Graphics page)
{
final int MID = 150;
final int TOP = 50;
setBackground (Color.cyan);
page.setColor (Color.blue);
page.fillRect (0, 175, 300, 50); // ground
page.setColor (Color.yellow);
page.fillOval (-40, -40, 80, 80); // sun
page.setColor (Color.white);
page.fillOval (MID-20, TOP, 40, 40);
// head
page.fillOval (MID-35, TOP+35, 70, 50); // upper torso
page.fillOval (MID-50, TOP+80, 100, 60); // lower torso
24
CLH GUI slides
page.setColor (Color.black);
page.fillOval (MID-10, TOP+10, 5, 5); // left eye
page.fillOval (MID+5, TOP+10, 5, 5); // right eye
page.drawArc (MID-10, TOP+20, 20, 10, 190, 160); // smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40); // left arm
page.drawLine (MID+25, TOP+60, MID+55, TOP+60); // right arm
page.drawLine (MID-20, TOP+5, MID+20, TOP+5);
page.fillRect (MID-15, TOP-20, 30, 25);
// brim of hat
// top of hat
}
}
25
CLH GUI slides
Snowman Applet
26
CLH GUI slides
More about Applets
4/6/2017 GUI’s 1051
27
Applet methods

public void init ()

public void start ()

public void stop ()

public void destroy ()

public void paint (Graphics g)
28
CLH GUI slides
Why an applet works

You write an applet by extending the class Applet.
Applet defines methods init( ), start( ), stop( ),
paintComponent(Graphics), destroy( )

These methods do nothing--they are stubs.

You make the applet do something by overriding these
methods.

29
CLH GUI slides
public void init ( )

This is the first method to execute

It is an ideal place to initialize variables

It is the best place to define and use buttons, text
fields, sliders, layouts, etc.
30
CLH GUI slides
The init() Method
Invoked when the applet is first loaded and again if the
applet is reloaded.
Common functions implemented in this method include
creating threads,
 loading images,
setting up user-interface components,
and getting parameters from the <applet> tag in the
HTML page.
31
CLH GUI slides
public void start ( )

Not always needed

Called after init( )


Called each time the page is loaded and restarted.e.g.
after a user leaves and goes to another web page.
Used mostly in conjunction with stop( )
32
CLH GUI slides
public void stop( )

Not always needed. Used mostly in conjunction with
start().

Called when the browser leaves the page - invoked
when the user moves off the page.


Use stop( ) if the applet is doing heavy computation
that you don’t want to continue when the browser is on
some other page.
When the user leaves the page, any threads the applet
has started—but not completed—will continue to run
if stop is not called.
33
CLH GUI slides
public void destroy( )

Seldom needed

Called after stop( )

Use to explicitly release system resources (like threads)

System resources are usually released automatically
34
CLH GUI slides
Applet flow of control
init( )
start( )
do some work
stop( )
destroy( )
35
CLH GUI slides
Browser Calling Applet Methods
reload
enters web page
init
after init
return to the page
start
exit
CLH GUI slides
stop
leave the page
destroy
36
public void paint(Graphics g)

Almost always needed

Any painting you want to do should be done here, or
in a method you call from here

Painting that you do in other methods may or may not
happen

Don’t call this paintComponent directly. It’s called
automatically. Call repaint( ) instead.
37
CLH GUI slides
repaint( )



Call repaint( ) when you have changed something
and want your changes to show up on the screen
repaint( ) is a request--it might not happen.
When you call repaint( ), Java schedules a call to
update(Graphics g).
38
CLH GUI slides
update( )


When you call repaint( ), Java schedules a call to
update(Graphics g)
Here's what update does:
public void update(Graphics g) {
// Fill applet with background color
paintComponent(g);
}
39
CLH GUI slides
Other useful Applet methods




System.out.println(String s)
 Works from appletviewer, not from browsers
 Automatically opens an output window.
showStatus(String) displays the String in the applet’s
status line.
Each call overwrites the previous call.
You have to allow time to read the line!
40
CLH GUI slides
Applets are not magic!

Anything you can do in an applet, you can do in an
application.

You can do some things in an application that you can’t
do in an applet such as reading in from a file.
41
CLH GUI slides
GUI’s

A GUI in Java is created with at least three kinds of
objects:
 Components
 Events
 Listeners
42
CLH GUI slides
Graphical Applications

Let's examine some Java applications that have
graphical components

These components will serve as a foundation to
programs that have true graphical user interfaces
(GUIs)
43
CLH GUI slides
GUI Components

A GUI component is an object that represents a screen
element such as a button or a text field

GUI-related classes are defined primarily in the
java.awt and the javax.swing packages

The Abstract Windowing Toolkit (AWT) was the
original Java GUI package

The Swing package provides additional and more
versatile components

Both packages are needed to create a Java GUI-based
program
44
CLH GUI slides
GUI Containers

A GUI container is a component that is used to hold
and organize other components

A frame is a container that is used to display a GUIbased Java application

A frame is displayed as a separate window with a title
bar – it can be repositioned and resized on the screen
as needed

A panel is a container that cannot be displayed on its
own but is used to organize other components

A panel must be added to another container to be
displayed
45
CLH GUI slides
Containers

A container is a special component that can hold other
components

The AWT Applet class, as well as the Swing JApplet
class, are containers

Other containers include:
 panels
 frames
 dialog boxes
46
CLH GUI slides
GUI Containers

A GUI container can be classified as either
heavyweight or lightweight

A heavyweight container is one that is managed by the
underlying operating system

A lightweight container is managed by the Java
program itself

Occasionally this distinction is important

A frame is a heavyweight container and a panel is a
lightweight container
47
CLH GUI slides
Containers and Components


The job of a Container is to hold and display
Components
Some common subclasses of Component are JButton,
JCheckbox, JLabel, JScrollbar, JTextField, and
JTextArea

A Container is also a Component

Other Container subclasses are Panel (and Applet), Window,
and Frame
48
CLH GUI slides
The Component Class Hierarchy

The Java classes that define GUI components are part of a
class hierarchy

Swing GUI components typically are derived from the
JComponent class which is derived from the Container
class which is derived from the Component class

Generally we use components and events that are
predefined by classes in the Java class library
49
CLH GUI slides
GUI Development


Therefore, to create a Java program that uses a GUI we
must:

instantiate and set up the necessary components

implement listener classes for any events we care about

establish the relationship between listeners and
components that generate the corresponding events
Let's now explore some new components and see how
this all comes together
50
CLH GUI slides
Some types of components
51
CLH GUI slides
Swing Components

There are various Swing GUI components that we can incorporate
into our software:









labels (including images)
text fields and text areas
buttons
check boxes
radio buttons
menus
combo boxes
and many more…
Using the proper components for the situation is an important
part of GUI design
52
CLH GUI slides
Creating components

JLabel lab = new Label (”Hi, Dave!");

JButton but = new Button ("Click me!");

JCheckbox toggle = new Checkbox (”toggle");


JTextField txt =
new JTextField (”Initial text.", 20);
JScrollbar scrolly = new Scrollbar
(Scrollbar.HORIZONTAL, initialValue,
bubbleSize, minValue, maxValue);
53
CLH GUI slides
Labels

A label is a GUI component that displays a line of text

Labels are usually used to display information or
identify other components in the interface

Let's look at a program that organizes three labels in a
panel and displays that panel in a frame

This program is not interactive, but the frame can be
repositioned and resized
54
CLH GUI slides
Labels and Image Icons

A label is used to provide information to the user or to
add decoration to the GUI

It can incorporate an image defined by the ImageIcon
class
55
CLH GUI slides
Image Icons

An image icon object represents an image

ImageIcon objects use either JPEG or GIF images

They can be used in several situations, such as being
displayed in a label

A JLabel can contain a String, and ImageIcon, or
both

The orientation of the label's text and image can be set
explicitly

See LabelDemo.java (page 487)

See LabelPanel.java (page 488)
56
CLH GUI slides
The LabelDemo Program
57
CLH GUI slides
public class LabelDemo
{
//-------------------------------------------------// Creates and displays three labels
//--------------------------------------------public static void main (String[] args) {
ImageIcon icon = new ImageIcon ("devil.gif");
JLabel label1, label2, label3;
label1 = new JLabel ("Devil Left", icon,
SwingConstants.CENTER);
label2 = new JLabel ("Devil Right", icon,
SwingConstants.CENTER);
label2.setHorizontalTextPosition (SwingConstants.LEFT);
label2.setVerticalTextPosition (SwingConstants.BOTTOM);
58
CLH GUI slides
label3 = new JLabel ("Devil Above", icon,
SwingConstants.CENTER);
label3.setHorizontalTextPosition (SwingConstants.CENTER);
label3.setVerticalTextPosition (SwingConstants.BOTTOM);
JPanel panel = new JPanel();
panel.setBackground (Color.cyan);
panel.setPreferredSize (new Dimension (200, 250));
panel.add (label1);
panel.add (label2);
panel.add (label3);
// get the container to put the labels on
Container c = getContentPane();
c.add(panel);
}
CLH GUI slides
59
The LabelDemo Program
60
CLH GUI slides
GUI Elements - Events

An event is an object that represents some occurrence.
Mostly, they correspond to user actions. E.g. a pressing
a mouse button.

When a user performs some action on an a component
most components generate events. E.g. when the user
presses a mouse button, an event is generated by the
component.

Later we will discuss how a GUI reacts to an event
with a Listener.
61
CLH GUI slides
Events
•
For example, we may want our program to perform some
action when the following occurs:
– the mouse is moved
– a mouse button is clicked
– the mouse is dragged
– a graphical button is clicked
– a keyboard key is pressed
– a timer expires
•
Not all events correspond to user actions. A program that
reacts to events is call event-driven.
62
CLH GUI slides
Making components active

Most components already appear to do something-buttons click, text appears

To associate an action with a component, attach a listener
to it

Components send events, listeners listen for events

Different components may send different events, and
require different listeners

A listener is an object that is “waiting for an event to
occur” and we can code what we want it to do when an
event occurs
63
CLH GUI slides
Listeners




Listeners are interfaces, not classes, like the
ActionListener interface
class ButtonListener implements ActionListener
An interface is a group of methods that must be
supplied
When you say implements, you are promising to supply
those methods
64
CLH GUI slides
Events and Listeners
Event
Generator
Listener
This object may
generate an event
This object waits for, and
responds to an event
When an event occurs, the generator calls
the appropriate method of the listener,
passing an object that describes the event
65
CLH GUI slides
Listener Interfaces

We can create a listener object by writing a class that
implements a particular listener interface

The Java standard class library contains several
interfaces that correspond to particular event categories

For example, the MouseListener interface contains
methods that correspond to mouse events

After creating the listener, we add the listener to the
component that might generate the event to set up a
formal relationship between the generator and listener
66
CLH GUI slides
Creating GUIs

Therefore, to create a program with a GUI, we :

define and set up the components

create listener objects

set up the relationships between the listeners
and the components which generate events of
interest

define what happens in response to each
event
67
CLH GUI slides
Buttons

A push button is a component that allows the user to
initiate an action by pressing a graphical button using
the mouse

A push button is defined by the JButton class

It generates an action event

The PushCounter example displays a push button
that increments a counter each time it is pushed

See PushCounter.java (page 186)
68
CLH GUI slides
PushButton applet
69
CLH GUI slides
Push Counter Example

The components of the GUI are the button, a label to
display the counter, a panel to organize the
components, and the main frame

The PushCounter class represents the panel used to
display the button and label

In the init method, the elements of the GUI are set up
and it initializes the counter to zero
70
CLH GUI slides
public class PushCounter extends JApplet
{
private int pushes;
private JLabel label;
private JButton push;
//-----------------------------------------------------------// Sets up the GUI.
//-----------------------------------------------------------public void init ()
{
pushes = 0;
push = new JButton ("Push Me!");
// attach the actionlistener class to the push buttons
push.addActionListener (new ButtonListener());
label = new JLabel ("Pushes: " + Integer.toString (pushes));
Container cp = getContentPane();
cp.setBackground (Color.cyan);
cp.setLayout (new FlowLayout());
cp.add (push);
cp.add (label); }
CLH GUI slides
71
/******************************************
// Represents a listener for button push (action) events.
//******************************************
private class ButtonListener implements ActionListener
{
//---------------------------------------------------------// Updates the counter when the button is pushed.
//---------------------------------------------------------public void actionPerformed (ActionEvent event)
{
pushes++;
label.setText("Pushes: " + pushes);
repaint ();
}
}}
A call is then made to repaint the applet to update the change on
the label
72
CLH GUI slides
Listeners
push = new JButton ("Push Me!");
push.addActionListener (new ButtonListener());

With the above code, a JButton object is created and an
class that acts as the listener is attached to it.

When the button is pushed, an event is fired, and the
actionPerformed method, which is defined in the
ButtonListener class is called.
73
CLH GUI slides
Push Counter Algorithm


When the user presses the button,

An event is fired:

the button component creates an ActionEvent object
and

calls the actionPerformed method of the listener class
The actionPerformed method increments the counter
and resets the text of the label
74
CLH GUI slides
Push Counter Example

The ButtonListener class is the listener for the
action event generated by the button

It is implemented as an inner class, which means it is
defined within the body of another class

This allows the listener class to have access to the
instance variables and methods in the outer class

Inner classes should only be used in situations where
there is an intimate relationship between the two
classes.
75
CLH GUI slides
Action Events

A JButton generates an action event when it is pushed
as does a JTextfield.

Some components have more than one listener (just to
keep things real simple!!!!!)

A list of the Components and their listeners in listed in
the back of the 1051 book.
76
CLH GUI slides
Nested Panels

Containers that contain other components make up the
containment hierarchy of an interface

This hierarchy can be as intricate as needed to create
the visual effect desired

The following example nests two panels inside a third
panel – note the effect this has as the frame is resized

See NestedPanels.java (page 146)
77
CLH GUI slides
Nested Panels
78
CLH GUI slides
public class NestedPanels
{
//-----------------------------------------------------------------
// Presents two colored panels nested within a third.
//-----------------------------------------------------------------
public static void main (String[] args)
{
JFrame frame = new JFrame ("Nested Panels");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
// Set up first subpanel
JPanel subPanel1 = new JPanel();
subPanel1.setPreferredSize (new Dimension(150,
100));
subPanel1.setBackground (Color.green);
79
CLH GUI slides
// create and add another label
JLabel label1 = new JLabel ("One");
subPanel1.add (label1);
// Set up second subpanel
JPanel subPanel2 = new JPanel();
subPanel2.setPreferredSize (new Dimension(150,
100));
subPanel2.setBackground (Color.red);
// create another label and add to panel 2
JLabel label2 = new JLabel ("Two");
subPanel2.add (label2);
80
CLH GUI slides
// Set up primary panel
JPanel primary = new JPanel();
primary.setBackground (Color.blue);
// add the two panels to the primary panel
primary.add (subPanel1);
primary.add (subPanel2);
// add the primary panel to the contentPane
getContentPane().add(primary);
}
}
81
CLH GUI slides
Text Fields

Let's look at another GUI example that uses another
type of component

A text field allows the user to enter one line of input

If the cursor is in the text field, the text field
component generates an action event when the enter
key is pressed

See Fahrenheit.java (page 190)
See FahrenheitPanel.java (page 191)

82
CLH GUI slides
See Farhenheit.doc
83
CLH GUI slides
Fahrenheit.java
public class Fahrenheit
{
//----------------------------------------------------------------// Creates and displays the temperature converter GUI.
//----------------------------------------------------------------public static void main (String[] args)
{
final JFrame jFrame = new FahrenheitGUI()); // Main frame
jFrame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
jFrame.pack();
jFrame.setSize(WINDOW_WIDTH,WINDOW_HEIGHT);
jFrame.setVisible(true);
}
}
84
// Demonstrates the use of JFrame and JTextArea GUI components.
//*****************************************
public class FahrenheitGUI extends JFrame{
private int WIDTH = 300;
private int HEIGHT = 75;
private JPanel panel;
private JLabel inputLabel, outputLabel,resultLabel;
private JTextField fahrenheit;
// Sets up the GUI.
public FahrenheitGUI() // create the labels
{
super("Farhrenheit Converter");
inputLabel = new JLabel ("Enter Fahrenheit temperature:");
outputLabel = new JLabel ("Temperature in Celcius: ");
resultLabel = new JLabel ("---");
85
CLH GUI slides
fahrenheit = new JTextField (5);
// add a listener to the textfield
fahrenheit.addActionListener (new TempListener());
// Create a panel to put the components on
panel = new JPanel();
panel.setBackground (Color.yellow);
panel.add (inputLabel);
panel.add (fahrenheit);
panel.add (outputLabel);
panel.add (resultLabel);
Container c = getContentPane();
c.add (panel);
} // close
86
CLH GUI slides
JTextFields

The Fahrenheit program is an application

The work of creating a GUI in an application is done in
the constructor – vs. the init method in an applet.

The program converts a Fahrenheit temperature to
Celsius value. The user enters an input value into a
text field.

A text Field is a component that displays an area into
which the user can type a single line of information

They are commonly used to get input from a user.
87
CLH GUI slides
Components & panels

Components are added using the Panel add
method. Once all the components are added, the
panel is added to the contentPane.
Panel panel = new JPanel()
panel.setPreferredSize (new Dimension(WIDTH, HEIGHT));
panel.setBackground (Color.yellow);
panel.add (inputLabel);
panel.add (fahrenheit);
panel.add (outputLabel);
panel.add (resultLabel);
getContentPane().add (panel);
88
CLH GUI slides
Panels & Containers.
If we are going to add more panels to the contentPane we
would use:
Container c = getContentPane();
c.add(panel);
89
CLH GUI slides
The Farenheit Program

The order in which the labels and text field are added is
the order in how they appear. The size of the panels
determines how they line up to each other.

This is a function of the layout managers.

Panels by default are governed by a flow layout which
we will explore later.
90
CLH GUI slides
The fahrenheit Program

The program reacts when the user presses the enter
key inside the text field.

A JTextField object generates an action even when the
enter key is pressed – same as the button in the
PushCounter program.

The TempListener class takes care of the event – which
is an action event. It is an inner class which allows easy
access to the components stored in the enclosing class.
In the actionPerformed method, the input string is
obtained using the getText method of the JTextField
CLH GUI
slides
class.

91
// Performs the conversion when the enter key is pressed in
// the text field.
// Represents an action listener for the temperature input field.
private class TempListener implements ActionListener
{
public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celciusTemp;
String text = fahrenheit.getText();
fahrenheitTemp = Integer.parseInt (text);
celciusTemp = (fahrenheitTemp-32) * 5/9;
resultLabel.setText (Integer.toString (celciusTemp));
}
}
}
CLH GUI slides
92
Listeners for TextFields


A JTextField has two listeners, ActionListener and
TextListener:
An (1) ActionListener listens for hitting the return key
An ActionListener demands
public void actionPerformed (ActionEvent e)

use getText( ) to get the text from whatever is input into the
textfield.

A (2)TextListener listens for any and all keys
A TextListener demands
public void textValueChanged(TextEvent e)
93
CLH GUI slides
Determining Event Sources

Recall that interactive GUIs require establishing a
relationship between components and the listeners
that respond to component events

One listener object can be used to listen to two
different components

The source of the event can be determined by using the
getSource method of the event passed to the listener

See LeftRight.java (page 258)
See LeftRightPanel.java (page 259)

94
CLH GUI slides
public class LeftRight
{
//----------------------------------------------------------------// Creates the main program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Left Right");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new LeftRightPanel());
frame.pack();
frame.setVisible(true);
}
}
95
CLH GUI slides
public class LeftRightPanel extends JPanel
{
private JButton left, right;
private JLabel label;
private JPanel buttonPanel;
//----------------------------------------// Create two buttons and add the same listener to them
//-----------------------------------------public LeftRightPanel ()
{
left = new JButton ("Left");
right = new JButton ("Right");
ButtonListener listener = new ButtonListener();
left.addActionListener (listener);
right.addActionListener (listener);
label = new JLabel ("Push a button");
96
CLH GUI slides
buttonPanel = new JPanel();
buttonPanel.setPreferredSize (new Dimension(200,
40));
buttonPanel.setBackground (Color.blue);
buttonPanel.add (left);
buttonPanel.add (right);
setPreferredSize (new Dimension(200, 80));
setBackground (Color.cyan);
add (label);
add (buttonPanel);
}
97
CLH GUI slides
//****************************************************
// Represents a listener for both buttons.
//****************************************************
private class ButtonListener implements ActionListener
{
//-------------------------------------------------------------// Determines which button was pressed and sets the label
// text accordingly.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
if (event.getSource() == left)
label.setText("Left");
else
label.setText("Right");
}
}
}
CLH GUI slides
98
99
CLH GUI slides
Layout Managers

A layout manager is an object that determines the way
that components are arranged in a container

There are several predefined layout managers defined
in the Java standard class library:
Flow Layout
Border Layout
Card Layout
Grid Layout
GridBag Layout
Box Layout
Overlay Layout
Defined in the AWT
Defined in Swing
100
CLH GUI slides
Layout Managers

Every container has a default layout manager, but we
can explicitly set the layout manager as well

Each layout manager has its own particular rules
governing how the components will be arranged

Some layout managers pay attention to a component's
preferred size or alignment, while others do not

A layout manager attempts to adjust the layout as
components are added and as containers are resized
101
CLH GUI slides
Layout Managers

We can use the setLayout method of a container to
change its layout manager
JPanel panel = new JPanel();
panel.setLayout (new BorderLayout());

The following example uses a tabbed pane, a container
which permits one of several panes to be selected

See LayoutDemo.java (page 512)

See IntroPanel.java (page 514)
102
CLH GUI slides
FlowLayout

Use add (component); to add to a component when using a
FlowLayout

Components are added left-to-right

If no room, a new row is started

Exact layout depends on size of Applet

Components are made as small as possible

FlowLayout is convenient but often ugly
103
CLH GUI slides
Flow Layout

Flow layout puts as many components as possible on a
row, and then moves to the next row

Each row of components is centered horizontally in the
window by default, but could also be aligned left or
right

The horizontal and vertical gaps between the
components can be explicitly set also

See FlowPanel.java (page 515)
104
CLH GUI slides
public class FlowPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with some buttons to show how flow layout
// affects their position.
//----------------------------------------------------------------public FlowPanel ()
{
setLayout (new FlowLayout());
setBackground (Color.green);
JButton b1 = new JButton ("BUTTON 1");
JButton b2 = new JButton ("BUTTON 2");
JButton b3 = new JButton ("BUTTON 3");
JButton b4 = new JButton ("BUTTON 4");
JButton b5 = new JButton ("BUTTON 5");
add (b1);
add (b2);
}
}
add (b3);
add (b4);
add (b5);
105
CLH GUI slides
LayoutDemo - Flow
106
CLH GUI slides
Border Layout

A border layout defines five areas to which
components can be added
North
West
Center
East
South
107
CLH GUI slides
BorderLayout

At most five components can
be added

If you want more
components, add a Panel,
then add components to it.

setLayout (new BorderLayout());
add (BorderLayout.NORTH, new Button(“NORTH”));
108
CLH GUI slides
BorderLayout with five Buttons
The code to add 4 buttons to a GUI
public void init()
{
setLayout (new BorderLayout ());
add (BorderLayout.NORTH, new Button ("NORTH"));
add (BorderLayout.SOUTH, new Button ("SOUTH"));
add (BorderLayout.EAST, new Button ("EAST"));
add (BorderLayout.WEST, new Button ("WEST"));
add (BorderLayout.CENTER, new Button ("CENTER"));
}
109
CLH GUI slides
Using a Panel
panel p = new Panel();
add (BorderLayout.SOUTH, p);
p.add (new Button (“Button 1”));
p.add (new Button (“Button 2”));
110
CLH GUI slides
Border Layout

Each area displays one component (which could be
another container such as a JPanel)

Each of the four outer areas enlarges as needed to
accommodate the component added to it

If nothing is added to the outer areas, they take up no
space and other areas expand to fill the void

The center area expands to fill space as needed

See BorderPanel.java (page 518)
111
CLH GUI slides
LayoutDemo - Border
112
CLH GUI slides
Grid Layout

A grid layout presents a container’s components in a
rectangular grid of rows and columns

One component is placed in each cell of the grid, and all
cells have the same size

As components are added to the container, they fill the
grid from left-to-right and top-to-bottom (by default)

The size of each cell is determined by the overall size of
the container

See GridPanel.java (page 521)
113
CLH GUI slides
public class GridPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with some buttons to show how grid
// layout affects their position, shape, and size.
//-----------------------------------------------------------------
public GridPanel()
{
setLayout (new GridLayout (2, 3));
setBackground (Color.green);
JButton b1 = new JButton ("BUTTON 1");
JButton b2 = new JButton ("BUTTON 2");
JButton b3 = new JButton ("BUTTON 3");
JButton b4 = new JButton ("BUTTON 4");
JButton b5 = new JButton ("BUTTON 5");
}
}
add (b1);
add (b2);
add (b3);
add (b4);
add (b5);
114
CLH GUI slides
LayoutDemo - Grid
115
CLH GUI slides
Box Layout

A box layout organizes components horizontally (in
one row) or vertically (in one column)

Components are placed top-to-bottom or left-to-right
in the order in which they are added to the container

By combining multiple containers using box layout,
many different configurations can be created

Multiple containers with box layouts are often
preferred to one container that uses the more
complicated gridbag layout manager
116
CLH GUI slides
Box Layout

Invisible components can be added to a box layout
container to take up space between components

Rigid areas have a fixed size

Glue specifies where excess space should go

A rigid area is created using the createRigidArea
method of the Box class

Glue is created using the createHorizontalGlue or
createVerticalGlue methods

See BoxPanel.java (page 524)
117
CLH GUI slides
LayoutDemo - Box
118
CLH GUI slides
public class BoxPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with some buttons to show how a
//vertical box layout (and invisible components) affects //their
position.
//----------------------------------------------------------------public BoxPanel()
{
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setBackground (Color.green);
JButton b1 = new JButton ("BUTTON 1");
JButton b2 = new JButton ("BUTTON 2");
JButton b3 = new JButton ("BUTTON 3");
JButton b4 = new JButton ("BUTTON 4");
JButton b5 = new JButton ("BUTTON 5");
119
CLH GUI slides
add (b1);
add (Box.createRigidArea (new Dimension (0, 10)));
add (b2);
add (Box.createVerticalGlue());
add (b3);
add (b4);
add (Box.createRigidArea (new Dimension (0, 20)));
add (b5);
}
}
120
CLH GUI slides
Dialog Boxes

A dialog box is a window that appears on top of any
currently active window

It may be used to:






convey information
confirm an action
allow the user to enter data
pick a color
choose a file
A dialog box usually has a specific, solitary purpose,
and the user interaction with it is brief
121
CLH GUI slides
Dialog Boxes

A dialog box is a graphical window that pops up on top
of any currently active window for the user

The Swing API contains a class called JOptionPane
that simplifies the creation and use of basic dialog
boxes

There are three categories of JOptionPane dialog
boxes



A message dialog displays an output string
An input dialog presents a prompt and a single input
text field
A confirm dialog presents the user with a simple yes-orno question
122
CLH GUI slides
Dialog Boxes

The JOptionPane class provides methods that
simplify the creation of some types of dialog boxes

See EvenOdd.java (page 262)

We examine dialog boxes for choosing colors and files
in Chapter 9
123
CLH GUI slides
The EvenOdd Program
124
CLH GUI slides
Check Boxes

A check box is a button that can be toggled on or off

It is represented by the JCheckBox class

Unlike a push button, which generates an action event,
a check box generates an item event whenever it
changes state (is checked on or off)

The ItemListener interface is used to define item
event listeners

The check box calls the itemStateChanged method
of the listener when it is toggled
125
CLH GUI slides
Check Boxes

Let's examine a program that uses check boxes to
determine the style of a label's text string

It uses the Font class, which represents a character
font's:





family name (such as Times or Courier)
style (bold, italic, or both)
font size
See StyleOptions.java (page 265)
See StyleOptionsPanel.java (page 266)
126
CLH GUI slides
public class StyleOptionsPanel extends JPanel
{
private JLabel saying;
private JCheckBox bold, italic;
//----------------------------------------------------------------// Sets up a panel with a label and some check boxes that
// control the style of the label's font.
//----------------------------------------------------------------public StyleOptionsPanel()
{
saying = new JLabel ("Say it with style!");
saying.setFont (new Font ("Helvetica", Font.PLAIN, 36));
bold = new JCheckBox ("Bold"); // create first checkbox
bold.setBackground (Color.cyan);
italic = new JCheckBox ("Italic"); // create second checkbox
italic.setBackground (Color.cyan);
127
// set up a listener classs for the checkboxes
StyleListener listener = new StyleListener();
bold.addItemListener (listener);// add listeners
italic.addItemListener (listener);
add (saying); // add checkboxes and label
add (bold);
add (italic);
setBackground (Color.cyan);
setPreferredSize (new Dimension(300, 100));
128
//****************************************************
// Represents the listener for both check boxes.
//***************************************************
private class StyleListener implements ItemListener
{
//-------------------------------------------------------------// Updates the style of the label font style.
//-------------------------------------------------------------public void itemStateChanged (ItemEvent event)
{
int style = Font.PLAIN;
if (bold.isSelected())
style = Font.BOLD;
if (italic.isSelected())
style += Font.ITALIC;
saying.setFont (new Font ("Helvetica", style, 36));
}
}
}
129
The StyleOptions Program
130
CLH GUI slides
Radio Buttons

A group of radio buttons represents a set of mutually
exclusive options – only one can be selected at any
given time

When a radio button from a group is selected, the
button that is currently "on" in the group is
automatically toggled off

To define the group of radio buttons that will work
together, each radio button is added to a ButtonGroup
object

A radio button generates an action event
131
CLH GUI slides
Radio Buttons

Let's look at a program that uses radio buttons to
determine which line of text to display


See QuoteOptions.java (page 269)
See QuoteOptionsPanel.java (page 270)

Compare and contrast check boxes and radio buttons

Check boxes work independently to provide a
boolean option – do you want skim milk or
whole milk?

Radio buttons work as a group to provide a
set of mutually exclusive options – do you
want to hear classical, rock, or country music?
132
CLH GUI slides
QuoteOptions Program
// Creates and presents the program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Quote Options");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
QuoteOptionsPanel panel = new
QuoteOptionsPanel();
frame.getContentPane().add (panel);
}
}
frame.pack();
frame.setVisible(true);
133
CLH GUI slides
public class QuoteOptionsPanel extends JPanel
{
private JLabel quote;
private JRadioButton comedy, philosophy, carpentry;
private String comedyQuote, philosophyQuote, carpentryQuote;
//----------------------------------------------------------------// Sets up a panel with a label and a set of radio buttons
// that control its text.
//----------------------------------------------------------------public QuoteOptionsPanel()
{
comedyQuote = "Take my wife, please.";
philosophyQuote = "I think, therefore I am.";
carpentryQuote = "Measure twice. Cut once.";
quote = new JLabel (comedyQuote);
quote.setFont (new Font ("Helvetica", Font.BOLD, 24))
134
CLH GUI slides
QuoteOptions
comedy = new JRadioButton ("Comedy", true);
comedy.setBackground (Color.green);
philosophy = new JRadioButton ("Philosophy");
philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry");
carpentry.setBackground (Color.green);
ButtonGroup group = new ButtonGroup();
group.add (comedy);
group.add (philosophy);
group.add (carpentry);
135
CLH GUI slides
QuoteOptions.java
QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener);
philosophy.addActionListener (listener);
carpentry.addActionListener (listener);
add (quote);
add (comedy);
add (philosophy);
add (carpentry);
}
setBackground (Color.green);
setPreferredSize (new Dimension(300, 100));
136
CLH GUI slides
//********************************************************
// Represents the listener for all radio buttons
/***********************************************************
private class QuoteListener implements ActionListener
{
//-------------------------------------------------------------// Sets the text of the label depending on which radio
// button was pressed.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
if (event.getSource() == comedy
quote.setText (comedyQuote);
else
}
}
}
if (event.getSource() == philosophy)
quote.setText (philosophyQuote);
else
quote.setText (carpentryQuote);
137
CLH GUI slides
The QuoteOptions Program
138
CLH GUI slides
Combo Boxes

A JCombobox displays a particular option with a pull
down menu from which the user can choose a different
option

The currently selected option is shown in the combo
box

A combo box can be editable, so that the user can type
their option directly into the box


See JukeBox.java (page 425)
See JukeBoxControls.java (page 426)
139
CLH GUI slides
Combo Boxes

Unlike a JList object, a combo box shows its options
only when the user presses it using the mouse

Options can be established using an array of strings or
using the addItem method

A combo box generates an action event when the user
makes a selection from it
140
CLH GUI slides
The JukeBox Program

See JukeBox.java (page 550)

See JukeBoxControls.java (page 551)
141
CLH GUI slides
//----------------------------------------------------------------// Sets up the GUI for the juke box.
//----------------------------------------------------------------public JukeBoxControls()
{
URL url1, url2, url3, url4, url5, url6;
url1 = url2 = url3 = url4 = url5 = url6 = null;
// Obtain and store the audio clips to play
try
{
url1 = new URL ("file", "localhost", "westernBeat.wav");
url2 = new URL ("file", "localhost", "classical.wav");
url3 = new URL ("file", "localhost", "jeopardy.au");
url4 = new URL ("file", "localhost", "newAgeRythm.wav");
url5 = new URL ("file", "localhost", "eightiesJam.wav");
url6 = new URL ("file", "localhost", "hitchcock.wav");
}
catch (Exception exception) {}
142
CLH GUI slides
music = new AudioClip[7];
music[0] = null; // Corresponds to "Make a
Selection..."
music[1] = JApplet.newAudioClip (url1);
music[2] = JApplet.newAudioClip (url2);
music[3] = JApplet.newAudioClip (url3);
music[4] = JApplet.newAudioClip (url4);
music[5] = JApplet.newAudioClip (url5);
music[6] = JApplet.newAudioClip (url6);
JLabel titleLabel = new JLabel ("Java Juke Box");
titleLabel.setAlignmentX
(Component.CENTER_ALIGNMENT);
143
CLH GUI slides
// Create the list of strings for the combo box options
String[] musicNames = {"Make A Selection...", "Western Beat",
"Classical Melody", "Jeopardy Theme", "New Age Rythm",
"Eighties Jam", "Alfred Hitchcock's Theme"};
musicCombo = new JComboBox (musicNames);
musicCombo.setAlignmentX
(Component.CENTER_ALIGNMENT);
// add an actionListener to the combo box
musicCombo.addActionListener (new
ComboListener());
144
CLH GUI slides
// Set up the buttons
playButton = new JButton ("Play", new ImageIcon ("play.gif"));
playButton.setBackground (Color.white);
playButton.setMnemonic ('p');
stopButton = new JButton ("Stop", new ImageIcon ("stop.gif"));
stopButton.setBackground (Color.white);
stopButton.setMnemonic ('s');/
// add action listeners to the buttons
stopButton.addActionListener (new ButtonListener());
playButton.addActionListener (new ButtonListener());
current = null;
145
CLH GUI slides
// Set up this panel
JPanel buttons = new JPanel();
// set the horizontal layout for the buttons panel to
BoxLayout
buttons.setLayout (new BoxLayout (buttons,
BoxLayout.X_AXIS));
buttons.add (playButton);
buttons.add (Box.createRigidArea (new
Dimension(5,0)));
buttons.add (stopButton);
buttons.setBackground (Color.cyan);
setPreferredSize (new Dimension (300, 100));
setBackground (Color.cyan);
146
CLH GUI slides
Set up a Box Layout
setLayout (new BoxLayout (this,
BoxLayout.Y_AXIS));
// put in a rigid area of 5 pixels
add (Box.createRigidArea (new Dimension(0,5)));
add (titleLabel);
// put in a rigid area of 5 pixels
add (Box.createRigidArea (new Dimension(0,5)));
add (musicCombo);
// put in a rigid area of 5 pixels
add (Box.createRigidArea (new Dimension(0,5)));
add (buttons);
add (Box.createRigidArea (new Dimension(0,5)));
147
CLH GUI slides
Listener for the Combo Boxes
private class ComboListener implements ActionListener
{
//-------------------------------------------------------------// Stops playing the current selection (if any) and resets
// the current selection to the one chosen.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
if (current != null)
current.stop();
// stores the selected music from the combo box in
current
current = music[musicCombo.getSelectedIndex()];
}
}
148
CLH GUI slides
//*****************************************************************
// Represents the action listener for both control
buttons.
//*****************************************************************
private class ButtonListener implements ActionListener
{
//-------------------------------------------------------------// Stops the current selection (if any) in either case. If
// the play button was pressed, start playing it again.
//--------------------------------------------------------------
public void actionPerformed (ActionEvent event)
{
if (current != null)
current.stop();
}
}
}
if (event.getSource() == playButton)
if (current != null)
current.play();
149
CLH GUI slides
Class JukeBox
public class JukeBox
{
//----------------------------------------------------------------// Creates and displays the JukeBoxControls frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JukeBoxControls frame = new JukeBoxControls();
frame.addWindowListener (new
GenericWindowListener());
frame.show();
}
}
150
CLH GUI slides
Outline
Mouse Events and Key Events
151
CLH GUI slides
Mouse Events

Events related to the mouse are separated into mouse
events and mouse motion events

Mouse Events:
mouse pressed
the mouse button is pressed down
mouse released
the mouse button is released
mouse clicked
the mouse button is pressed down and
released without moving the mouse in
between
mouse entered
the mouse pointer is moved onto (over) a
component
mouse exited
the mouse pointer is moved off of a
component
152
CLH GUI slides
Mouse Events

Mouse Motion Events:
mouse moved
the mouse is moved
mouse dragged
the mouse is moved while the mouse button
is pressed down

Listeners for mouse events are created using the
MouseListener and MouseMotionListener
interfaces

A MouseEvent object is passed to the appropriate
method when a mouse event occurs
153
CLH GUI slides
The Dots Program
154
CLH GUI slides
Mouse Events

For a given program, we may only care about one or
two mouse events

To satisfy the implementation of a listener interface,
empty methods must be provided for unused events

See Dots.java (page 413)
See DotsPanel.java (page 414)

155
CLH GUI slides
Extending Event Adapter
Classes

Creating listener classes by implementing a particular
interface (such as MouseListener interface) is not the
only way.

A listener can also be created by extending a special
adapter class of the Java class library

Each listener interface has a corresponding adapter
class (such as the MouseAdapter class)

Each adapter class implements the corresponding
listener and provides empty method definitions
156
CLH GUI slides
Event Adapter Classes

Each adapter class implements the corresponding
listener and provides empty method definitions

When you derive a listener class from an adapter
class, you only need to override the event methods
that pertain to the program

Empty definitions for unused event methods do not
need to be defined because they are provided via
inheritance

See OffCenter.java (page 466)
See OffCenterPanel.java (page 467)

157
CLH GUI slides
Key Events

A key event is generated when the user types on the
keyboard
key pressed
a key on the keyboard is pressed down
key released
a key on the keyboard is released
key typed
a key on the keyboard is pressed down and
released

Listeners for key events are created by implementing the
KeyListener interface

A KeyEvent object is passed to the appropriate method
when a key event occurs
158
CLH GUI slides
Key Events

The component that generates a key event is the one
that has the current keyboard focus

Constants in the KeyEvent class can be used to
determine which key was pressed

The following example "moves" an image of an arrow
as the user types the keyboard arrow keys

See Direction.java (page 421)
See DirectionPanel.java (page 422)

159
CLH GUI slides
The Direction Program
160
CLH GUI slides
The Timer Class

The Timer class of the javax.swing package is a GUI
component, but it has no visual representation

A Timer object generates an action event at specified
intervals

Timers can be used to manage any events that are
based on a timed interval, such as an animation

To create the illusion of movement, we use a timer to
change the scene after an appropriate delay
161
CLH GUI slides
The Timer Class

The start and stop methods of the Timer class start
and stop the timer

The delay can be set using the Timer constructor or
using the setDelay method

See Rebound.java (page 471)
See ReboundPanel.java (page 472)

162
CLH GUI slides
Animations

An animation is a constantly changing series of
pictures or images that create the illusion of movement

We can create animations in Java by changing a picture
slightly over time

The speed of a Java animation is usually controlled by
a Timer object
163
CLH GUI slides
The Rebound Program
164
CLH GUI slides
Animations

A Timer object generates and ActionEvent every n
milliseconds (where n is set by the object creator)

The ActionListener interface contains an
actionPerformed method

Whenever the timer expires (generating an
ActionEvent) the animation can be updated
165
CLH GUI slides
Outline Chapter 7
Polygons and Polylines
166
CLH GUI slides
Polygons and Polylines

Arrays can be helpful in graphics processing

For example, they can be used to store a list of
coordinates

A polygon is a multisided, closed shape

A polyline is similar to a polygon except that its
endpoints do not meet, and it cannot be filled

See Rocket.java (page 409)
See RocketPanel.java (page 410)

167
CLH GUI slides
The Polygon Class

The Polygon class can also be used to define and draw
a polygon

It is part of the java.awt pacakage

Versions of the overloaded drawPolygon and
fillPolygon methods take a single Polygon object
as a parameter instead of arrays of coordinates

A Polygon object encapsulates the coordinates of the
polygon
168
CLH GUI slides
GUI Design

We must remember that the goal of software is to help
the user solve the problem

To that end, the GUI designer should:


Know the user

Prevent user errors

Optimize user abilities

Be consistent
Let's discuss each of these in more detail
169
CLH GUI slides
Know the User

Knowing the user implies an understanding of:

the user's true needs

the user's common activities

the user's level of expertise in the problem
domain and in computer processing

We should also realize these issues may differ for
different users

Remember, to the user, the interface is the program
170
CLH GUI slides
Prevent User Errors

Whenever possible, we should design user interfaces
that minimize possible user mistakes. Automate as
much as possible by using components that limit the
number of choices.

We should choose the best GUI components for each
task

For example, in a situation where there are only a few
valid options, using a menu or radio buttons would be
better than an open text field

Error messages should guide the user appropriately
171
CLH GUI slides
Optimize User Abilities

Not all users are alike – some may be more familiar
with the system than others

Knowledgeable users are sometimes called power users

We should provide multiple ways to accomplish a task
whenever reasonable



"wizards" to walk a user through a process
short cuts for power users
Help facilities should be available but not intrusive
172
CLH GUI slides
Be Consistent

Consistency is important – users get used to things
appearing and working in certain ways

Colors should be used consistently to indicate similar
types of information or processing

Screen layout should be consistent from one part of a
system to another –

For example, error messages should appear in
consistent locations e.g. A JtextArea. This way the
user knows to look there if there is a problem
173
CLH GUI slides
Designing for Inheritance

As we've discussed, taking the time to create a good
software design reaps long-term benefits

Inheritance issues are an important part of an objectoriented design

Properly designed inheritance relationships can
contribute greatly to the elegance, maintainabilty, and
reuse of the software

Let's summarize some of the issues regarding
inheritance that relate to a good software design
174
CLH GUI slides
Inheritance Design Issues

Every derivation should be an is-a relationship

Think about the potential future of a class hierarchy,
and design classes to be reusable and flexible

Find common characteristics of classes and push
them as high in the class hierarchy as appropriate

Override methods as appropriate to tailor or change
the functionality of a child

Add new variables to children, but don't redefine
(shadow) inherited variables
175
CLH GUI slides
Inheritance Design Issues

Allow each class to manage its own data; use the
super reference to invoke the parent's constructor to
set up its data

Even if there are no current uses for them, override
general methods such as toString and equals with
appropriate definitions

Use abstract classes to represent general concepts that
lower classes have in common

Use visibility modifiers carefully to provide needed
access without violating encapsulation
176
CLH GUI slides
Restricting Inheritance

The final modifier can be used to curtail inheritance

If the final modifier is applied to a method, then that
method cannot be overridden in any descendent
classes

If the final modifier is applied to an entire class, then
that class cannot be used to derive any children at all


Thus, an abstract class cannot be declared as
final
These are key design decisions, establishing that a
method or class should be used as is
177
CLH GUI slides
The Component Class
Hierarchy

The Java classes that define GUI components are part
of a class hierarchy

Swing GUI components typically are derived from the
JComponent class which is derived from the
Container class which is derived from the
Component class

Many Swing components can serve as (limited)
containers, because they are derived from the
Container class

For example, a JLabel object can contain an
ImageIcon
178
CLH GUI slides
The Component Class
Hierarchy

An applet is a good example of inheritance

Recall that when we define an applet, we extend the
Applet class or the JApplet class

The Applet and JApplet classes already handle all
the details about applet creation and execution,
including:

interaction with a Web browser

accepting applet parameters through HTML

enforcing security restrictions
179
CLH GUI slides
The Component Class Hierarchy

Our applet classes only have to deal with issues that
specifically relate to what our particular applet will do

When we define paintComponent method of an
applet, we are actually overriding a method defined
originally in the JComponent class and inherited by
the JApplet class
180
CLH GUI slides
Event Processing

Polymorphism plays an important role in the
development of a Java graphical user interface

As we've seen, we establish a relationship between a
component and a listener:
JButton button = new JButton();
button.addActionListener(new MyListener());

Note that the addActionListener method is
accepting a MyListener object as a parameter

In fact, we can pass the addActionListener method
any object that implements the ActionListener
interface
181
CLH GUI slides
Event Processing

The source code for the addActionListener method
accepts a parameter of type ActionListener (the
interface)

Because of polymorphism, any object that implements
that interface is compatible with the parameter
reference variable

The component can call the actionPerformed
method because of the relationship between the
listener class and the interface

Extending an adapter class to create a listener
represents the same situation; the adapter class
implements the appropriate interface already
182
CLH GUI slides
Containment Hierarchies

The way components are grouped into containers and
the way those containers are nested within each other
establishes the containment hierarchy for the GUI

Each container can have its own layout manager

The appearance of a GUI is determined by:


the containment hierarchy

the layout manager of each container

the properties of individual components
All of these issues work together to determine the final
visual effect
183
CLH GUI slides
Containment Hierarchies
184
CLH GUI slides
Special Features

Swing components offer special features to facilitate
and enhance their use
Special Feature
Description
Tool tip
Causes a line of text to appear when the mouse
cursor pauses over a component
Mnemonic
Allows an action to occur in response to a
keyboard key combination
Disable
Allows a component to be explicitly enabled or
disabled
Border
Surrounds a component with a border
185
CLH GUI slides
Tool Tips

Tool tips provide a short pop-up description when the
mouse cursor rests momentarily on a component

A tool tip is assigned using the setToolTipText
method of a Swing component
JButton button = new JButton ("Compute");
button.setToolTipText ("Calculate size.");
186
CLH GUI slides
Mnemonics

A mnemonic provides a keyboard alternative for
pushing a button or selecting a menu option

The mnemonic character should be chosen from the
component's label, and is underlined

The user activates the component by holding down the
ALT key and pressing the mnemonic character

A mnemonic is established using the setMnemonic
method
JButton button = new JButton ("Calculate");
button.setMnemonic ("C");
187
CLH GUI slides
Disabled Components

Components can be disabled if they should not be used

A disabled component is "grayed out" and will not
respond to user interaction

The status is set using the setEnabled method:
JButton button = new JButton (“Do It”);
button.setEnabled (false);
188
CLH GUI slides
Special Features

The right combination of special features and
components can enhance the usefulness of a GUI

See LightBulb.java (page 530)

See LightBulbPanel.java (page 531)

See LightBulbControls.java (page 533)
189
CLH GUI slides
The LightBulb Program
190
CLH GUI slides
File Choosers

Situations often arise where we want the user to select
a file stored on a disk drive, usually so that its contents
can be read and processed

A file chooser, represented by the JFileChooser class,
simplifies this process

A file chooser is a specialized dialog box created using
the JFileChooser class

The user can browse the disk and filter the file types
displayed

See DisplayFile.java (page 516)
191
CLH GUI slides
The DisplayFile Program
192
CLH GUI slides
Color Choosers

In many situations we want to allow the user to select a
color

A color chooser , represented by the JColorChooser
class, simplifies this process

The user can choose a color from a palette or specify
the color using RGB values

A color can be selected using swatches or RGB values

See DisplayColor.java (page 519)
193
CLH GUI slides
The DisplayColor Program
194
CLH GUI slides
Scroll Panes

A scroll pane is useful for images or information too
large to fit in a reasonably-sized area

A scroll pane offers a limited view of the component it
contains

It provides vertical and/or horizontal scroll bars that
allow the user to scroll to other areas of the component

No event listener is needed for a scroll pane

See TransitMap.java (page 540)
195
CLH GUI slides
The TransitMap Program
196
CLH GUI slides
Split Panes

A split pane (JSplitPane) is a container that displays two
components separated by a moveable divider bar

The two components can be displayed side by side, or one on top of
the other
Moveable Divider Bar
Top Component
Left
Component
Right
Component
Bottom Component
197
CLH GUI slides
Split Panes

The orientation of the split pane is set using the
HORIZONTAL_SPLIT or VERTICAL_SPLIT constants

The divider bar can be set so that it can be fully
expanded with one click of the mouse

The components can be continuously adjusted as the
divider bar is moved, or wait until it stops moving

Split panes can be nested
198
CLH GUI slides
Lists

The Swing Jlist class represents a list of items from
which the user can choose

The contents of a JList object can be specified using
an array of objects

A JList object generates a list selection event when the
current selection changes

See PickImage.java (page 544)

See ListPanel.java (page 546)
199
CLH GUI slides
The PickImage Program
200
CLH GUI slides
Lists

A JList object can be set so that multiple items can be selected at
the same time

The list selection mode can be one of three options:




single selection – only one item can be selected at a
time
single interval selection – multiple, contiguous items
can be selected at a time
multiple interval selection – any combination of items
can be selected
The list selection mode is defined by a ListSelectionModel
object
201
CLH GUI slides
Sliders

A slider is a GUI component that allows the user to
specify a value within a numeric range

A slider can be oriented vertically or horizontally and
can have optional tick marks and labels

The minimum and maximum values for the slider are
set using the JSlider constructor

A slider produces a change event when the slider is
moved, indicating that the slider and the value it
represents has changed
202
CLH GUI slides
Sliders

The following example uses three sliders to change
values representing the color components of an RGB
value

See SlideColor.java (page 522)
See SlideColorPanel.java (page 523)

203
CLH GUI slides
The BorderDemo Program
204
CLH GUI slides
Borders

A border can be put around any Swing component to
define how the edges of the component should be
drawn

Borders can be used effectively to group components
visually

The BorderFactory class contains several static
methods for creating border objects

A border is applied to a component using the
setBorder method
205
CLH GUI slides
Borders



An empty border

buffers the space around the edge of a
component

otherwise has no visual effect
A line border

surrounds the component with a simple line

the line's color and thickness can be specified
An etched border

creates the effect of an etched groove around
a component

uses colors for the highlight and shadow
CLH GUI slides
206
Borders



A bevel border

can be raised or lowered

uses colors for the outer and inner
highlights and shadows
A titled border

places a title on or around the border

the title can be oriented in many ways
A matte border

specifies the sizes of the top, left, bottom,
and right edges of the border separately

uses either a solid color or an image
207
CLH GUI slides
Borders


A compound border

is a combination of two borders

one or both of the borders can be a compound
border
See BorderDemo.java (page 355)
208
CLH GUI slides
public static void main (String[] args)
{
JPanel panel = new JPanel();
panel.setLayout (new GridLayout (0, 2, 5, 10));
panel.setBorder (BorderFactory.createEmptyBorder (5, 5, 5, 5));
JPanel p1 = new JPanel();
p1.setBorder (BorderFactory.createLineBorder (Color.red, 3));
p1.add (new JLabel ("Line Border"));
panel.add (p1);
209
CLH GUI slides
JPanel p2 = new JPanel();
p2.setBorder (BorderFactory.createEtchedBorder ());
p2.add (new JLabel ("Etched Border"));
panel.add (p2);
JPanel p3 = new JPanel();
p3.setBorder (BorderFactory.createRaisedBevelBorder
());
p3.add (new JLabel ("Raised Bevel Border"));
panel.add (p3);
210
CLH GUI slides
JPanel p4 = new JPanel();
p4.setBorder
(BorderFactory.createLoweredBevelBorder ());
p4.add (new JLabel ("Lowered Bevel Border"));
panel.add (p4);
JPanel p5 = new JPanel();
p5.setBorder (BorderFactory.createTitledBorder
("Title"));
p5.add (new JLabel ("Titled Border"));
panel.add (p5);
211
CLH GUI slides
JPanel p6 = new JPanel();
TitledBorder tb = BorderFactory.createTitledBorder ("Title");
tb.setTitleJustification (TitledBorder.RIGHT);
p6.setBorder (tb);
p6.add (new JLabel ("Titled Border (right)"));
panel.add (p6);
JPanel p7 = new JPanel();
Border b1 = BorderFactory.createLineBorder (Color.blue, 2);
Border b2 = BorderFactory.createEtchedBorder ();
p7.setBorder (BorderFactory.createCompoundBorder (b1, b2));
p7.add (new JLabel ("Compound Border"));
panel.add (p7);
212
CLH GUI slides
JPanel p8 = new JPanel();
Border mb = BorderFactory.createMatteBorder (1, 5, 1,
1, Color.yellow);
p8.setBorder (mb);
p8.add (new JLabel ("Matte Border"));
panel.add (p8);
}
}
213
CLH GUI slides
Tiled Pictures

Consider the task of repeatedly displaying a set of
images in a mosaic


Three quadrants contain individual images
Upper-left quadrant repeats pattern

The base case is reached when the area for the images
shrinks to a certain size

See TiledPictures.java (page 594)
214
CLH GUI slides
Tiled Pictures
215
CLH GUI slides
Fractals

A fractal is a geometric shape made up of the same
pattern repeated in different sizes and orientations

The Koch Snowflake is a particular fractal that begins
with an equilateral triangle

To get a higher order of the fractal, the sides of the
triangle are replaced with angled line segments

See KochSnowflake.java (page 597)
See KochPanel.java (page 600)

216
CLH GUI slides
Koch Snowflakes
< x5 , y5 >
< x 5 , y5 >
< x 4 , y4 >
Becomes
< x3 , y 3 >
< x 2 , y2 >
< x1 , y1 >
< x 1 , y1 >
217
CLH GUI slides
Koch Snowflakes
218
CLH GUI slides
Koch Snowflakes
219
CLH GUI slides
The Component Class Hierarchy

The Java classes that define GUI components are part of a
class hierarchy

Swing GUI components typically are derived from the
JComponent class which is derived from the Container
class which is derived from the Component class

Many Swing components can serve as (limited) containers,
because they are derived from the Container class
220
CLH GUI slides
Graphics Class Hierarchy (Swing)
AWTEvent
Font
Classes in the java.awt
package
LayoutManager
1
Heavyweight
FontMetrics
Object
Color
Panel
Applet
JApplet
Window
Frame
JFrame
Dialog
JDialog
Graphics
Component
Container
*
Swing Components
in the javax.swing package
JComponent
Lightweight
221
CLH GUI slides
JComponent
.
JCheckBoxMenuItem
AbstractButton
JMenuItem
JMenu
JButton
.JRadioButtonMenuItem
.JToggleButton
JCheckBox
JRadioButton
.JEditorPane
JComponent
.JTextComponent
.JTextField
.JPasswordField
.JTextArea
.JLabel
.JList
.JComboBox
.JMenuBar
.JPanel
.JOptionPane
.JScrollBar
.JScrollPane
.JPopupMenu
.JSeparator
.JSlider
.JTabbedPane
.JRootPane
.JPane
.JProgressBar
.JToolBar
.JSplitPane
.JTable
.JTree
.JColorChooser
.JInternalFrame
.JToolTip
.JLayeredPane
.JTableHeader
.JFileChooser
222
CLH GUI slides
AWT (Optional)
AWTEvent
Font
FontMetrics
Object
Color
Graphics
Component
Container
Panel
Applet
Button
Window
Frame
Label
TextField
Dialog
FileDialog
TextComponent
List
TextArea
Choice
CheckBox
LayoutManager
CheckBoxGroup
Canvas
MenuComponent
Scrollbar
MenuItem
Menu
MenuBar
223
CLH GUI slides