Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Graphical User Interfaces
Java Software Solutions
Foundations of Program Design
Seventh Edition
Combination of a set of GUI related
slides from various chapters
Introduction to Graphics
• 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
Copyright © 2012 Pearson Education, Inc.
Representing Images
• A digitized picture with a small portion magnified:
Copyright © 2012 Pearson Education, Inc.
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)
40
112
X
(112, 40)
Y
Copyright © 2012 Pearson Education, Inc.
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
• 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
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
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 be
transported over the Web and executed using a
web browser
• An applet also can be executed using the
appletviewer tool of the Java SDK
• An applet doesn't have a main method
• Instead, there are several special methods that
serve specific purposes
Copyright © 2012 Pearson Education, Inc.
Applets
• The paint method is executed automatically
whenever the applet’s contents are drawn
• 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
Copyright © 2012 Pearson Education, Inc.
Applets
• We create an applet by extending the JApplet
class
• The JApplet class is part of the javax.swing
package
• This makes use of inheritance, which is explored in
more detail in Chapter 8
• See Einstein.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Einstein.java
Author: Lewis/Loftus
//
// Demonstrates a basic applet.
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class Einstein extends JApplet
{
//----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.
//----------------------------------------------------------------public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40);
// square
page.drawRect (60, 80, 225, 30);
// rectangle
page.drawOval (75, 65, 20, 20);
// circle
page.drawLine (35, 60, 100, 120); // line
page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Einstein.java
Author: Lewis/Loftus
//
// Demonstrates a basic applet.
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class Einstein extends JApplet
{
//----------------------------------------------------------------// Draws a quotation by Albert Einstein among some shapes.
//----------------------------------------------------------------public void paint (Graphics page)
{
page.drawRect (50, 50, 40, 40);
// square
page.drawRect (60, 80, 225, 30);
// rectangle
page.drawOval (75, 65, 20, 20);
// circle
page.drawLine (35, 60, 100, 120); // line
page.drawString ("Out of clutter, find simplicity.", 110, 70);
page.drawString ("-- Albert Einstein", 130, 100);
}
}
Copyright © 2012 Pearson Education, Inc.
The HTML applet Tag
• 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
<html>
<head>
<title>The Einstein Applet</title>
</head>
<body>
<applet code="Einstein.class" width=350 height=175>
</applet>
</body>
</html>
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Drawing a Line
10
150
X
20
45
Y
page.drawLine (10, 20, 150, 45);
or
page.drawLine (150, 45, 10, 20);
Copyright © 2012 Pearson Education, Inc.
Drawing a Rectangle
50
X
20
40
100
Y
page.drawRect (50, 20, 100, 40);
Copyright © 2012 Pearson Education, Inc.
Drawing an Oval
175
X
20
80
bounding
rectangle
Y
50
page.drawOval (175, 20, 50, 80);
Copyright © 2012 Pearson Education, Inc.
Drawing an Arc
• An arc is defined by an oval, a start angle, and an
arc angle:
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Snowman.java
Author: Lewis/Loftus
//
// Demonstrates basic drawing methods and the use of color.
//********************************************************************
import javax.swing.JApplet;
import java.awt.*;
public class Snowman extends JApplet
{
//----------------------------------------------------------------// Draws a snowman.
//----------------------------------------------------------------public void paint (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
continued
Copyright © 2012 Pearson Education, Inc.
continued
page.setColor
page.fillOval
page.fillOval
page.fillOval
(Color.white);
(MID-20, TOP, 40, 40);
(MID-35, TOP+35, 70, 50);
(MID-50, TOP+80, 100, 60);
page.setColor (Color.black);
page.fillOval (MID-10, TOP+10, 5, 5);
page.fillOval (MID+5, TOP+10, 5, 5);
// head
// upper torso
// lower torso
// left eye
// right eye
page.drawArc (MID-10, TOP+20, 20, 10, 190, 160);
// smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40);
page.drawLine (MID+25, TOP+60, MID+55, TOP+60);
// left arm
// 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
}
}
Copyright © 2012 Pearson Education, Inc.
continued
page.setColor
page.fillOval
page.fillOval
page.fillOval
(Color.white);
(MID-20, TOP, 40, 40);
(MID-35, TOP+35, 70, 50);
(MID-50, TOP+80, 100, 60);
page.setColor (Color.black);
page.fillOval (MID-10, TOP+10, 5, 5);
page.fillOval (MID+5, TOP+10, 5, 5);
// head
// upper torso
// lower torso
// left eye
// right eye
page.drawArc (MID-10, TOP+20, 20, 10, 190, 160);
// smile
page.drawLine (MID-25, TOP+60, MID-50, TOP+40);
page.drawLine (MID+25, TOP+60, MID+55, TOP+60);
// left arm
// 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
}
}
Copyright © 2012 Pearson Education, Inc.
Graphical Applications
• Except for the applets seen in Chapter 2, the
example programs we've explored thus far have
been text-based
• They are called command-line applications, which
interact with the user using simple text prompts
• 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)
Copyright © 2012 Pearson Education, Inc.
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 GUIbased program
Copyright © 2012 Pearson Education, Inc.
GUI Containers
• A GUI container is a component that is used to hold
and organize other components
• A frame is a container 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 (like a
frame or another panel) to be displayed
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Labels
• A label is a GUI component that displays a line of
text and/or an image
• Labels are usually used to display information or
identify other components in the interface
• Let's look at a program that organizes two labels in
a panel and displays that panel in a frame
• This program is not interactive, but the frame can
be repositioned and resized
• See Authority.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Authority.java
Author: Lewis/Loftus
//
// Demonstrates the use of frames, panels, and labels.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class Authority
{
//----------------------------------------------------------------// Displays some words of wisdom.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Authority");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
JPanel primary = new JPanel();
primary.setBackground (Color.yellow);
primary.setPreferredSize (new Dimension(250, 75));
continued
Copyright © 2012 Pearson Education, Inc.
continued
JLabel label1 = new JLabel ("Question authority,");
JLabel label2 = new JLabel ("but raise your hand first.");
primary.add (label1);
primary.add (label2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
continued
JLabel label1 = new JLabel ("Question authority,");
JLabel label2 = new JLabel ("but raise your hand first.");
primary.add (label1);
primary.add (label2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// NestedPanels.java
Author: Lewis/Loftus
//
// Demonstrates a basic componenet hierarchy.
//********************************************************************
import java.awt.*;
import javax.swing.*;
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);
JLabel label1 = new JLabel ("One");
subPanel1.add (label1);
continued
Copyright © 2012 Pearson Education, Inc.
continued
// Set up second subpanel
JPanel subPanel2 = new JPanel();
subPanel2.setPreferredSize (new Dimension(150, 100));
subPanel2.setBackground (Color.red);
JLabel label2 = new JLabel ("Two");
subPanel2.add (label2);
// Set up primary panel
JPanel primary = new JPanel();
primary.setBackground (Color.blue);
primary.add (subPanel1);
primary.add (subPanel2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
continued
// Set up second subpanel
JPanel subPanel2 = new JPanel();
subPanel2.setPreferredSize (new Dimension(150, 100));
subPanel2.setBackground (Color.red);
JLabel label2 = new JLabel ("Two");
subPanel2.add (label2);
// Set up primary panel
JPanel primary = new JPanel();
primary.setBackground (Color.blue);
primary.add (subPanel1);
primary.add (subPanel2);
frame.getContentPane().add(primary);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
Outline
Creating Objects
The String Class
The Random and Math Classes
Formatting Output
Enumerated Types
Wrapper Classes
Components and Containers
Images
Copyright © 2012 Pearson Education, Inc.
Images
• Images can be displayed in a Java program in
various ways
• As we've seen, a JLabel object can be used to
display a line of text
• It can also be used to display an image
• That is, a label can be composed of text, an image,
or both at the same time
Copyright © 2012 Pearson Education, Inc.
Images
• The ImageIcon class is used to represent the
image that is stored in a label
• If text is also included, the position of the text
relative to the image can be set explicitly
• The alignment of the text and image within the
label can be set as well
• See LabelDemo.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// LabelDemo.java
Author: Lewis/Loftus
//
// Demonstrates the use of image icons in labels.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class LabelDemo
{
//----------------------------------------------------------------// Creates and displays the primary application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Label Demo");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
ImageIcon icon = new ImageIcon ("devil.gif");
JLabel label1, label2, label3;
label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);
continued
Copyright © 2012 Pearson Education, Inc.
continued
label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);
label2.setHorizontalTextPosition (SwingConstants.LEFT);
label2.setVerticalTextPosition (SwingConstants.BOTTOM);
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);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
continued
label2 = new JLabel ("Devil Right", icon, SwingConstants.CENTER);
label2.setHorizontalTextPosition (SwingConstants.LEFT);
label2.setVerticalTextPosition (SwingConstants.BOTTOM);
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);
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
Graphical User Interfaces
• A Graphical User Interface (GUI) in Java is created
with at least three kinds of objects:
– components, events, and listeners
• We've previously discussed components, which are
objects that represent screen elements:
– labels, buttons, text fields, menus, etc.
• Some components are containers that hold and
organize other components:
– frames, panels, applets, dialog boxes
Copyright © 2012 Pearson Education, Inc.
Events
• An event is an object that represents some activity
to which we may want to respond
• For example, we may want our program to perform
some action when the following occurs:
–
–
–
–
–
–
the mouse is moved
the mouse is dragged
a mouse button is clicked
a graphical button is pressed
a keyboard key is pressed
a timer expires
Copyright © 2012 Pearson Education, Inc.
Events and Listeners
• The Java API contains several classes that
represent typical events
• Components, such as a graphical button, generate
(or fire) an event when it occurs
• We set up a listener object to respond to an event
when it occurs
• We can design listener objects to take whatever
actions are appropriate when an event occurs
Copyright © 2012 Pearson Education, Inc.
Events and Listeners
Event
Component
Listener
A component object
generates an event
A corresponding listener
object is designed to
respond to the event
When the event occurs, the component calls
the appropriate method of the listener,
passing an object that describes the event
Copyright © 2012 Pearson Education, Inc.
GUI Development
• 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
the components that generate the corresponding
events
• Let's now explore some new components and see
how this all comes together
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// GridPanel.java
Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the grid layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
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);
continue
Copyright © 2012 Pearson Education, Inc.
Buttons
• 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
• See PushCounterPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// PushCounter.java
Authors: Lewis/Loftus
//
// Demonstrates a graphical user interface and an event listener.
//********************************************************************
import javax.swing.JFrame;
public class PushCounter
{
//----------------------------------------------------------------// Creates the main program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Push Counter");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new PushCounterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// PushCounter.java
Authors: Lewis/Loftus
//
// Demonstrates a graphical user interface and an event listener.
//********************************************************************
import javax.swing.JFrame;
public class PushCounter
{
//----------------------------------------------------------------// Creates the main program frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Push Counter");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new PushCounterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// PushCounterPanel.java
Authors: Lewis/Loftus
//
// Demonstrates a graphical user interface and an event listener.
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class PushCounterPanel extends JPanel
{
private int count;
private JButton push;
private JLabel label;
//----------------------------------------------------------------// Constructor: Sets up the GUI.
//----------------------------------------------------------------public PushCounterPanel ()
{
count = 0;
push = new JButton ("Push Me!");
push.addActionListener (new ButtonListener());
continue
Copyright © 2012 Pearson Education, Inc.
continue
label = new JLabel ("Pushes: " + count);
add (push);
add (label);
setPreferredSize (new Dimension(300, 40));
setBackground (Color.cyan);
}
//*****************************************************************
// Represents a listener for button push (action) events.
//*****************************************************************
private class ButtonListener implements ActionListener
{
//-------------------------------------------------------------// Updates the counter and label when the button is pushed.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
count++;
label.setText("Pushes: " + count);
}
}
}
Copyright © 2012 Pearson Education, Inc.
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 PushCounterPanel class represents the
panel used to display the button and label
• The PushCounterPanel class is derived from
JPanel using inheritance
• The constructor of PushCounterPanel sets up
the elements of the GUI and initializes the counter
to zero
Copyright © 2012 Pearson Education, Inc.
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
• That facilitates the communication between the
listener and the GUI components
• Inner classes should only be used in situations
where there is an intimate relationship between the
two classes and the inner class is not needed in any
other context
Copyright © 2012 Pearson Education, Inc.
Push Counter Example
• Listener classes are written by implementing a
listener interface
• The ButtonListener class implements the
ActionListener interface
• An interface is a list of methods that the
implementing class must define
• The only method in the ActionListener interface
is the actionPerformed method
• The Java API contains interfaces for many types of
events
• We discuss interfaces in more detail in Chapter 6
Copyright © 2012 Pearson Education, Inc.
Push Counter Example
• The PushCounterPanel constructor:
– instantiates the ButtonListener object
– establishes the relationship between the button and the
listener by the call to addActionListener
• When the user presses the button, the button
component creates an ActionEvent object and
calls the actionPerformed method of the listener
• The actionPerformed method increments the
counter and resets the text of the label
Copyright © 2012 Pearson Education, Inc.
Quick Check
Which object in the Push Counter example generated
the event?
What did it do then?
Copyright © 2012 Pearson Education, Inc.
Quick Check
Which object in the Push Counter example generated
the event?
The button component generated the event.
What did it do then?
It called the actionPerformed method of the
listener object that had been registered with it.
Copyright © 2012 Pearson Education, Inc.
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 object
generates an action event when the enter key is
pressed
• See Fahrenheit.java
• See FahrenheitPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Fahrenheit.java
Author: Lewis/Loftus
//
// Demonstrates the use of text fields.
//********************************************************************
import javax.swing.JFrame;
public class Fahrenheit
{
//----------------------------------------------------------------// Creates and displays the temperature converter GUI.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Fahrenheit.java
Author: Lewis/Loftus
//
// Demonstrates the use of text fields.
//********************************************************************
import javax.swing.JFrame;
public class Fahrenheit
{
//----------------------------------------------------------------// Creates and displays the temperature converter GUI.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Fahrenheit");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
FahrenheitPanel panel = new FahrenheitPanel();
frame.getContentPane().add(panel);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// FahrenheitPanel.java
Author: Lewis/Loftus
//
// Demonstrates the use of text fields.
//********************************************************************
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class FahrenheitPanel extends JPanel
{
private JLabel inputLabel, outputLabel, resultLabel;
private JTextField fahrenheit;
//----------------------------------------------------------------// Constructor: Sets up the main GUI components.
//----------------------------------------------------------------public FahrenheitPanel()
{
inputLabel = new JLabel ("Enter Fahrenheit temperature:");
outputLabel = new JLabel ("Temperature in Celsius: ");
resultLabel = new JLabel ("---");
fahrenheit = new JTextField (5);
fahrenheit.addActionListener (new TempListener());
continue
Copyright © 2012 Pearson Education, Inc.
continue
add
add
add
add
(inputLabel);
(fahrenheit);
(outputLabel);
(resultLabel);
setPreferredSize (new Dimension(300, 75));
setBackground (Color.yellow);
}
//*****************************************************************
// Represents an action listener for the temperature input field.
//*****************************************************************
private class TempListener implements ActionListener
{
//-------------------------------------------------------------// Performs the conversion when the enter key is pressed in
// the text field.
//-------------------------------------------------------------public void actionPerformed (ActionEvent event)
{
int fahrenheitTemp, celsiusTemp;
String text = fahrenheit.getText();
continue
Copyright © 2012 Pearson Education, Inc.
continue
fahrenheitTemp = Integer.parseInt (text);
celsiusTemp = (fahrenheitTemp-32) * 5/9;
resultLabel.setText (Integer.toString (celsiusTemp));
}
}
}
Copyright © 2012 Pearson Education, Inc.
Other GUI Elements
• Radio boxes and check boxes (Chapter 5)
• Dialog boxes (Chapter 6)
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Prevent User Errors
• Whenever possible, we should design user
interfaces that minimize possible user mistakes
• 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
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
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 API:
Flow Layout
Border Layout
Card Layout
Grid Layout
GridBag Layout
Defined in the AWT
Box Layout
Overlay Layout
Defined in Swing
Copyright © 2012 Pearson Education, Inc.
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 adjusts the layout as components
are added and as containers are resized
Copyright © 2012 Pearson Education, Inc.
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
• See IntroPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// LayoutDemo.java
Authors: Lewis/Loftus
//
// Demonstrates the use of flow, border, grid, and box layouts.
//********************************************************************
import javax.swing.*;
public class LayoutDemo
{
//----------------------------------------------------------------// Sets up a frame containing a tabbed pane. The panel on each
// tab demonstrates a different layout manager.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Layout Manager Demo");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
continue
Copyright © 2012 Pearson Education, Inc.
continue
JTabbedPane tp = new JTabbedPane();
tp.addTab ("Intro", new IntroPanel());
tp.addTab ("Flow", new FlowPanel());
tp.addTab ("Border", new BorderPanel());
tp.addTab ("Grid", new GridPanel());
tp.addTab ("Box", new BoxPanel());
frame.getContentPane().add(tp);
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// IntroPanel.java
Authors: Lewis/Loftus
//
// Represents the introduction panel for the LayoutDemo program.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class IntroPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with two labels.
//----------------------------------------------------------------public IntroPanel()
{
setBackground (Color.green);
JLabel l1 = new JLabel ("Layout Manager Demonstration");
JLabel l2 = new JLabel ("Choose a tab to see an example of " +
"a layout manager.");
add (l1);
add (l2);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// IntroPanel.java
Authors: Lewis/Loftus
//
// Represents the introduction panel for the LayoutDemo program.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class IntroPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with two labels.
//----------------------------------------------------------------public IntroPanel()
{
setBackground (Color.green);
JLabel l1 = new JLabel ("Layout Manager Demonstration");
JLabel l2 = new JLabel ("Choose a tab to see an example of " +
"a layout manager.");
add (l1);
add (l2);
}
}
Copyright © 2012 Pearson Education, Inc.
Flow Layout
• Flow layout puts as many components as possible
on a row, then moves to the next row
• Components are displayed in the order they are
added to the container
• Each row of components is centered horizontally by
default, but could also be aligned left or right
• The horizontal and vertical gaps between the
components can be explicitly set
• See FlowPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// FlowPanel.java
Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the flow layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
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);
continue
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(b2);
(b3);
(b4);
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(b2);
(b3);
(b4);
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
Border Layout
• A border layout defines five areas into which
components can be added
North
West
Center
East
South
Copyright © 2012 Pearson Education, Inc.
Border Layout
• Each area displays one component (which could be
a 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
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// BorderPanel.java
Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the border layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
public class BorderPanel extends JPanel
{
//----------------------------------------------------------------// Sets up this panel with a button in each area of a border
// layout to show how it affects their position, shape, and size.
//----------------------------------------------------------------public BorderPanel()
{
setLayout (new BorderLayout());
setBackground (Color.green);
continue
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
(b1,
(b2,
(b3,
(b4,
(b5,
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
BorderLayout.CENTER);
BorderLayout.NORTH);
BorderLayout.SOUTH);
BorderLayout.EAST);
BorderLayout.WEST);
}
}
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
(b1,
(b2,
(b3,
(b4,
(b5,
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
BorderLayout.CENTER);
BorderLayout.NORTH);
BorderLayout.SOUTH);
BorderLayout.EAST);
BorderLayout.WEST);
}
}
Copyright © 2012 Pearson Education, Inc.
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
• Components fill the grid from left-to-right and topto-bottom (by default)
• The size of each cell is determined by the overall
size of the container
• See GridPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// GridPanel.java
Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the grid layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
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);
continue
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(b2);
(b3);
(b4);
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(b2);
(b3);
(b4);
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// BoxPanel.java
Authors: Lewis/Loftus
//
// Represents the panel in the LayoutDemo program that demonstrates
// the box layout manager.
//********************************************************************
import java.awt.*;
import javax.swing.*;
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);
continue
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(Box.createRigidArea (new Dimension (0, 10)));
(b2);
(Box.createVerticalGlue());
(b3);
(b4);
(Box.createRigidArea (new Dimension (0, 20)));
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
continue
JButton
JButton
JButton
JButton
JButton
add
add
add
add
add
add
add
add
b1
b2
b3
b4
b5
=
=
=
=
=
new
new
new
new
new
JButton
JButton
JButton
JButton
JButton
("BUTTON
("BUTTON
("BUTTON
("BUTTON
("BUTTON
1");
2");
3");
4");
5");
(b1);
(Box.createRigidArea (new Dimension (0, 10)));
(b2);
(Box.createVerticalGlue());
(b3);
(b4);
(Box.createRigidArea (new Dimension (0, 20)));
(b5);
}
}
Copyright © 2012 Pearson Education, Inc.
Other GUI Elements
• Borders (Chapter 7)
Copyright © 2012 Pearson Education, Inc.
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
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
Copyright © 2012 Pearson Education, Inc.
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
• See DotsPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Dots.java
Author: Lewis/Loftus
//
// Demonstrates mouse events.
//********************************************************************
import javax.swing.JFrame;
public class Dots
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Dots");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new DotsPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Dots.java
Author: Lewis/Loftus
//
// Demonstrates mouse events.
//********************************************************************
import javax.swing.JFrame;
public class Dots
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Dots");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new DotsPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// DotsPanel.java
Author: Lewis/Loftus
//
// Represents the primary panel for the Dots program.
//********************************************************************
import
import
import
import
java.util.ArrayList;
javax.swing.JPanel;
java.awt.*;
java.awt.event.*;
public class DotsPanel extends JPanel
{
private final int SIZE = 6; // radius of each dot
private ArrayList<Point> pointList;
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Constructor: Sets up this panel to listen for mouse events.
//----------------------------------------------------------------public DotsPanel()
{
pointList = new ArrayList<Point>();
addMouseListener (new DotsListener());
setBackground (Color.black);
setPreferredSize (new Dimension(300, 200));
}
//----------------------------------------------------------------// Draws all of the dots stored in the list.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent(page);
page.setColor (Color.green);
for (Point spot : pointList)
page.fillOval (spot.x-SIZE, spot.y-SIZE, SIZE*2, SIZE*2);
page.drawString ("Count: " + pointList.size(), 5, 15);
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//*****************************************************************
// Represents the listener for mouse events.
//*****************************************************************
private class DotsListener implements MouseListener
{
//-------------------------------------------------------------// Adds the current point to the list of points and redraws
// the panel whenever the mouse button is pressed.
//-------------------------------------------------------------public void mousePressed (MouseEvent event)
{
pointList.add(event.getPoint());
repaint();
}
//-------------------------------------------------------------// Provide empty definitions for unused event methods.
//-------------------------------------------------------------public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
}
}
Copyright © 2012 Pearson Education, Inc.
Mouse Events
• Rubberbanding is the visual effect in which a shape
is "stretched" as it is drawn using the mouse
• The following example continually redraws a line as
the mouse is dragged
• See RubberLines.java
• See RubberLinesPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// RubberLines.java
Author: Lewis/Loftus
//
// Demonstrates mouse events and rubberbanding.
//********************************************************************
import javax.swing.JFrame;
public class RubberLines
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Rubber Lines");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new RubberLinesPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// RubberLines.java
Author: Lewis/Loftus
//
// Demonstrates mouse events and rubberbanding.
//********************************************************************
import javax.swing.JFrame;
public class RubberLines
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Rubber Lines");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new RubberLinesPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// RubberLinesPanel.java
Author: Lewis/Loftus
//
// Represents the primary drawing panel for the RubberLines program.
//********************************************************************
import javax.swing.JPanel;
import java.awt.*;
import java.awt.event.*;
public class RubberLinesPanel extends JPanel
{
private Point point1 = null, point2 = null;
//----------------------------------------------------------------// Constructor: Sets up this panel to listen for mouse events.
//----------------------------------------------------------------public RubberLinesPanel()
{
LineListener listener = new LineListener();
addMouseListener (listener);
addMouseMotionListener (listener);
setBackground (Color.black);
setPreferredSize (new Dimension(400, 200));
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Draws the current line from the initial mouse-pressed point to
// the current position of the mouse.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor (Color.yellow);
if (point1 != null && point2 != null)
page.drawLine (point1.x, point1.y, point2.x, point2.y);
}
//*****************************************************************
// Represents the listener for all mouse events.
//*****************************************************************
private class LineListener implements MouseListener, MouseMotionListener
{
//-------------------------------------------------------------// Captures the initial position at which the mouse button is
// pressed.
//-------------------------------------------------------------public void mousePressed (MouseEvent event)
{
point1 = event.getPoint();
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//-------------------------------------------------------------// Gets the current position of the mouse as it is dragged and
// redraws the line to create the rubberband effect.
//-------------------------------------------------------------public void mouseDragged (MouseEvent event)
{
point2 = event.getPoint();
repaint();
}
//-------------------------------------------------------------// Provide empty definitions for unused event methods.
//-------------------------------------------------------------public void mouseClicked (MouseEvent event) {}
public void mouseReleased (MouseEvent event) {}
public void mouseEntered (MouseEvent event) {}
public void mouseExited (MouseEvent event) {}
public void mouseMoved (MouseEvent event) {}
}
}
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
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
• See DirectionPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Direction.java
Author: Lewis/Loftus
//
// Demonstrates key events.
//********************************************************************
import javax.swing.JFrame;
public class Direction
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Direction");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new DirectionPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// Direction.java
Author: Lewis/Loftus
//
// Demonstrates key events.
//********************************************************************
import javax.swing.JFrame;
public class Direction
{
//----------------------------------------------------------------// Creates and displays the application frame.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Direction");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add (new DirectionPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// DirectionPanel.java
Author: Lewis/Loftus
//
// Represents the primary display panel for the Direction program.
//********************************************************************
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class DirectionPanel extends JPanel
{
private final int WIDTH = 300, HEIGHT = 200;
private final int JUMP = 10; // increment for image movement
private final int IMAGE_SIZE = 31;
private ImageIcon up, down, right, left, currentImage;
private int x, y;
continue
Copyright © 2012 Pearson Education, Inc.
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
• See DirectionPanel.java
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Constructor: Sets up this panel and loads the images.
//----------------------------------------------------------------public DirectionPanel()
{
addKeyListener (new DirectionListener());
x = WIDTH / 2;
y = HEIGHT / 2;
up = new ImageIcon ("arrowUp.gif");
down = new ImageIcon ("arrowDown.gif");
left = new ImageIcon ("arrowLeft.gif");
right = new ImageIcon ("arrowRight.gif");
currentImage = right;
setBackground (Color.black);
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setFocusable(true);
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Draws the image in the current location.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
currentImage.paintIcon (this, page, x, y);
}
//*****************************************************************
// Represents the listener for keyboard activity.
//*****************************************************************
private class DirectionListener implements KeyListener
{
//-------------------------------------------------------------// Responds to the user pressing arrow keys by adjusting the
// image and image location accordingly.
//-------------------------------------------------------------public void keyPressed (KeyEvent event)
{
switch (event.getKeyCode())
{
case KeyEvent.VK_UP:
currentImage = up;
y -= JUMP;
break;
continue
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Partial Component Class Hierarchy
Copyright © 2012 Pearson Education, Inc.
The Component Class Hierarchy
• An applet is another good example of inheritance
• Recall that when we define an applet, we extend
the JApplet class
• The JApplet class already handles all the details
about applet creation and execution, including:
– interaction with a Web browser
– accepting applet parameters through HTML
– enforcing security restrictions
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Event Adapter Classes
• Inheritance also gives us a alternate technique for
creating listener classes
• We've seen that listener classes can be created by
implementing a particular interface, such as
MouseListener
• We can also create a listener class by extending an
event adapter class
• If a listener interface has more than one method, it
has a corresponding adapter class, such as the
MouseAdapter class
Copyright © 2012 Pearson Education, Inc.
Event Adapter Classes
• Each adapter class implements the corresponding
listener, providing 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 are
automatically provided via inheritance
• See OffCenter.java
• See OffCenterPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenter.java
Author: Lewis/Loftus
//
// Demonstrates the use of an event adapter class.
//********************************************************************
import javax.swing.*;
public class OffCenter
{
//----------------------------------------------------------------// Creates the main frame of the program.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Off Center");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new OffCenterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenter.java
Author: Lewis/Loftus
//
// Demonstrates the use of an event adapter class.
//********************************************************************
import javax.swing.*;
public class OffCenter
{
//----------------------------------------------------------------// Creates the main frame of the program.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Off Center");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new OffCenterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenterPanel.java
Author: Lewis/Loftus
//
// Represents the primary drawing panel for the OffCenter program.
//********************************************************************
import
import
import
import
java.awt.*;
java.awt.event.*;
java.text.DecimalFormat;
javax.swing.*;
public class OffCenterPanel extends JPanel
{
private final int WIDTH=300, HEIGHT=300;
private
private
private
private
DecimalFormat fmt;
Point current;
int centerX, centerY;
double length;
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Constructor: Sets up the panel and necessary data.
//----------------------------------------------------------------public OffCenterPanel()
{
addMouseListener (new OffCenterListener());
centerX = WIDTH / 2;
centerY = HEIGHT / 2;
fmt = new DecimalFormat ("0.##");
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.yellow);
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Draws a line from the mouse pointer to the center point of
// the applet and displays the distance.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor (Color.black);
page.drawOval (centerX-3, centerY-3, 6, 6);
if (current != null)
{
page.drawLine (current.x, current.y, centerX, centerY);
page.drawString ("Distance: " + fmt.format(length), 10, 15);
}
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//*****************************************************************
// Represents the listener for mouse events. Demonstrates the
// ability to extend an adaptor class.
//*****************************************************************
private class OffCenterListener extends MouseAdapter
{
//-------------------------------------------------------------// Computes the distance from the mouse pointer to the center
// point of the applet.
//-------------------------------------------------------------public void mouseClicked (MouseEvent event)
{
current = event.getPoint();
length = Math.sqrt(Math.pow((current.x-centerX), 2) +
Math.pow((current.y-centerY), 2));
repaint();
}
}
}
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Partial Component Class Hierarchy
Copyright © 2012 Pearson Education, Inc.
The Component Class Hierarchy
• An applet is another good example of inheritance
• Recall that when we define an applet, we extend
the JApplet class
• The JApplet class already handles all the details
about applet creation and execution, including:
– interaction with a Web browser
– accepting applet parameters through HTML
– enforcing security restrictions
Copyright © 2012 Pearson Education, Inc.
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
Copyright © 2012 Pearson Education, Inc.
Event Adapter Classes
• Inheritance also gives us a alternate technique for
creating listener classes
• We've seen that listener classes can be created by
implementing a particular interface, such as
MouseListener
• We can also create a listener class by extending an
event adapter class
• If a listener interface has more than one method, it
has a corresponding adapter class, such as the
MouseAdapter class
Copyright © 2012 Pearson Education, Inc.
Event Adapter Classes
• Each adapter class implements the corresponding
listener, providing 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 are
automatically provided via inheritance
• See OffCenter.java
• See OffCenterPanel.java
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenter.java
Author: Lewis/Loftus
//
// Demonstrates the use of an event adapter class.
//********************************************************************
import javax.swing.*;
public class OffCenter
{
//----------------------------------------------------------------// Creates the main frame of the program.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Off Center");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new OffCenterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenter.java
Author: Lewis/Loftus
//
// Demonstrates the use of an event adapter class.
//********************************************************************
import javax.swing.*;
public class OffCenter
{
//----------------------------------------------------------------// Creates the main frame of the program.
//----------------------------------------------------------------public static void main (String[] args)
{
JFrame frame = new JFrame ("Off Center");
frame.setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
frame.getContentPane().add(new OffCenterPanel());
frame.pack();
frame.setVisible(true);
}
}
Copyright © 2012 Pearson Education, Inc.
//********************************************************************
// OffCenterPanel.java
Author: Lewis/Loftus
//
// Represents the primary drawing panel for the OffCenter program.
//********************************************************************
import
import
import
import
java.awt.*;
java.awt.event.*;
java.text.DecimalFormat;
javax.swing.*;
public class OffCenterPanel extends JPanel
{
private final int WIDTH=300, HEIGHT=300;
private
private
private
private
DecimalFormat fmt;
Point current;
int centerX, centerY;
double length;
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Constructor: Sets up the panel and necessary data.
//----------------------------------------------------------------public OffCenterPanel()
{
addMouseListener (new OffCenterListener());
centerX = WIDTH / 2;
centerY = HEIGHT / 2;
fmt = new DecimalFormat ("0.##");
setPreferredSize (new Dimension(WIDTH, HEIGHT));
setBackground (Color.yellow);
}
continue
Copyright © 2012 Pearson Education, Inc.
continue
//----------------------------------------------------------------// Draws a line from the mouse pointer to the center point of
// the applet and displays the distance.
//----------------------------------------------------------------public void paintComponent (Graphics page)
{
super.paintComponent (page);
page.setColor (Color.black);
page.drawOval (centerX-3, centerY-3, 6, 6);
if (current != null)
{
page.drawLine (current.x, current.y, centerX, centerY);
page.drawString ("Distance: " + fmt.format(length), 10, 15);
}
}
continue
Copyright © 2012 Pearson Education, Inc.
Other GUI Elements
• File choosers (Chapter 10)
• Color choosers (Chapter 10)
• Sliders (Chapter 10)
Copyright © 2012 Pearson Education, Inc.
Other GUI Elements
• Scroll panes (Chapter 11)
• Split panes (Chapter 11)
Copyright © 2012 Pearson Education, Inc.