CLH GUI slides 1 1052 Series for Graphics Graphics, Applets Graphical User Interfaces.
-
Upload
marilyn-riley -
Category
Documents
-
view
227 -
download
0
Transcript of CLH GUI slides 1 1052 Series for Graphics Graphics, Applets Graphical User Interfaces.
CLH GUI slides1
1052 Series for Graphics
Graphics, Applets
Graphical User Interfaces
CLH GUI slides2
Outline - Chapter 2
Graphics
Applets
Drawing Shapes
CLH GUI slides3
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
CLH GUI slides4
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
Y
X(0, 0)
(112, 40)
112
40
CLH GUI slides5
The Coordinate System
<0, 0>
<x, y>
<width-1, height-1>
x
y
Y
X
CLH GUI slides6
Outline
Graphics
Applets
Drawing Shapes
CLH GUI slides7
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
CLH GUI slides8
Applets
A applet is typically embedded in a Web page and can be run from a browser.
You need a special HTML in the Web page to tell the browser about the applet.
CLH GUI slides9
Applets The class that defines an applet extends the JApplet class
An applet is embedded into an HTML file using a tag that references the bytecode version 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 on the receiving site
CLH GUI slides10
HTML
<html> <head> <title> Hi World Applet </title> </head>
<body> <applet code="HiWorld.class” width=300 height=200> </applet> </body></html>
CLH GUI slides11
The HTML applet Tag
<html>
<head><title>The Einstein Applet</title></head>
<body><applet code="Einstein.class" </applet></body>
</html>
CLH GUI slides12
Java Applets
Java sourcecode
Javabytecode
Javacompiler
Javainterpreter
Web browser
local computer
remotecomputer
Changing bytecode to machine code
When the bytecode is sent to another computer over the web,
that computer’s browser will interpret the bytecode with a java compiler on its computer
change it to the machine code of that computer.
This allows applets to used on both MACS and Windows machines and Unix servers
CLH GUI slides13
CLH GUI slides14
Drawing Shapes 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
CLH GUI slides15
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);
CLH GUI slides16
Drawing a Line
X
Y
10
20
150
45
page.drawLine (10, 20, 150, 45);
page.drawLine (150, 45, 10, 20);
or
CLH GUI slides17
Drawing a Rectangle
X
Y page.drawRect (50, 20, 100, 40);
Where 50,20 are the x and y values whereThe rectangle will start100 is the width40 is the length
50
20
100
40
CLH GUI slides18
Drawing an Oval
X
Y
page.drawOval (175, 20, 50, 80);We give values for the bounding rectangle –Start the left side of oval at 175,20
175
20
50
80
boundingrectangle
CLH GUI slides19
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
Applet Started
Parking
Appletviewer : No_Parking Class
CLH GUI slides20
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)
CLH GUI slides21
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
CLH GUI slides22
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
Color.blackColor.blueColor.cyanColor.orangeColor.whiteColor.yellow
RGB Value
0, 0, 00, 0, 2550, 255, 255255, 200, 0255, 255, 255255, 255, 0
CLH GUI slides23
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
CLH GUI slides24
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); // brim of hat
page.fillRect (MID-15, TOP-20, 30, 25); // top of hat
}
}
CLH GUI slides25
Snowman Applet
CLH GUI slides26
Applet methods
public void init ()
public void start ()
public void stop ()
public void destroy ()
public void paint (Graphics g)
The paint method is executed automatically when the applet is loaded
The paint method accepts a parameter that is an object of the Graphics class.
It is used to draw shapes and text e.g page.drawRect(x, y, width, width)
CLH GUI slides27
CLH GUI slides28
Why an applet works
You write an applet by extending the class JApplet.
CLH GUI slides29
public void init ( ) Invoked when the applet is first loaded and again
if the applet is reloaded.
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.
Even if you do not use it, it is called anyway
CLH GUI slides30
The init() Method
Other Common functions implemented in this method are:
creating threads,
loading images,
reading images from a file. Init is similar to a constructor in an application
CLH GUI slides31
public void start ( )
Not always needed
Automocatically 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( )
CLH GUI slides32
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.
CLH GUI slides33
public void destroy( ) Seldom needed
Called after stop( )
Use to explicitly release system resources (like threads)
System resources are usually released automatically
CLH GUI slides34
Applet flow of control
CLH GUI slides35
Browser Calling Applet Methods
CLH GUI slides36
public void paint(Graphics g)
Do drawing here.
WE call fillboard () and other methods in paint.
If you want to repaint some image:
Don’t call this paint directlyDon’t call this paint directly. It’s called automatically.
Call repaint( ) instead.
CLH GUI slides37
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.
CLH GUI slides38
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 easily if at al in an applet such as writing to a file.
CLH GUI slides39
Graphical User Interfaces - GUI’s
A GUI in Java is created with at least three kinds of objects:
Components - textfields, buttons
Events - a button is pressed
Listeners - react to the event
CLH GUI slides40
Graphical Applications
These components will serve as a foundation for programs that USE graphical user interfaces (GUIs)
CLH GUI slides41
GUI Components
A GUI component is an object that
represents a screen element such as
a button or a text field
CLH GUI slides42
GUI Containers
A GUI is a container that is used to hold and organize other components e.g.
Containers include:
Panels
Frames
dialog boxes
A Container holding components
43
CLH GUI slides44
Containers
A frame is a container that is used to display a GUI-based 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
CLH GUI slides45
THE FRAME HOLDS THE PANEL OF IMAGES AND DISPLAYS THE NAME OF THE PROGRAM
CLH GUI slides46
Containers and Components
A GUI container can be classified as either heavyweight or lightweight
A lightweight container is managed by the Java program itself
A frame is a heavyweight container and a panel is a lightweight container
CLH GUI slides47
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 set up.
establish the relationship between listeners and components
CLH GUI slides48
Some types of components
CLH GUI slides49
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…
CLH GUI slides50
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);
51
Labels
A label is a GUI component that displays a line of text
Labels are 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
CLH GUI slides52
A LABEL WITH IMAGES AND TEXT
CLH GUI slides53
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
CLH GUI slides54
Image Icons An Imageicon object represents an image
ImageIcon are either JPEG or GIF images
A JLabel can contain a String, or ImageIcon, or both
The orientation of the label's text and image can be set explicitly
CLH GUI slides55
The LabelDemo Program
56
public class LabelDemo{ //-------------------------------------------------- // Creates and displays three labels //--------------------------------------------- public static void main (String[] args) { ImageIcon icon = new ImageIcon ("devil.gif");
// 3 LABELS of class Jlabel JLabel label1, label2, label3;
// put label in the middle of A panel label1 = new JLabel ("Devil Left", icon, SwingConstants.CENTER);
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);57
CLH GUI slides58
//Create a Panel and put the three labels on it
JPanel panel = new JPanel(); // HOLDS THE LABELS
panel.setBackground (Color.cyan); panel.setPreferredSize (new Dimension (200, 250)); panel.add (label1); // ADD EACH LABEL TO THE PANEL panel.add (label2); panel.add (label3);
// get the container to put the panel on Container c = getContentPane();c.add(panel); // add the panel to the CONTAINER
}
CLH GUI slides59
The LabelDemo Program
CLH GUI slides60
GUI Elements - Events
An An event is an object event is an object that represents some that represents some interaction with the user. interaction with the user.
E.g. pressing a button in Dating Service selecting an option from checkbox
CLH GUI slides61
Events
• 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
• .
CLH GUI slides62
Making components active
Most components appear to do something—
buttons click, text appears
To associate an particular action with a component, we
attach a listener to it
Buttons fire events
Components fire events,
e.g. a button is pressed
listeners listen for events
CLH GUI slides63
Listeners
Different components may fire different events, and require different listeners
A listener is an object that is “waiting for an event to occur” and
we code what we want it to do when an event occurs
CLH GUI slides64
CLH GUI slides65
Listeners
Listeners are interfaces, the class below implements The ActionListener interface
class ButtonListener implements ActionListener
ActionListener Interface with one method:
public void ActionPerformed(Event e);
CLH GUI slides66
Events and Listeners
Generator
This object mayThis object maygenerate an eventgenerate an event
Listener
This object waits for, andThis object waits for, andresponds to an eventresponds to an event
Event
When an event occurs, the When an event occurs, the the appropriate method of the listener is called,the appropriate method of the listener is called,
passing an object that describes the eventpassing an object that describes the event
CLH GUI slides67
Creating GUIs - Review
Therefore, to create a program with a GUI, we :
define and set up the components
create listener classes
set up the relationships between the listeners and the components which generate events
define what happens in response to each event
Listener class for buttons
The listener class must implement the ActionListener Interface.
A method is called in the listener class to listener class to respond:respond:
public void actionPerformed(Event e)
CLH GUI slides68
CLH GUI slides69
PushButton applet
CLH GUI slides70
Push Counter Example
The components of the PushCounter class are
the button which the user presses
a label to display the counter,
a panel to organize the components,
and the main frame to hold the GUI
CLH GUI slides 71
public class PushCounter extends JApplet{ private int pushes; // set up components
private JLabel label;
private JButton push;
//------------------------------------------------------------ // Now set up the GUI. //------------------------------------------------------------
public void init () { pushes = 0;
push = new JButton ("Push Me!");// create a button
// add the ButtonListener class as the listener for the //button
push.addActionListener (new ButtonListener()); label = new JLabel ("Pushes: " + Integer.toString (pushes));
Container cp = getContentPane();// cp holds the components cp.add (push); // add the button to contentPane
cp.add (label); } // add the label
CLH GUI slides72
CLH GUI slides73
CLH GUI slides74
/******************************************
// Class BUTTONLISTENER listens for when the Jbutton is pressed AND implements the ActionListener Interface
//******************************************
private class ButtonListener implements ActionListener { //----------------------------------------------------------
// Updates the counter when the button is pushed. // and changes the number of pushed on the label //----------------------------------------------------------
public void actionPerformed (ActionEvent event) { pushes++;
label.setText("Pushes: " + pushes); repaint (); // tell layout manager to redraw label } }}
//repaint forces an update to change the label
CLH GUI slides75
Listeners - Reviewing the Code
// CREATE THE BUTTON push = new JButton ("Push Me!");
// ADD A LISTENER TO IT - ButtonListener push.addActionListener (new ButtonListener());
The ButtonListener class is listed as the listener for for the push buttons - (whenever the button is pressed).
CLH GUI slides76
Push Counter Algorithm
When the user presses the button,
An event is fired:
An an ActionEvent object created AND
The program looks for the actionPerformed method in the ButtonListener class
The actionPerformed method increments the counter and resets the text of the label
CLH GUI slides77
Push Counter Example
The ButtonListener class is implemented as an inner class
This allows the listener class to have access to the instance variables and methods in the outer class
CLH GUI slides78
Action Events
Some components have more than one listener (just to keep things real simple!!!!!)
A list of the Components and their listeners can be found on either Oracle of Sun’s website.
CLH GUI slides79
Nested Panels
Containers that contain other components make up the containment hierarchy
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
CLH GUI slides80
Nested Panels
CLH GUI slides81
public class NestedPanels{ //----------------------------------------------------------------- // Presents two colored panels nested within a third. //-----------------------------------------------------------------public static void main (String[] args) { // Set up first subpanel JPanel subPanel1 = new JPanel();
// set its preferred size and background color subPanel1.setPreferredSize (new Dimension(150, 100));
subPanel1.setBackground (Color.green);
CLH GUI slides82
// create and add another label to a panel JLabel label1 = new JLabel ("One");
subPanel1.add (label1);
// Set up second subpanel and size it 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);
CLH GUI slides83
// 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);
}}
CLH GUI slides84
CLH GUI slides85
Text Fields
A text field allows the user to enter one line of input
If the cursor is in the text field,
the text field generates an action event when the enter key is pressed
CLH GUI slides86
See Farhenheit.doc
87
public class Fahrenheit{ //-----------------------------------------------------------------//----------------------------------------------------------------- // Creates and displays the temperature converter GUI.// 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); }
}
Fahrenheit.java
CLH GUI slides88
// 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; // create a panel
// create two labels and a textfield private JLabel inputLabel, outputLabel, resultLabel; private JTextField fahrenheit;
// Sets up the GUI. public FahrenheitGUI() // create the labels { super("Farhrenheit Converter");
// Create three labels inputLabel = new JLabel ("Enter Fahrenheit
temperature:");
outputLabel = new JLabel ("Temperature in Celcius: ");
resultLabel = new JLabel ("---"); CLH GUI slides
89
CLH GUI slides90
// create a textfield with 10 columns, 20 rows fahrenheit = new JTextField (10, 20);fahrenheit = new JTextField (10, 20);
// add a listener classt o the textfield fahrenheit.addActionListener (new TempListener());
// when enter is pressed in the textfield, an event is //fired
// Create a panel to put the components onpanel = new JPanel();
// set the background color of the panel panel.setBackground (Color.yellow);
// Add the labels and the textfield to the panelpanel.add (inputLabel); // add labelpanel.add (fahrenheit); // add textfield
panel.add (outputLabel); //labelpanel.add (resultLabel);
// Get the contentPane and add the panel to it Container c = getContentPane(); c.add (panel); // add the panel to the GUI
} // closeCLH GUI slides
91
CLH GUI slides92
CLH GUI slides93
The Farenheit Program
The order in which the labels and text fields are added is the order in how they appear.
The size of the panels determines how they line up to each other.
Panels by default are governed by a flow layout which we will explore later.
CLH GUI slides94
The fahrenheit Program
The program reacts when the user presses the enter key inside the text field.
A JTextField objects generates an action event when the enter key is pressed
The TempListener class will handle the class will handle the action event when key is pressed . It LISTENS FOR the event
CLH GUI slides95
private class TempListener implements ActionListener
{ public void actionPerformed (ActionEvent event) { int fahrenheitTemp, celciusTemp;
// get the text the user entered into the textfield// get the text the user entered into the textfield String text = fahrenheit.getText();
// change the text to an int and store it in celciusTemp// change the text to an int and store it in celciusTemp
fahrenheitTemp = Integer.parseInt (text);fahrenheitTemp = Integer.parseInt (text); celciusTemp = (fahrenheitTemp-32) * 5/9;celciusTemp = (fahrenheitTemp-32) * 5/9;
// when the enter key is pressed in the text field.
// // change the text to an int and store it in celciusTempchange the text to an int and store it in celciusTemp fahrenheitTemp = Integer.parseInt (text);fahrenheitTemp = Integer.parseInt (text); celciusTemp = (fahrenheitTemp-32) * 5/9;celciusTemp = (fahrenheitTemp-32) * 5/9;
// change the text in the resultLabel// change the text in the resultLabel resultLabel.setText (Integer.toString (celciusTemp));
} // end of method
CLH GUI slides96
SetText,() getText()
In the above code,
setText(some value) will change what is printed on the label.
To get a value from a textfield use:
String text = fahrenheit.getText();
CLH GUI slides97
CLH GUI slides98
Listeners for TextFields
A JTextField has two listeners,
ActionListener and TextListener:
An ActionListener listens for hitting the return key
use getText( ) to get the text from whatever is input into the textfield.
CLH GUI slides99
Determining Event Sources
The other listener – TextListener - listens for changes to the text already in the textfield
The TextListener Interface has one method
public void textValueChanged(TextEvent e)
What Event? The source of the event ( which component was
fired e.g a textfield, a button) can be determined by
using the:
getSource() method e.g.
event.getSource()
“event” is the parameter sent to the ActionPerformed method e.g.
public void actionPerformed (ActionEvent event)CLH GUI slides
100
CLH GUI slides101
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); }}
CLH GUI slides102
// Puts a Panel on top of a Panel
public class LeftRightPanel extends JPanel{ // creates components for the Panel
private JButton left, right; private JLabel label; private JPanel buttonPanel;
Listeners
public LeftRightPanel ()public LeftRightPanel () { // create two buttons left = new JButton ("Left"); right = new JButton ("Right");
// attach listener class to them - same listener for both ButtonListener listener = new ButtonListener(); left.addActionListener (listener); right.addActionListener (listener);
label = new JLabel ("Push a button"); // create a label
CLH GUI slides103
CLH GUI slides104
105
buttonPanel = new JPanel(); // create a panel
buttonPanel.setPreferredSize (new Dimension(200, 40)); buttonPanel.setBackground (Color.blue); buttonPanel.add (left); buttonPanel.add (left); // add buttons to panel// add buttons to panel buttonPanel.add (right);buttonPanel.add (right);
setPreferredSize (new Dimension(200, 80)); setBackground (Color.cyan);
// add the label and the panel to the LeftRightPanel add (label); add (buttonPanel); }
106
//****************************************************
// Class Represents a listener for both buttons.//****************************************************
private class ButtonListener implements ActionListener { //-------------------------------------------------------------- // Determines which button was pressed and sets the label // text accordingly. The event object knows what button was
pressed //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) { if (event.getSource() == left) // which event was fired? label.setText("Left"); // write left on the label else
label.setText("Right"); } }
CLH GUI slides107
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:
Defined in the AWT
Defined in Swing
Flow LayoutBorder LayoutCard LayoutGrid LayoutGridBag LayoutBox Layout
Overlay Layout
CLH GUI slides108
Layout Managers
We can explicitly set the layout manager
Each layout manager has its own particular rules on how the components will be arranged
Some layout managers pay attention to a component's preferred size or alignment, while others do not
CLH GUI slides109
Layout Managers
We can use the setLayout method setLayout method of a container to change its layout manager
JPanel panel = new JPanel();
panel.setLayout (new BorderLayout());
The following example uses a tabbed panetabbed pane, a , a container which permits one of several panes to be container which permits one of several panes to be selectedselected
CLH GUI slides110
FlowLayout
Components are added left-to-right
If no room is left , a new row is started
Exact layout depends on size of the container
Components are made as small as possible
FlowLayout is convenient but often ugly
CLH GUI slides111
Flow Layout Flow layout puts as many components as possible on
in 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
CLH GUI slides112
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);
// create 5 buttons// create 5 buttons JButton b1 = new JButton 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");
}}
Adding the buttons to the panel
Now add all the buttons to the panel
add (b1); add (b2); add (b3); add (b4); add (b5);
Because FlowPanel extend Jpanel, we add the buttons directly to it.
CLH GUI slides113
CLH GUI slides114
LayoutDemo - Flow
CLH GUI slides115
Border Layout
A border layout defines five areas to which components
can be added North
South
Center EastWest
CLH GUI slides116
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”));
CLH GUI slides117
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")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"));}
CLH GUI slides118
Using a Panel within a panel
panel p = new Panel(); // create another paneladd (BorderLayout.SOUTH, p);// set its layoutp.add (new Button (“Button 1”)); //add buttons to itp.add (new Button (“Button 2”));
CLH GUI slides119
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
CLH GUI slides120
LayoutDemo - Border
CLH GUI slides121
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
Grid Layout
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
CLH GUI slides122
CLH GUI slides123
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)); // 2 rows, 3 columns 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 all the buttons to the panel add (b2); add (b3); add (b4); add (b5); }}
CLH GUI slides124
LayoutDemo - Grid
CLH GUI slides125
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
BOX Layout
By combining multiple containers using box layout,
many different configurations can be created
Multiple containers with box layouts are often
preferred to one container
CLH GUI slides126
Gridbag layoutGridbag layout
The Gridbag layout Gridbag layout uses the more complicated
gridbag layout manager
For GRIDBAG layout you place components yourself by
Giving the pixel locations of every component
CLH GUI slides127
CLH GUI slides128
Box Layout
Invisible components can be added to a boxlayout
container to take up space between components
Rigid areas have a fixed size
Glue specifies where excess space should go
Boxlayout
A rigid area is created using the
createRigidArea()createRigidArea() method of the BoxBox class class
Glue which allows an area to expand is created using the methods
createHorizontalGlue () or
createVerticalGlue ()
CLH GUI slides129
CLH GUI slides130
LayoutDemo - Box
CLH GUI slides131
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");
CLH GUI slides132
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); }}
CLH GUI slides133
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
CLH GUI slides134
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-or-no question
CLH GUI slides135
CLH GUI slides136
The EvenOdd Program
CLH GUI slides137
Check Boxes A check box is a button that can be
toggled on or off
You use the JCheckBox class
Unlike a push button, which generates an action event, ( a listener)
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
which are the listeners for checkboxes
The The check boxcheck box calls the calls the
itemStateChanged() mitemStateChanged() method
when it is toggled
Just like buttons call actionPerformed() methodCLH GUI slides
138
CLH GUI slides139
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’s font: You can specify:
family name (such as Times or Courier)
style (bold, italic, or both)
font size
CLH GUI slides140
Checkbox – choose bold or italic
public class StyleOptionsPanel extends JPanel{ private JLabel saying; // label to place the saying
private JCheckBox bold, italic; // two checkboxs
//----------------------------------------------------------------- // Sets up a panel with a label and some check boxes // and controls the style of the label's font. //-----------------------------------------------------------------
141
//Setting the font for the Jlabel and the checkboxes**************************************************public StyleOptionsPanel(){
saying = new JLabel ("Say it with style!");
saying.setFont (new Font ("Helvetica", Font.PLAIN, 36)); bold = new JCheckBox ("Bold");
bold.setBackground (Color.cyan);
italic = new JCheckBox ("Italic");
italic.setBackground (Color.cyan);
CLH GUI slides142
// 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));
143
Setting up listeners for checkboxesSetting up listeners for checkboxes
// set up a listener classs for the checkboxes StyleListener listener = new StyleListener();
// add listeners to the checkboxes bold.addItemListener (listener);// add listeners italic.addItemListener (listener); add (saying); // add checkboxes and label to panel add (bold); add (italic);
setBackground (Color.cyan); setPreferredSize (new Dimension(300, 100));
CLH GUI slides144
//****************************************************
// Represents the listener class for both Represents the listener class for both check boxcheck box.. //***************************************************
private class StyleListener implements ItemListener { //-------------------------------------------------------------- //--------------------------------------------------------------
// // Updates the style of the label font Updates the style of the label font style.style. //-------------------------------------------------------------- //-------------------------------------------------------------- public void itemStateChanged (ItemEvent event) { int style = Font.PLAIN;int style = Font.PLAIN;
if (bold.isSelected()) if (bold.isSelected()) // if the bold checkbox is // if the bold checkbox is selectedselected style = Font.BOLD style = Font.BOLD; // set the style to BOLD; // set the style to BOLD
if if (italic.isSelected(italic.isSelected()) ()) // if italic checkbox is // if italic checkbox is selectedselected style = Font.ITALIC; style = Font.ITALIC; // set the style to italic// set the style to italic
saying.setFont (new Font ("Helvetica", style, 36)); } } }
145
CLH GUI slides146
The StyleOptions Program
CLH GUI slides147
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
CLH GUI slides148
CLH GUI slides149
Radio Buttons 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?
CLH GUI slides150
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); }}
CLH GUI slides151
public class QuoteOptionsPanel extends JPanel{ private JLabel quote; private JRadioButton comedy, philosophy, carpentry; private String comedyQuote, philosophyQuote, carpentryQuote; // strings to be placed on buttons
//----------------------------------------------------------------- // Sets up a panel with a label and
// a set of radio buttons // that control its text. //-----------------------------------------------------------------
public QuoteOptionsPanel()public QuoteOptionsPanel() { { comedyQuote = "Take my wife, please.";comedyQuote = "Take my wife, please."; philosophyQuote = "I think, therefore I am."; philosophyQuote = "I think, therefore I am."; carpentryQuote = "Measure twice. Cut once."; carpentryQuote = "Measure twice. Cut once.";
quote = new JLabel (comedyQuote); quote = new JLabel (comedyQuote); quote.setFont (new Font ("Helvetica", Font.BOLD, 24))quote.setFont (new Font ("Helvetica", Font.BOLD, 24))
CLH GUI slides152
CLH GUI slides153
Create three radio buttons
comedy = new JRadioButton ("Comedy", true); comedy.setBackground (Color.green);
philosophy philosophy = new JRadioButton ("Philosoph("Philosophy"); philosophy.setBackground (Color.green);
carpentry = new JRadioButton ("Carpentry"); carpentry.setBackground (Color.green);
// puts the buttons into a group - this is required// puts the buttons into a group - this is required ButtonGroup group = new ButtonGroup(); group.add (comedy); group.add (philosophy); group.add (carpentry);
CLH GUI slides154
QuoteOptions.java// see slide 156 first
// set up a listener for the buttons QuoteListener listener = new QuoteListener();
comedy.addActionListener (listener); philosophy.addActionListener (listener); carpentry.addActionListener (listener);
// Add the buttons to this panel add (quote);add (quote); add (comedy); add (comedy); add (philosophy); add (philosophy); add (carpentry); add (carpentry);
setBackground (Color.green); setPreferredSize (new Dimension(300, 100)); }
CLH GUI slides155
//******************************************************** // Represents the listener class for all radio buttons /***********************************************************
private class QuoteListener implements ActionListenerprivate class QuoteListener implements ActionListener { { //-------------------------------------------------------------- // Sets the text on the label depending on which radio // button was pressed. //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) public void actionPerformed (ActionEvent event) { if (event.getSource() == comedy // if the comedy button is pressed quote.setText (comedyQuote); else // if the philosophy button is pressed
if (event.getSource() == philosophy) quote.setText (philosophyQuote); else quote.setText (carpentryQuote);quote.setText (carpentryQuote); } }}
CLH GUI slides156
The QuoteOptions Program
CLH GUI slides157
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 See JukeBoxControls.java
CLH GUI slides158
Combo Boxes
Unlike a JList , 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
CLH GUI slides159
The JukeBox Program See JukeBox.java
See JukeBoxControls.java
CLH GUI slides160
//----------------------------------------------------------------// Sets up the GUI for the juke box.// You need to create URL’s to load the sound files//-----------------------------------------------------------------
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) {}
}
CLH GUI slides161
// now create an array of AudioClips
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);
// Create a Jlable and set its alignment Jlabel titleLabel = new JLabel ("Java Juke Box"); titleLabel.setAlignmentX (Component.CENTER_ALIGNMENT);
CLH GUI slides162
// Create the list of strings for the combo box options
String[] musicNames = {"Make A Selection...", "Western Beat",String[] musicNames = {"Make A Selection...", "Western Beat", "Classical Melody", "Jeopardy Theme", "New Age Rythm", "Classical Melody", "Jeopardy Theme", "New Age Rythm", "Eighties Jam", "Alfred Hitchcock's Theme"}; "Eighties Jam", "Alfred Hitchcock's Theme"};
// Create the Combo Box and put the musicnames above in it// Create the Combo Box and put the musicnames above in it
musicCombo = new JComboBox (musicNamemusicCombo = new JComboBox (musicNamess); musicCombo.setAlignmentX (Component.CENTER_ALIGNMENT);
// add a listener to the combo box
// ComboListenerComboListener()() is the listener class for the combo box musicCombo.addActionListener musicCombo.addActionListener (new ComboListener());(new ComboListener());
CLH GUI slides163
// Set up the buttons
playButton = new JButton ("Play", new ImageIcon ("play.gif"))playButton.setBackground (Color.white); playButton.setMnemonic ('p');
stopButtonstopButton = new JButton ("Stop", new ImageIcon ("stop.gif"));= new JButton ("Stop", new ImageIcon ("stop.gif"));
stopButton.setBackground (Color.white);stopButton.setBackground (Color.white);
stopButton.setMnemonic ('s'); stopButton.setMnemonic ('s'); // keyboard // keyboard
// add action listeners to the buttons stopButton.addActionListener (stopButton.addActionListener (new ButtonListener());new ButtonListener());
playButton.addActionListener (new ButtonListener());
current = null;
CLH GUI slides164
JPanel buttons = new JPanel(); // USE A BOXLAYOUT// USE A BOXLAYOUT// set the horizontal layout for the buttons panel to BoxLayout buttons.setLayout (new BoxLayout (buttons,
BoxLayout.X_AXIS))
// ADD THE BUTTONS 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);
CLH GUI slides165
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)));
CLH GUI slides166
Listener for the Combo Boxes
private class ComboListener implements ActionListener { //-------------------------------------------------------------- // Stops playing the current selection (if any) and resets // the current selection to the new 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()]; } }
CLH GUI slides167
//***************************************************************** // Represents the action listener for both control buttons. //*****************************************************************
private class ButtonListener implements ActionListener { //-------------------------------------------------------------- // Stops the current selection (if any) .
//
// 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(); } }
CLH GUI slides168
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(); }}
CLH GUI slides169
Outline
Mouse Events and Key Events
CLH GUI slides170
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
CLH GUI slides171
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
CLH GUI slides172
The Dots Program
CLH GUI slides173
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) Lewis Book See DotsPanel.java (page 414)
CLH GUI slides174
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
CLH GUI slides175
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
CLH GUI slides176
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); }}
CLH GUI slides177
public class OffCenterPanel extends JPanel{ private final int WIDTH=300, HEIGHT=300;
private DecimalFormat fmt; private Point current; private int centerX, centerY; private double length;
//----------------------------------------------------------------- public OffCenterPanel() { addMouseListener (new OffCenterListener());
centerX = WIDTH / 2; centerY = HEIGHT / 2;
fmt = new DecimalFormat ("0.##");
setPreferredSize (new Dimension(WIDTH, HEIGHT)); setBackground (Color.yellow); }
CLH GUI slides178
//----------------------------------------------------------------- // 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); } }
CLH GUI slides179
//***************************************************************** // 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(); }
CLH GUI slides180
The user clicks on a point on panel and distance is calculated
CLH GUI slides181
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
CLH GUI slides182
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
CLH GUI slides183
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); }}
CLH GUI slides184
The Direction Program
CLH GUI slides185
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;
//----------------------------------------------------------
CLH GUI slides186
//----------------------------------------------------------------- // 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); }
CLH GUI slides187
//--------------------------------------------------------- // Draws the image in the current location. //------------------------------------------------------ public void paintComponent (Graphics page) { super.paintComponent (page); currentImage.paintIcon (this, page, x, y); }// close class
The paintIcon method draws the current image at the specified x and y location
CLH GUI slides188
//***************************************************************** // 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 using //-------------------------------------------------------------- public void keyPressed (KeyEvent event) { switch (event.getKeyCode()) { case KeyEvent.VK_UP: currentImage = up; y -= JUMP; break; case KeyEvent.VK_DOWN: currentImage = down; y += JUMP; break;
CLH GUI slides189
case KeyEvent.VK_LEFT: currentImage = left; x -= JUMP; break; case KeyEvent.VK_RIGHT: currentImage = right; x += JUMP; break; }
repaint(); }
//-------------------------------------------------------------- // Provide empty definitions for unused event methods.// Had the listener implement KeyAdaptor – this would not be necessary //-------------------------------------------------------------- public void keyTyped (KeyEvent event) {} public void keyReleased (KeyEvent event) {} }}
CLH GUI slides190
Some of the methods available on KeyEvents:Method Purpose
int getKeyChar() Obtains the Unicode character associated with this event. Only rely on this value for key-typed events.
int getKeyCode() Obtains the key code associated with this event. The key code identifies the particular key on the keyboard that the user pressed or released.
The KeyEvent class defines many key code constants for commonly seen keys.
For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the Escape key.
KeyEvents
See this site for examples of all key events:
http://download.oracle.com/javase/1.4.2/docs/api/java/awt/event/KeyEvent.html
CLH GUI slides191
CLH GUI slides192
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 timed delay
CLH GUI slides193
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
CLH GUI slides194
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
CLH GUI slides195
The Rebound Program
CLH GUI slides196
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
Rebound Program
public class ReboundPanel extends JPanel{ private final int WIDTH = 300, HEIGHT = 100; private final int DELAY = 20, IMAGE_SIZE = 35;
private ImageIcon image;
// be sure to declare timer at top of program private Timer timer;
private int x, y, moveX, moveY;
CLH GUI slides197
//Sets up the panel, //including the timer for the animation.
public ReboundPanel() { // create the timer and its listener class timer = new Timer(DELAY, new ReboundListener());
image = new ImageIcon ("happyFace.gif"); x = 0; y = 40; moveX = moveY = 3; // # of pixels to move each time
setPreferredSize (new Dimension(WIDTH, HEIGHT)); setBackground (Color.black);
timer.start(); // START TIMER }
CLH GUI slides198
// Class Represents the action listener for the timer. //*********************************** private class ReboundListener implements ActionListener { / Updates the position and direction of the image
// whenever the timer fires an action event. //-------------------------------------------------------------- public void actionPerformed (ActionEvent event) { x += moveX; y += moveY; if (x <= 0 || x >= WIDTH-IMAGE_SIZE) moveX = moveX * -1; if (y <= 0 || y >= HEIGHT-IMAGE_SIZE) moveY = moveY * -1;
repaint(); // calls paintComponet() to redraw image
} } }
GUI slides 199
CLH GUI slides200
//----------------------------------------------------------------- // is called from actionPerformed method // to Draws the image in the new location.// when the timer fires. // Each time the timer fires, it will redraw the image at a // new location //----------------------------------------------------------------- public void paintComponent (Graphics page) { super.paintComponent (page); // draw the image on “this “ panel at location values of x and y image.paintIcon (this, page, x, y); }
CLH GUI slides201
Containment Hierarchies
CLH GUI slides202
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
CLH GUI slides203
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.");
CLH GUI slides204
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");
CLH GUI slides205
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);
CLH GUI slides206
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)
CLH GUI slides207
The LightBulb Program
CLH GUI slides208
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)
CLH GUI slides209
The DisplayFile Program
CLH GUI slides210
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)
CLH GUI slides211
The DisplayColor Program
CLH GUI slides212
In this application, radio buttons were displayed with various colors and the option for users to choose their own color with the colorChooser
// a radio Button was selected to choose a color in main programpublic void actionPerformed(ActionEvent event) {
// If the other radio button is pressed the JColorChooser pops up if(event.getActionCommand().equals("Other")) {
// Allows user to pick another color , otherPanel is the panel it will be displayed on
// colorChosen is the color the user picks colorChosen = JColorChooser.showDialog(otherPanel,
"Pick a Color!", colorChosen);
// Sets a panel displayed next to radiobuttons to the current color being used
colorPanel.setBackground(colorChosen); }// close if
CLH GUI slides213
CLH GUI slides214
else { // Sets current color to the radiobutton selected
colorChosen = mycolor;
// Sets panel next to radiobuttons to the current color being used
colorPanel.setBackground(colorChosen);}
}// Close actionPerformed
CLH GUI slides215
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)
CLH GUI slides216
The TransitMap Program
CLH GUI slides217
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
LeftComponent
RightComponent
Top Component
Bottom Component
CLH GUI slides218
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
CLH GUI slides219
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)
CLH GUI slides220
The PickImage Program
CLH GUI slides221
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
We used the DefaultListModel because it contains a vector
CLH GUI slides222
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
CLH GUI slides223
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)
CLH GUI slides224
CLH GUI slides225
public class SlideColorPanel extends JPanel{ private JPanel controls, colorPanel; private JSlider rSlider, gSlider, bSlider; private JLabel rLabel, gLabel, bLabel;
//----------------------------------------------------------------- // Sets up the sliders and their labels, aligning them along // their left edge using a box layout. //----------------------------------------------------------------- public SlideColorPanel() { rSlider = new JSlider (JSlider.HORIZONTAL, 0, 255, 0);
rSlider.setMajorTickSpacing (50); // set values for ticks rSlider.setMinorTickSpacing (10);
rSlider.setPaintTicks (true); // necessary to have ticks appear rSlider.setPaintLabels (true); // set labels for the ticks
rSlider.setAlignmentX (Component.LEFT_ALIGNMENT);
// sets up two other sliders
CLH GUI slides226
By default, spacing for major and minor tick marks is zero.
To see tick marks, you must explicitly set the spacing for either major or minor tick marks (or both) to a non-zero value and call the setPaintTicks(true) method.
However, you also need labels for your tick marks.
To display standard, numeric labels at major tick mark locations,
Set the major tick spacing(rSlider.setMajorTickSpacing (50);, then call the setPaintLabels(true) method.
CLH GUI slides227
SliderListener listener = new SliderListener();// set change listeners for the sliders rSlider.addChangeListener (listener); gSlider.addChangeListener (listener); bSlider.addChangeListener (listener);
create the labels and set alignment LEFT rLabel = new JLabel ("Red: 0"); rLabel.setAlignmentX (Component.LEFT_ALIGNMENT); gLabel = new JLabel ("Green: 0"); gLabel.setAlignmentX (Component.LEFT_ALIGNMENT); bLabel = new JLabel ("Blue: 0"); bLabel.setAlignmentX (Component.LEFT_ALIGNMENT);
Create a boxlayout for label/slider
controls = new JPanel(); BoxLayout layout = new BoxLayout (controls, BoxLayout.Y_AXIS); controls.setLayout (layout); controls.add (rLabel); controls.add (rSlider); controls.add (Box.createRigidArea (new Dimension (0, 20))); controls.add (gLabel); controls.add (gSlider); controls.add (Box.createRigidArea (new Dimension (0, 20))); controls.add (bLabel); controls.add (bSlider);
CLH GUI slides228
CLH GUI slides229
// Create a Panel to display a color
colorPanel = new JPanel(); colorPanel.setPreferredSize (new Dimension (100, 100)); colorPanel.setBackground (new Color (0, 0, 0)); add (controls); add (colorPanel);
CLH GUI slides230
//***************************************************************** // Represents the listener for all three sliders. //***************************************************************** private class SliderListener implements ChangeListener { private int red, green, blue;
//-------------------------------------------------------------- // Gets the value of each slider, then updates the labels and the color panel. //-------------------------------------------------------------- public void stateChanged (ChangeEvent event) { red = rSlider.getValue(); // get all the slider values green = gSlider.getValue(); blue = bSlider.getValue();
rLabel.setText ("Red: " + red); gLabel.setText ("Green: " + green); bLabel.setText ("Blue: " + blue); // set the colorpanel to that color colorPanel.setBackground (new Color (red, green, blue)); } }}
CLH GUI slides231
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)
CLH GUI slides232
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
CLH GUI slides233
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
CLH GUI slides234
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
CLH GUI slides235
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
CLH GUI slides236
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
CLH GUI slides237
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
CLH GUI slides238
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 object-oriented 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
CLH GUI slides239
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
CLH GUI slides240
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
CLH GUI slides241
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
CLH GUI slides242
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
CLH GUI slides243
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
CLH GUI slides244
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
CLH GUI slides245
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
CLH GUI slides246
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
CLH GUI slides247
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
CLH GUI slides248
The BorderDemo Program
CLH GUI slides249
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
CLH GUI slides250
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 slides251
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
CLH GUI slides252
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)
CLH GUI slides253
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);
CLH GUI slides254
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);
CLH GUI slides255
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);
CLH GUI slides256
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);
CLH GUI slides257
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);
}}
CLH GUI slides258
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)
CLH GUI slides259
Tiled Pictures
CLH GUI slides260
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)
CLH GUI slides261
Koch Snowflakes
< x5, y5>
< x1, y1>
Becomes
< x5, y5>
< x1, y1>
< x4, y4>
< x2, y2>
< x3, y3>
CLH GUI slides262
Koch Snowflakes
CLH GUI slides263
Koch Snowflakes
CLH GUI slides264
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
CLH GUI slides265
Graphics Class Hierarchy (Swing)
AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Container
Panel Applet
Frame
Dialog
Window
JComponent
JApplet
JFrame
JDialog
Swing Components in the javax.swing package
Lightweight
Heavyweight
Classes in the java.awt package
1
LayoutManager
*
CLH GUI slides266
JComponent .
JButton
JMenuItem
JCheckBoxMenuItem
AbstractButton
JComponent
JMenu
.JRadioButtonMenuItem
.JToggleButton JCheckBox
JRadioButton
.JComboBox
.JInternalFrame .JLayeredPane
.JList .JMenuBar .JOptionPane
.JPopupMenu
.JProgressBar
.JPane
.JFileChooser .JScrollBar .JScrollPane
.JSeparator
.JSplitPane
.JSlider .JTabbedPane
.JTable
.JTableHeader
.JTextField .JTextComponent
.JEditorPane
.JTextArea
.JToolBar
.JToolTip
.JTree
.JRootPane
.JPanel
.JPasswordField
.JColorChooser
.JLabel
CLH GUI slides267
AWT (Optional)AWTEvent
Font
FontMetrics
Component
Graphics
Object Color
Canvas
Button
TextComponent
Label
List
CheckBoxGroup
CheckBox
Choice
Container Panel Applet
Frame
Dialog FileDialog
Window
TextField
TextArea
MenuComponent MenuItem
MenuBar
Menu
Scrollbar
LayoutManager