Chapter 10
Learning Objectives
· Using the Frame Class.
· Creating a frame that can be closed
· Using adapters
· Additional Frame class methods
· Using Container class methods
- Emphasize the concept of a frame and what it looks like. The
resize and close functions are
part of the frame. Demonstrate that when an applet is run within the
appletviewer, it can be resized and
closed with the close button because the appletviewer runs the applet
within a frame.
- When the exact same applet is run within a browser, the frame
does not
appear, and the applet cannot be resized or closed.
- When creating Windows objects, the WindowListener listens
for Window events.
- As this is an interface, all seven of its methods are abstract
and must be
made concrete, even if they do nothing.
- Java provides an adapter that makes all of the
methods concrete methods
that do nothing.
- A class may extend this adapter and override
any methods that must
contain actual code.
I. Components
– known as widgets (window gadgets). The Component class is an
abstract class which must be
instantiated by a child class.
A. Components
include Buttons, Labels and Containers (among others) as child
classes
B. Containers
include Panels and Windows as child classes
C. Panel includes
Applet as a child; Window includes Frame and Dialog as child
classes
II. Frames – A
Frame is a Window, a Window is a Container, a Container is a
Component, a Component is an
Object.
A. The Frame
class has two constructors: one with no arguments, and one with a
String argument which
becomes the Frame title.
B. The most basic
methods included as part of the Frame class are:
· framename.setSize(width, height); with width and height int
values
· framename.setVisible(boolean); with the boolean true or false.
III. Window interface and adapters
A. The listener
for Window events is an interface and provides seven abstract
Window event methods:
· windowClosing( )
· windowClosed( )
· windowDeiconified( )
· windowIconified( )
· windowOpened( )
· windowActivated( )
· windowDeactivated( )
B. Each of the
methods is public void and has an argument of
WindowEvent.
Since all methods in an interface are abstract, if a class
implements the WindowListener interface, all seven methods must
be made
concrete, even if the class does not use them.
C. The Java
language provides classes called adapters for all Listener interfaces.
The adapters make all of the methods in a Listener interface concrete with no
coding. A programmer can choose to extend one of these adapters and override
only those methods they wish to use.
IV. Additional Frame and Container methods
A. Additional
Frame methods include:
· setTitle(String) Sets a Frame title to the String
argument
· getTitle( ) Returns a String which is the Frame’s title
· setResizable(boolean) Sets the Frame to be
resizable or not based on
the boolean
· isResizable( ) Returns a boolean true if resizable, false if not
B. Container
Methods include:
· add(component) Adds component to
the Container
· getComponentCount() Returns an int that is the number of
components
in the Container
· getComponent(n) Returns the nth component of the
Container
· getComponents( ) Returns an array of Components which includes
all of the Components in a Container
· remove(component) Removes component from
the Container
· removeAll( ) Removes all Components from the Container.
Exercises: 1 (page 474)
Write a program that displays a Frame that contains the words to
any well-known nursery rhyme. Name the program Rhyme.java
Answer:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class Rhyme
extends Applet
{
private RhymeFrame fycc =
new RhymeFrame();
Label msg1 = new
Label("Little Miss Muffet sat on a tuffet");
public void init()
{
fycc.setSize(300,250);
fycc.setLocation(10,10);
fycc.add(msg1);
fycc.setVisible(true);
}
}
import java.awt.event.*;
import java.awt.*;
public class RhymeFrame
extends Frame implements WindowListener
{
public RhymeFrame()
{
super("Rhyme Frame");
addWindowListener(this);
}
public void
windowClosing(WindowEvent e)
{
e.getWindow().dispose();
System.exit(0);
}
public void
windowClosed(WindowEvent e)
{}
public void
windowDeiconified(WindowEvent e)
{}
public void
windowIconified(WindowEvent e)
{}
public void
windowOpened(WindowEvent e)
{}
public void
windowActivated(WindowEvent e)
{}
public void
windowDeactivated(WindowEvent e)
{}
}
Using Components
· Using
Component Methods
· Using Checkboxes and
Checkbox Groups
· Using Choices and Lists
· Swing Components
Review the colors from Chapter
7.
Review the use of Buttons,
Labels, TextFields and other Components from the Chapters dealing with applets.
Review these components exist
within a Container that is an instance of an Applet.
A Button has a Label on it, and
that a Label contains text. Checkboxes allow the user to click in a small square
to talk to a listener. Checkboxes can be set to an initial value of on (true) or
off (false).
Independent Checkboxes
have values that are independent if each other. A CheckboxGroup allows the user
to pick one and only one of the Checkboxes in a group. The Checkboxes in a group
appear as small circles (radio buttons)..Choices and List are very similar, but
emphasize that the
Choice is a drop down menu where
only one true choice can be made, and a List is a menu that appears in its
entirety and multiple selections may be made, if that option is enabled.
I. Containers are Components that usually hold or
"contain" other components.
Containers include Frames,
Windows, Applets and Panels. Other Components are non-container
components.
A. Non-Container Components that may be placed within
Containers include:
· Label
· Button
· Checkbox
· Choice
· List
· TextComponent
including
· TextArea
· TextField
B. Methods common to all of these Components include:
getFont( ) Returns the Font
setFont(font) Sets
the font to font for the Component
setEnabled(boolean)
Enables or forbids the Component from
responding to the user
isEnabled( ) Returns a boolean
indicating if the
Component can respond to the
user
setVisible(boolean)
Makes the Component visible or invisible
depending on the value of boolean
isVisible( ) Returns a boolean
indicating if the Component
is visible or not
isShowing( ) Returns a boolean
indicating if the Component
is visible and not obscured by other
Components
setSize(width, height)
Sets the Components size based on the integers
width and height
toString( ) Returns a String
describing the Component
setLocation(x, y)
Places the Component within the Container at
position x, y
setBackground(color)
Sets the background color to color
setForeground(color)
Sets the foreground color to color
repaint( ) Repaints a Component
C. The Label class also defines the following methods:
getText( ) Returns a String from
the Label.setText(String) Assigns String as the
value to displayed by the Label
D. The Button class also defines the following methods:
getLabel ( ) Returns a String
from the Button
setLabel (String)
Assigns String as the value to displayed on
the Button
II. Checkboxes
A. The Checkbox class creates a Component that consists of a
label, a small
square, and the state of the
square (checked as true or false). There are two
constructors, the first with no
argument that constructs a checkbox with no
label, and the second with a
String argument that constructs a checkbox with
the String as the label.
Checkbox box1 = new Checkbox(
);
Checkbox box2 = new
Checkbox("Put the label here");
B. The methods used with the Checkbox class are:
setLabel(String)
Sets the Label for the Checkbox to String
getLabel( ) Returns a String
which is the Label
setState(boolean)
Sets the Checkbox to the value of boolean
where true is checked and false
is not checked getState( ) Returns a boolean that indicates the state of the
Checkbox, true if checked and false if not checked
C. The ItemListener interface must be used to listen for
checkboxes. This interface includes an abstract method called
itemStateChanged(ItemEvent e) which must be made concrete in the class
implementing it. The method is executed anytime the state if a Checkbox is
changed (true to false and false to true).
III. Checkbox Groups
A. The state of a Checkbox is independent from the state of
any other Checkbox.
In order to create a group of
items in which only one item can be true at any
one time, a CheckboxGroup
must be defined. In a CheckboxGroup, only one
can have a state of true at
any one time. As soon as another Checkbox in the
group is checked, all other
Checkboxes are made false.
B. A CheckboxGroup is created by the statement (where the
definition String is optional):
CheckboxGroup groupname = new
CheckboxGroup("Some definition");
Individual Checkboxes are added
when they are created by:
Checkbox checkboxname = new
Checkbox(String, boolean,
groupname);
where the String is the Checkbox
label, the boolean is the Checkbox initial state, and the groupname is the name
of the CheckboxGroup the Checkbox belongs to. C. Checkboxes may be added to
groups after they are created, and their state can be changed after they are
created. Only one of the members of a CheckboxGroup can be true at any time.
IV. Choice
A. The Choice Component is a drop down menu which allows you
to choose from a list of options. It is created by:
Choice choiceName = new
Choice( );
Options are added to the drop
down menu by:
choiceName.add("Choice
text");
B. Methods are available for the Choice class to add an item
to the Choice, select
an item based on name or position, return the name of the currently selected
item or an item at a given
position, return the number of choices, and return the
position of the current
selection.
V. Lists
A. A List is very similar to a Choice, except that a List
displays multiple options and
allows multiple choices.
List listName = new List( );
ListName.add("List
text");
B. Methods exist to add and remove items, select and
deselect items, allow or disallow
multiple choices, and return arrays of selected items or their positions in
the list.
VI. Swing Components
Debug 1 (on page 500)
// This applet offers the user a choice
// of car wash options
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DebugTen1 extends Applet implements ItemListener
{
String companyName = new String("Cal's Car Wash");
Font bigFont = new Font("Arial", Font.ITALIC, 16);
Checkbox wax = new Checkbox("Hi-Gloss Wax");
Checkbox dry = new Checkbox("No-Spot Dry");
int waxPrice = 2, dryPrice = 1;
int totalPrice=4;
public void init()
{
add(Checkbox);
Checkbox.addItemListener(this);
add(Checkbox);
Checkbox.addItemListener(this);
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName,10,100);
gr.drawString("Select options for your car wash
$",10,150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice),260,150);
}
public void itemStateChanged(ItemEvent check)
{
totalPrice = 4;
if(wax.getState())
{
totalPrice += waxPrice;
}
if(dry.getState())
{
totalPrice += dryPrice;
}
repaint();
}
}
Debug 2 (page 500)
//This applet lets the user choose
// a payment method
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DebugTen2 extends Applet implements ItemListener
{
String thanks = new String("Thanks for shopping with
us");
String feeMsg = new String("We charge a fee to help offset
costs");
String pctMsg = new String("per cent will be added to your
bill");
Font bigFont = new Font("Arial", Font.PLAIN, 14);
Choice payMethod = new Choice();
int fee = 0;
int[] fees = {5,2,0};
public void init()
{
add(payMethod);
payMethod.addItemListener(this);
add("Credit card");
add("Check");
add("Cash");
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.blue);
gr.drawString(thanks,10,80);
gr.drawString(feeMsg,10,100);
gr.drawString("Service fee",10,140);
gr.setColor(Color.green);
gr.drawString(Integer.toString(fee),10,180);
gr.drawString(pctMsg,36,180);
}
public void itemStateChanged(ItemEvent check)
{
int x = payMethod.getSelectedIndex();
fee = fees[x];
repaint();
}
}
Answer:
Debug 1 (answer)
// This applet offers the
user a choice
// of car wash options
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class FixDebugTen1
extends Applet implements ItemListener
{
String companyName = new
String("Cal's Car Wash");
Font bigFont = new
Font("Arial", Font.ITALIC, 16);
Checkbox wax = new
Checkbox("Hi-Gloss Wax");
Checkbox dry = new
Checkbox("No-Spot Dry");
int waxPrice = 2, dryPrice
= 1;
int totalPrice=4;
public void init()
{
// use object names
("wax", "dry"), not class name ("Checkbox")
// in each of the next
four lines.
add(wax);
wax.addItemListener(this);
add(dry);
dry.addItemListener(this);
}
public void paint(Graphics
gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName,10,100);
gr.drawString("Select
options for your car wash $",10,150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice),260,150);
}
public void
itemStateChanged(ItemEvent check)
{
totalPrice = 4;
if(wax.getState())
{
totalPrice += waxPrice;
}
if(dry.getState())
{
totalPrice += dryPrice;
}
repaint();
}
}
Debug 2 (answer)
//This applet lets the
user choose
// a payment method
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class FixDebugTen2
extends Applet implements ItemListener
{
String thanks = new
String("Thanks for shopping with us");
String feeMsg = new
String("We charge a fee to help offset costs");
String pctMsg = new
String("per cent will be added to your bill");
Font bigFont = new
Font("Arial", Font.PLAIN, 14);
Choice payMethod = new
Choice();.int fee = 0;
int[] fees = {5,2,0};
public void init()
{
add(payMethod);
payMethod.addItemListener(this);
// include payMethod
object in each of the
// three add() method
calls below.
payMethod.add("Credit
card");
payMethod.add("Check");
payMethod.add("Cash");
}
public void paint(Graphics
gr)
{
gr.setFont(bigFont);
gr.setColor(Color.blue);
gr.drawString(thanks,10,80);
gr.drawString(feeMsg,10,100);
gr.drawString("Service
fee",10,140);
gr.setColor(Color.green);
gr.drawString(Integer.toString(fee),10,180);
gr.drawString(pctMsg,36,180);
}
public void
itemStateChanged(ItemEvent check)
{
int x =
payMethod.getSelectedIndex();
fee = fees[x];
repaint();
}
}
Section A
Using the Frame class
Example1: a frame that does not close
import java.awt.*;
import java.awt.event.*;
public class demoFrame1 extends Frame implements WindowLinstener
{
public demoFrame1(String str)
{
super(str);
addWindowListener(this);
}
public static void main(String arg[])
{
Frame aF = new Frame("This is a frame");
aF.setSize(200,100);
aF.setVisible(true);
}
}
import java.awt.*;
import java.awt.event.*;
public class closeFrame extends Frame implements WindowListener
{
public closeFrame(String str)
{
super(str);
addWindowListener(this);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowDeiconified(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}
}
import java.awt.*;
public class demoClose
{
public static void main(String[] args)
{
closeFrame aFrame = new closeFrame("This is a frame that closes");
aFrame.setSize(400,100);
aFrame.setVisible(true);
}
}
Using Adapter – Use Adapter can inherit from the adapter class and you can include methods that were abstract in the original class are not abstract within the adapter class. You don’t have to code the methods in a class you extend from an adapter.
import java.awt.event.*;
public class CloseWindow extends WindowAdapter
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
import java.awt.*;
import java.awt.event.*;
public class CloseFrame extends Frame
{
public CloseFrame(String str)
{
super(str);
addWindowListener(new CloseWindow());
}
}
import java.awt.*;
public class demoCloseFrame
{
public static void main(String[] args)
{
CloseFrame aFrame = new CloseFrame("This is a frame that closes");
aFrame.setSize(400,100);
aFrame.setVisible(true);
}
}
1. void setTitle(String title) - sets a frame’s title
2. string getTitle() - returns a frme’s title
3. void setResizable(Boolean resizable) - sets the frame to be resiable by passing true, or sets the frame to be not resizable by passing false to the method.
4. Boolean isResizable() - returns true or false to indicate whether the frame is resizable.
import java.awt.event.*;
import java.awt.*;
public class Frame2 extends Frame implements WindowListener
{
public FixedFrame()
{
super("Size can Change");
addWindowListener(this);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}public void windowIcomified(WindowEvent e)
{
setTitle("Size can't change");
setResizable(false);
}
public void windowClosed(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDecactivated(WindowEvent e) {}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class AppletDemoComponents extends Applet implements ActionListener
{
private FrameYouCanClose fycc = new FrameYouCanClose("Demo Components");
private Button showFrame = new Button("Press Me");
Label msg1 = new Label("Java Programming Class");
Label msg2 = new Label("With your Instructor - Shin Liu");
Label msg3 = new Label("Have fun.");
int pressCounter =0;
public void init()
{
add(showFrame);
fycc.setSize(200,150);
showFrame.addActionListener(this);
}
public void actionPerformed(ActionEvent e)
{
if (pressCounter == 0)
fycc.add(msg1);
else if (pressCounter == 1)
{
fycc.remove(msg1);
fycc.add(msg2);
}
else if(pressCounter == 2)
{
fycc.remove(msg2);
fycc.setSize(400, 150);
fycc.add(msg3);
}
if (pressCounter < 3)
fycc.setVisible(true);
else
fycc.setVisible(false);
if (pressCounter == 4)
showFrame.setEnabled(false);
++pressCounter;
}
}
import java.awt.event.*;
import java.awt.*;
public class FrameYouCanClose extends Frame implements WindowListener
{
public FrameYouCanClose(String str)
{
super(str);
addWindowListener(this);
}
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
public void windowClosed(WindowEvent e) {}
public void windowDeiconified(WindowEvent e) {}
public void windowIconified(WindowEvent e) {}
public void windowOpened(WindowEvent e) {}
public void windowActivated(WindowEvent e) {}
public void windowDeactivated(WindowEvent e) {}
}
Section B:
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoCheckBox extends Applet implements ItemListener
{
String companyName = new String("Shin Liu's Incorporated");
Font bigFont = new Font("Arial",Font.PLAIN, 24);
Checkbox cocktailBox = new Checkbox("Cocktails");
Checkbox dinnerBox = new Checkbox("Dinner");
int cocktailPrice = 300, dinnerPrice = 600, totalPrice = 200;
public void init()
{
add(cocktailBox);
cocktailBox.addItemListener(this);
add(dinnerBox);
dinnerBox.addItemListener(this);
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10,100);
gr.drawString("Event price estimate", 10,150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice), 280,150);
}
public void itemStateChanged(ItemEvent check)
{
totalPrice = 200;
if (cocktailBox.getState())
{
totalPrice += cocktailPrice;
}
if (dinnerBox.getState())
{
totalPrice += dinnerPrice;
}
repaint();
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoCheckBoxGroup extends Applet implements ItemListener
{
String companyName = new String("Shin Liu's Incorporated");
Font bigFont = new Font("Arial",Font.PLAIN, 24);
Checkbox cocktailBox = new Checkbox("Cocktails");
Checkbox dinnerBox = new Checkbox("Dinner");
int cocktailPrice = 300, dinnerPrice = 600, totalPrice = 200;
int beefPrice = 100, fishPrice = 75;
CheckboxGroup dinnerGrp = new CheckboxGroup();
Checkbox chickenBox = new Checkbox("Chicken",false, dinnerGrp);
Checkbox beefBox = new Checkbox("Beef", false, dinnerGrp);
Checkbox fishBox = new Checkbox("Fish", false, dinnerGrp);
public void init()
{
add(cocktailBox);
cocktailBox.addItemListener(this);
add(dinnerBox);
dinnerBox.addItemListener(this);
add(chickenBox);
chickenBox.addItemListener(this);
add(beefBox);
beefBox.addItemListener(this);
add(fishBox);
fishBox.addItemListener(this);
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10,100);
gr.drawString("Event price estimate", 10,150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice), 280,150);
}
public void itemStateChanged(ItemEvent check)
{
totalPrice = 200;
if (cocktailBox.getState())
{
totalPrice += cocktailPrice;
}
if (dinnerBox.getState())
{
totalPrice += dinnerPrice;
}
Checkbox dinnerSelection = dinnerGrp.getSelectedCheckbox();
if (dinnerSelection == beefBox)
totalPrice += beefPrice;
else if (dinnerSelection == fishBox)
totalPrice += fishPrice;
else
chickenBox.setState(true);
repaint();
}
}
· Using the Choice class – When you want a user to select an option from a list, you can use a Choice object.
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoChoice extends Applet implements ItemListener
{
String companyName = new String("Shin Liu Incorporated");
Font bigFont = new Font("Arial", Font.PLAIN, 24);
int totalPrice = 0;
Choice entertainmentChoice = new Choice();
int[] actPrice = {0,725,325,125};
public void init()
{
add(entertainmentChoice);
entertainmentChoice.addItemListener(this);
entertainmentChoice.add("No entertainments");
entertainmentChoice.add("Rock band");
entertainmentChoice.add("Pianist");
entertainmentChoice.add("Clown");
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10,100);
gr.drawString("Price for entertainment", 10, 150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice), 280,150);
}
public void itemStateChanged(ItemEvent choice)
{
int actNum = entertainmentChoice.getSelectedIndex();
totalPrice = actPrice[actNum];
repaint();
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoList extends Applet implements ItemListener
{
String companyName = new String("Shin Liu Incorporated");
Font bigFont = new Font("Arial", Font.PLAIN, 24);
int totalPrice = 0;
List partyFavorList = new List();
int[] favorPrice = {8,10,25,35};
public void init()
{
add(partyFavorList);
partyFavorList.addItemListener(this);
partyFavorList.add("Hats");
partyFavorList.add("Streamers");
partyFavorList.add("Noise makers");
partyFavorList.add("Ballons");
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10,100);
gr.drawString("Price for favors", 10, 150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice),280,150);
}
public void itemStateChanged(ItemEvent check)
{
int favorNum = partyFavorList.getSelectedIndex();
totalPrice = favorPrice[favorNum];
repaint();
}
}
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class DemoList2 extends Applet implements ItemListener
{
String companyName = new String("Shin Liu Incorporated");
Font bigFont = new Font("Arial", Font.PLAIN, 24);
int totalPrice = 0;
List partyFavorList = new List();
int[] favorPrice = {8,10,25,35};
public void init()
{
add(partyFavorList);
partyFavorList.setMultipleMode(true);
partyFavorList.addItemListener(this);
partyFavorList.add("Hats");
partyFavorList.add("Streamers");
partyFavorList.add("Noise makers");
partyFavorList.add("Ballons");
}
public void paint(Graphics gr)
{
gr.setFont(bigFont);
gr.setColor(Color.magenta);
gr.drawString(companyName, 10,100);
gr.drawString("Price for favors", 10, 150);
gr.setColor(Color.blue);
gr.drawString(Integer.toString(totalPrice),280,150);
}
public void itemStateChanged(ItemEvent check)
{
int[] favorNum = partyFavorList.getSelectedIndexes();
totalPrice =0;
for (int x = 0; x < favorNum.length; ++x)
totalPrice += favorPrice[favorNum[x]];
repaint();
}
}