KEMBAR78
javaprogramming framework-ppt frame.pptx
BY
Dr.D.Gayathri Devi
Abstract Window Toolkit (AWT) is an API to develop GUI or window –
based applications in java.
A graphical user interface is built of graphical elements called
components. Typical components include such items as buttons, scrollbars, and
text fields.
Java AWT Components are platform dependent that is components are
displayed according to the view of operating system.
The Container class is a subclass of Component. Container class used to
display non-container class.
In java GUI can be design using some predefined classes. All these
classes are defined in java.awt package.
INTRODUCTION
java.awt class
TheAWT provides nine basic non-container component and three container
classes.
Java Provides 2 Frameworks for building GUI-based applications.
Those are
• AWT - (Abstract Window Toolkit)
• Swing
AWT-(Abstract Window Toolkit):
AWT (Abstract Window Toolkit) is an API to develop GUI
or window-based applications in java.
• The java.awt package provides classes for AWT API such as
TextField, Label, TextArea, Checkbox, Choice, List etc.
• AWT components are platform-dependent i.e. components are
displayed according to the view of operating system.
INTRODUCTION
• Component:
Component is an abstract class that contains various classes such as
Button, Label,Checkbox,TextField, Menu and etc.
• Container:
The Container is a component in AWT that can contain another
components like buttons, textfields, labels etc. The Container class extends
Frame and Panel.
• Window:
The window is the container that have no borders and menu bars. You
must use frame for creating a window.
• Frame:
The Frame is the container that contain title bar and can have menubars. It
can have other components like button, textfield etc.
• Panel:
The Panel is the container that doesn't contain title bar and menu bars. It
can have other components like button, textfield etc.
INTRODUCTION
Container class
Create simple AWT example, you need a frame. There
are two ways to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
Container class
Create simple AWT example, you need a frame. There
are two ways to create a GUI using Frame in AWT.
1. By extending Frame class (inheritance)
2. By creating the object of Frame class (association)
Container class
By extending Frame class (inheritance)
Ex:
class Example extends Frame
{
……..
}
Container class
By creating the object of Frame class (association)
Ex:
class Example
{
Frame obj=new Frame();
……..
}
import java.awt.*;
// extending Frame class to our class
AWTExample1
public class AWTExample1 extends Frame
{ // initializing using constructor
AWTExample1()
{ // creating a button
Button b = new Button("Click Me!!");
// setting button position on screen
b.setBounds(30,100,80,30);
// adding button into frame
add(b);
// frame size 300 width and 300 height
setSize(300,300);
// setting the title of Frame
setTitle("This is our basic AWT example");
// no layout manager
setLayout(null);
// now frame will be visible, by default it is not
visible
setVisible(true);
}
// main method
public static void main(String args[]) {
// creating instance of Frame class
AWTExample1 f = new AWTExample1();
}
}
Steps in frame
Step 1 Create an object of type Frame.
Step 2 Give the Frame object a size using setSize () method.
Step 3 - Make the Frame object appear on the screen by calling
setVisible () method.
Step 4 - In order to close the window by clicking the close(X) button, you
will have to insert the code for window closing event..
Frame Methods
setTitle(String) - used to set display user defined message
on title bar.
setBackground(color) - used to set background color.
setForeground(color) - used to set Foreground or text color.
setSize(dimension) - set the width and height for frame
setVisible(boolean) - set frame is visible or not.
setLayout() - used to set any layout to the frame .
add(component) - add component to the frame.
Frame example1
import java.awt.*;
public class AwtExample
{
public static void main(String[] args)
{
Frame f=new Frame(); f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
f.setTitle("Simple Example");
}
}
Frame example
import java.awt.*;
import java.awt.event.*;
Class FrameJavaExample
{
public static void main (String args[])
{
Frame frame = new Frame("Frame Java Example");
//set the size of the frame
frame.setSize(300,250);
frame.addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});
frame.setVisible(true);
}
}
Frame example
Add component to a Container
import java.awt.*;
class AddComponent
{
public static void main(String args[])
{
Frame frame = new Frame("Add Components to a Container");
Button button = new Button("OK");
frame.add(button);
frame.setSize(300,250);
frame.setVisible(true);
}
}
Component in container
Label
The object of the Label class is a component for placing text in a
container. It is used to display a single line of read only text. The text
can be changed by a programmer but a user cannot edit it directly.
Frame example
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
class SampleFrame extends Frame {
SampleFrame(String title) {
super(title);
MyWindowAdapter adapter = new MyWindowAdapter(this);
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString("This is in frame window", 40, 40);
}
}
class MyWindowAdapter extends WindowAdapter {
SampleFrame sf;
public MyWindowAdapter(SampleFrame sf) {
this.sf = sf;
}
Frame example (cont.,)
public void windowClosing(WindowEvent we) {
sfsetVisible(false);
}
}
public class testFrame extends Applet {
Frame f;
public void init() {
f = new SampleFrame("A Frame Window");
f.setSize(500, 500);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
OUTPUT
EVENT HANDLING
EVENT HANDLING (Cont)
Components defined in the AWT generate AWTEvents
Identify which events you wish to listen for (some components generate
more than one type of event)
Identify the Listener class which Listens for that event
Once we have identified the Listener interface, implement the Listener
interface
Our listener class must register with the component to received events
Call the addXXXListener method where XXX is the Event type.
HOW TO USE EVENTS
The following is a list of events in the java.awt.event package:
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
ItemEvent
KeyEvent
MouseEvent
TextEvent
WindowEvent
- Action has occurred (eg. Button
pressed)
- "Adjustable" Component changed
- Component Changed
- Container changed (add or remove)
- Focus Changed
- Item Selected or Deselected
- Keyboard event
- Mouse event
- Text Changed events
- Window related Events
AWT EVENT
The Following events have Listeners associated with them:
ActionEvent
AdjustmentEvent
ComponentEvent
ContainerEvent
FocusEvent
ItemEvent
KeyEvent
MouseEvent
TextEvent
WindowEvent
- ActionListener
- AdjustmentListener
- ComponentListener
- ContainerListener
- FocusListener
- ItemListener
- KeyListener
- MouseListener
- MouseMotionListener
- TextListener
- WindowListener
LISTENER INTERFACE
The ActionEvent is generated when button is clicked or the item of a
list is double clicked.
To write an Action Listener,follow the steps given below:
First declare an event handler class and specify that the class either
implements an ActionListener interface or extends a class that implements
an ActionListener interface.
For example
public class MyClass implements ActionListener
{
//abstract methods of ActionListener inteface
}
ActionEvent
ActionEvent Listener (cont)
Register an instance of the event handler class as a listener on one or more
components.
For example:
someComponent.addActionListener(instanceOfMyClass)
Include code that implements the methods in listener interface.
public void actionPerformed(ActionEvent e)
{
if(e.getSouce()==someComponent)
{
//code that reacts to the action
}
}
On entering the character from any source generates the key event.This
interface has 3 methods. These are
public void keyTyped(KeyEvent ae)
{
//active on typing a code…..
}
public void keyPressed(KeyEvent ae)
{
//active on pressing a key……
}
public void keyReleased(KeyEvent ae)
{
//active on realesing a key…..
}
KeyEvent
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
public class Key extends Applet implements KeyListener {
int X=20,
Y=30;
String msg="KeyEvents--->";
public void init() {
addKeyListener(this);
setBackground(Color.green);
setForeground(Color.blue);
}
public void keyPressed(KeyEvent k) {
showStatus("KeyDown");
int key=k.getKeyCode();
Key Event example
switch(key) {
case KeyEvent.VK_UP: //constant for non-numpad up arrow key
showStatus("Move to Up");
break;
case KeyEvent.VK_DOWN: //constant for non-numpad down arrow key
showStatus("Move to Down");
break;
case KeyEvent.VK_LEFT: //constant for non-numpad left arrow key
showStatus("Move to Left");
break;
case KeyEvent.VK_RIGHT: //constant for non-numpad right arrow key
showStatus("Move to Right");
break;
}
repaint();
}
Key Event example
OUTPUT
public void keyReleased(KeyEvent k) {
showStatus("Key Up");
}
public void keyTyped(KeyEvent k) {
msg+=k.getKeyChar();
repaint();
}
public void paint(Graphics g){
g.drawString(msg,X,Y);
}
}
Key Event example
Called just after the user presses a mouse button while the cursor is over
the listened-to component.
Called just after the user releases a mouse button after a mouse press
over the listened-to component
Called just after the user clicks the listened-to component.
Called just after the cursor enters the bounds of the listened-to component.
Called just after the cursor exits the bounds of the listened-to component.
Mouse Event
executed when mouse is dragged over the listened-to
component..
executed when mouse is moved over the listened-to
component
MouseMotionEvent
This class provide two interface methods:
focusGained:
Called just after the listened-to component gets the focus.
focusLost:
Called just after the listened-to component Loses the focus.
FocusEvent
import java.awt.*;
import java.awt.event.*;
public class FocusListenertest extends Frame implements
FocusListener
{
//initialization occur…
public FocusListenertest()
{
Label l;
add(b1=new Button ("First"),"South");
add(b2=new Button ("Second"),"North");
add(l);
b1.addFocusListener(this);
b2.addFocusListener(this);
setSize(200,200);
Example
}
public void focusGained(FocusEvent fe) {
if(fe.getSource()==b1)
{
l.setText("focus gained of first & Lost of second");
}
public void focusLost(FocusEvent fe) { if(fe.getSource()==b1)
{
l.setText("focus Lost of First & Gained of Second ");
}
Example
OUTPUT
OUTPUT
This class provide 8 interface methods:
windowOpened:
Called just after the listened-to window has been shown for the
first time.
windowClosing:
Called in response to a user request for the listened-to window to
be closed.To actually close the window ,the listener should invoke
the windowsdispose or setVisible(fasle) method.
windowClosed:
Called just after the listened-to window has closed.
windowIconified:
Called just after the listened-to window is iconified .
windowDeicoified:
Called just after the listened-to window is deiconified.
WindowEvent Listener
• windowActivated and windowDeactivated :
WindowEvent Class
itemStateChanged:
ItemEvent Class
• //where initialization occurs checkbox.addItemListener(this); ...
public void itemStateChanged(ItemEvent e)
{
if (e.getStateChange() == ItemEvent.SELECTED) {
label.setVisible(true); ... }
else
{ label.setVisible(false);
} }
Example
GRAPHICS PROGRAMMING
The AWT supports a rich assortment of graphics methods.All
graphics are drawn relative to a window.
Coordinates are specified in pixels.
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
(0, 0) X
(100, 40)
100
40
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
DRAWING A LINE
X
10
20
150
45
Y
g.drawLine (int startX,int startY,int endX,int endY);
g.drawLine (10, 20, 150, 45);
DRAWING A RECTANGLE
X
Y
g.drawRect (int top,int left,int width,int height);
g.drawRect (50, 20, 100, 40);
50
20
100
40
DRAWING AN OVAL
X
Y
g.drawOval (int top,int left,int width,int height);
g.drawOval (175, 20, 50, 80);
175
20
50
80
bounding
rectangle
DRAWING AN ARC
X
Y
g.drawArc(int x,int y,int width,int height,int sa,int aa);
g.drawArc (175, 20, 50, 80,0,90);
175
20
50
80
bounding
rectangle
THE COLOR CLASS
🞭 Colors in java are in java.awt.Color class
🞭 Class Constructor
🞭 Color(int r, int g , int b)
🞭 Creates an RGB color with specified red,green and
blue values in the range 0 to 255
RGB Value
0, 0, 0
0, 0, 255
0, 255, 255
255, 200, 0
255, 255, 255
255, 255, 0
Object
Color.black
Color.blue
Color.cyan
Color.orange
Color.white
Color.yellow
THE COLOR CLASS METHODS
Method name Meaning
getBlue()
getGreen()
getRed()
gets the blue component
gets the green component
gets the red component
getColor(String) Gets the specified color property
getColor(int) Gets the specified color property of the
color value
getRGB() Gets the RGB value representing the
color in the default RGB color model
FONTS
🞭 The AWT supports multiple type fonts.fonts have family
name,a logical font name, and a face name.
🞭 Fonts are encapsulated by the Font class.
 Font(String name,int fontStyle,int size);
Variable Meaning
String name Name of the font
Float pointsize Size of the font in points
Int size Size of the font in points
Int style Font style
THE FONT CLASS
Method Description
static Font decode(String str) Returns a font given its name.
boolean equals(Object FontObj) Returns true if the FontObj equals to
current Font otherwise it returns false.
String getFontName() Returns the face name of current font
String getName() Returns the logical name of the font.
int getSize() Returns the size
Int getStyle() returns the style values
boolean isBold() Returns true it the font includes the BOLD
style value, otherwise false.
boolean isItalic Returns true it the font includes the
ITALIC style value, otherwise false.
boolean isPlain Returns true it the font includes the PLAIN
style value, otherwise false.
String toSring() Returns the string equivalent of the
invoking font.
CREATING THE FONT
🞭 To use new font, we must first construct a Font object that
describes that font.
Font(String fontName,int fontStyle,int size)
fontName
fontStyle ~
~ name of the font
Font.PLAIN, Font.BOLD,
Font.ITALIC.
To combine use pipeline( | ).
🞭 Set the font to current program by calling the method
Void setFont(Font fontObj);
COLOR AND FONT EXAMPLE
i m p o r t j a v a . a wt . * ;
i m p o r t j a v a . a p p l e t . * ;
p u b l i c c l a s s F o n t D e m o e x t e n d s Ap p l e t {
F o n t f 1 ;
C o l o r c 1 , c 2 ;
p u b l i c v o i d i n i t ( ) {
c 1 = n e w C o l o r ( 1 0 0 , 1 2 0 , 1 0 0 ) ;
c 2 = n e w C o l o r ( 1 4 0 , 0 , 0 ) ;
f 1 = n e w F o n t ( “Ar i a l ” , F o n t . B O LD |F o n t . I TALI C , 4 0 ) ;
s e t B a c k g r o u n d ( c 1 ) ;
s e t F o r e g r o u n d ( c 2 ) ;
s e t F o n t ( f 1 ) ;
}
public void paint(Graphics g) {
g.drawString(“Hello World”,60,40);
}
}
OUTPUT
Color and Font example
AWT CONTROLS
🞭 AWT Supports the following types of controls.
List
Scroll bar
Text box
Text area
Label
Button
Check box
Check box Group
Choice list
To add controls you must create an window and add by following method.
Component .add(ComponentObj);
To remove call the following method
void remove(ComponentObj);
LABEL
🞭 A label displays a single line of read only text ,the label cannot
changed by the end user anyway.
Creating the Label
The following constructor used to create the Label
Label();
Label(String text);
Label(String text,int alignment);
the value of alignment must be one of these three
constants : Label.LEFT , Label.RIGHT ,
Label.CENTER.
LABEL
🞭 Set the text of the label by calling
void setText(String str);
🞭 Obtain the current label text by calling
String getText()
🞭 Set the Alignment of the label by calling
Void setAlignment(int align)
🞭 Obtain the current label Alignment by calling
int getAlignment()
This class represents a push-button which displays some specified text.
When a button is pressed, it notifies its Listeners. (More about Listeners
in the next chapter).
To be a Listener for a button, an object must implement the
ActionListener Interface.
Panel aPanel = new Panel();
Button okButton = new Button("Ok");
Button cancelButton = new Button("Cancel");
aPanel.add(okButton));
aPanel.add(cancelButton));
okButton.addActionListener(this);
cancelButton.addActionListener(this);
Buttons
This class is a Component which displays a list of Strings.
The list is scrollable, if necessary.
Sometimes called Listbox in other languages.
Lists can be set up to allow single or multiple selections.
The list will return an array indicating which Strings are selected
List aList = new List();
aList.add("Calgary");
aList.add("Edmonton");
aList.add("Regina");
aList.add("Vancouver");
aList.setMultipleMode(true);
List
This class represents a GUI checkbox with a textual label.
The Checkbox maintains a boolean state indicating whether it is
checked or not.
If a Checkbox is added to a CheckBoxGroup, it will behave like a radio
button.
Checkbox creamCheckbox = new CheckBox("Cream");
Checkbox sugarCheckbox = new CheckBox("Sugar");
[
if (creamCheckbox.getState())
{
coffee.addCream();
}
Checkbox
This class represents a dropdown list of Strings.
Similar to a list in terms of functionality, but displayed differently.
Only one item from the list can be selected at one time and the currently
selected element is displayed.
Choice aChoice = new Choice();
aChoice.add("Calgary");
aChoice.add("Edmonton");
aChoice.add("Alert Bay");
[
String selectedDestination= aChoice.getSelectedItem();
Choice
This class displays a single line of optionally editable text.
This class inherits several methods from TextComponent.
This is one of the most commonly used Components in theAWT
TextField emailTextField = new TextField();
TextField passwordTextField = new TextField();
passwordTextField.setEchoChar("*");
[…]
String userEmail = emailTextField.getText();
String userpassword = passwordTextField.getText();
Text Field
This class displays multiple lines of optionally editable text.
This class inherits several methods from TextComponent.
TextArea also provides the methods: appendText(), insertText() and
replaceText()
// 5 rows, 80 columns
TextArea fullAddressTextArea = new TextArea(5, 80);
[
String userFullAddress= fullAddressTextArea.getText();
Text Area
Since the Component class defines the setSize() and setLocation()
methods, all Components can be sized and positioned with those
methods.
Problem: the parameters provided to those methods are defined in
terms of pixels. Pixel sizes may be different (depending on the
platform) so the use of those methods tends to produce GUIs which
will not display properly on all platforms.
Solution: Layout Managers. Layout managers are assigned to
Containers. When a Component is added to a Container, its Layout
Manager is consulted in order to determine the size and placement of
the Component.
NOTE: If you use a Layout Manager, you can no longer change the
size and location of a Component through the setSize and
setLocation methods.
Layout Managers
There are several different LayoutManagers, each of which sizes and
positions its Components based on an algorithm:
FlowLayout
BorderLayout
GridLayout
For Windows and Frames, the default LayoutManager is BorderLayout.
For Panels, the default LayoutManager is FlowLayout.
Layout Managers (cont)
The algorithm used by the FlowLayout is to lay out
Components like words on a page: Left to right, top to
bottom.
It fits as many Components into a given row before moving
to the next row.
Panel aPanel = new Panel();
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Flow Layout
The BorderLayout Manager breaks the Container up into 5 regions
(North, South, East, West, and Center).
When Components are added, their region is also specified:
Frame aFrame = new Frame();
aFrame.add("North", new Button("Ok"));
aFrame.add("South", new Button("Add"));
aFrame.add("East", new Button("Delete"));
aFrame.add("West", new Button("Cancel"));
aFrame.add("Center", new Button("Recalculate"));
Border Layout
Center
The regions of the BorderLayout are defined as follows:
North
South
West East
Border Layout (cont)
The GridLayout class divides the region into a grid of equally sized rows
and columns.
Components are added left-to-right, top-to-bottom.
The number of rows and columns is specified in the constructor for the
LayoutManager.
Panel aPanel = new Panel();
GridLayout theLayout = new GridLayout(2,2);
aPanel.setLayout(theLayout);
aPanel.add(new Button("Ok"));
aPanel.add(new Button("Add"));
aPanel.add(new Button("Delete"));
aPanel.add(new Button("Cancel"));
Grid Layout
MENU BAR AND MENU
🞭 A menu bar displays a list of top-level menu choices
🞭 Each choice is associated with a drop-down menu
🞭 This concept is implemented in Java by the following classes
🞭 MenuBar
🞭 Menu
🞭 MenuItem
MENU BAR AND MENU (CONT)
🞭 In general, a menu bar contains one or more Menu
objects
🞭 Each Menu object contains a list of MenuItem objects
🞭 Each MenuItem object represents something that can be
selected by the user
MENUBAR AND MENU (CONT)
🞭 Following are the constructors for Menu:
🞭 Menu( )
🞭 Menu(String optionName)
🞭 Menu(String optionName, boolean removable)
🞭 Here, optionName specifies the name of the menu
selection
🞭 If removable is true, the pop-up menu can be removed
and allowed to float free
🞭 Otherwise, it will remain attached to the menu bar
MENUBAR AND MENU (CONT)
🞭 MenuItem defines these constructors
🞭 MenuItem( )
🞭 MenuItem(String itemName)
🞭 MenuItem(String itemName, MenuShortcut keyAccel)
🞭 Here, itemName is the name shown in the menu
🞭 keyAccel is the menu shortcut for this item
SAMPLE PROGRAM
// Illustrate menus.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="MenuDemo" width=250 height=250>
</applet>
*/
// Create a subclass of Frame
class MenuFrame extends Frame {
String msg = "";
CheckboxMenuItem debug, test;
MenuFrame(String title) {
super(title);
// create menu bar and add it to frame
MenuBar mbar = new MenuBar();
setMenuBar(mbar);
PROGRAM (CONT.)
// create the menu items
Menu file = new Menu("File");
MenuItem item1, item2, item3, item4, item5;
file.add(item1 = new MenuItem("New..."));
file.add(item2 = new MenuItem("Open..."));
file.add(item3 = new MenuItem("Close"));
file.add(item4 = new MenuItem("-"));
file.add(item5 = new MenuItem("Quit..."));
mbar.add(file);
Menu edit = new Menu("Edit");
MenuItem item6, item7, item8, item9;
edit.add(item6 = new MenuItem("Cut"));
edit.add(item7 = new MenuItem("Copy"));
edit.add(item8 = new MenuItem("Paste"));
edit.add(item9 = new MenuItem("-"));
PROGRAM (CONT.)
Menu sub = new Menu("Special");
MenuItem item10, item11, item12;
sub.add(item10 = new MenuItem("First"));
sub.add(item11 = new MenuItem("Second"));
sub.add(item12 = new MenuItem("Third"));
edit.add(sub);
// these are checkable menu items
debug = new CheckboxMenuItem("Debug");
edit.add(debug);
test = new CheckboxMenuItem("Testing");
edit.add(test);
mbar.add(edit);
// create an object to handle action and item events
MyMenuHandler handler = new MyMenuHandler(this);
PROGRAM (CONT.)
// register it to receive those events
item1.addActionListener(handler);
item2.addActionListener(handler);
item3.addActionListener(handler);
item4.addActionListener(handler);
item5.addActionListener(handler);
item6.addActionListener(handler);
item7.addActionListener(handler);
item8.addActionListener(handler);
item9.addActionListener(handler);
item10.addActionListener(handler);
item11.addActionListener(handler);
item12.addActionListener(handler);
debug.addItemListener(handler);
test.addItemListener(handler);
PROGRAM (CONT.)
// create an object to handle window events
MyWindowAdapter adapter = new MyWindowAdapter(this);
// register it to receive those events
addWindowListener(adapter);
}
public void paint(Graphics g) {
g.drawString(msg, 10, 200);
if(debug.getState())
g.drawString("Debug is on.", 10, 220);
else
g.drawString("Debug is off.", 10, 220);
if(test.getState())
g.drawString("Testing is on.", 10, 240);
else
g.drawString("Testing is off.", 10, 240);
}
}
PROGRAM (CONT.)
class MyWindowAdapter extends WindowAdapter {
MenuFrame menuFrame;
public MyWindowAdapter(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
public void windowClosing(WindowEvent we) {
menuFrame.setVisible(false);
}
}
class MyMenuHandler implements ActionListener, ItemListener {
MenuFrame menuFrame;
public MyMenuHandler(MenuFrame menuFrame) {
this.menuFrame = menuFrame;
}
PROGRAM (CONT.)
// Handle action events
public void actionPerformed(ActionEvent ae) {
String msg = "You selected ";
String arg = (String)ae.getActionCommand();
if(arg.equals("New..."))
msg += "New.";
else if(arg.equals("Open..."))
msg += "Open.";
else if(arg.equals("Close"))
msg += "Close.";
else if(arg.equals("Quit..."))
msg += "Quit.";
else if(arg.equals("Edit"))
msg += "Edit.";
else if(arg.equals("Cut"))
msg += "Cut.";
else if(arg.equals("Copy"))
msg += "Copy.";
PROGRAM (CONT.)
else if(arg.equals("Paste"))
msg += "Paste.";
else if(arg.equals("First"))
msg += "First.";
else if(arg.equals("Second"))
msg += "Second.";
else if(arg.equals("Third"))
msg += "Third.";
else if(arg.equals("Debug"))
msg += "Debug.";
else if(arg.equals("Testing"))
msg += "Testing.";
menuFrame.msg = msg;
menuFrame.repaint();
}
PROGRAM (CONT.)
// Handle item events
public void itemStateChanged(ItemEvent ie) {
menuFrame.repaint();
}
}
// Create frame window.
public class MenuDemo extends Applet {
Frame f;
public void init() {
f = new MenuFrame("Menu Demo");
int width = Integer.parseInt(getParameter("width"));
int height = Integer.parseInt(getParameter("height"));
setSize(new Dimension(width, height));
f.setSize(width, height);
f.setVisible(true);
}
public void start() {
f.setVisible(true);
}
public void stop() {
f.setVisible(false);
}
}
Sample output is shown here
Fig. 74.1 Output of MenuDemo
PROGRAM (CONT.)
THANK YOU

javaprogramming framework-ppt frame.pptx

  • 1.
  • 2.
    Abstract Window Toolkit(AWT) is an API to develop GUI or window – based applications in java. A graphical user interface is built of graphical elements called components. Typical components include such items as buttons, scrollbars, and text fields. Java AWT Components are platform dependent that is components are displayed according to the view of operating system. The Container class is a subclass of Component. Container class used to display non-container class. In java GUI can be design using some predefined classes. All these classes are defined in java.awt package. INTRODUCTION
  • 3.
    java.awt class TheAWT providesnine basic non-container component and three container classes.
  • 4.
    Java Provides 2Frameworks for building GUI-based applications. Those are • AWT - (Abstract Window Toolkit) • Swing AWT-(Abstract Window Toolkit): AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in java. • The java.awt package provides classes for AWT API such as TextField, Label, TextArea, Checkbox, Choice, List etc. • AWT components are platform-dependent i.e. components are displayed according to the view of operating system. INTRODUCTION
  • 5.
    • Component: Component isan abstract class that contains various classes such as Button, Label,Checkbox,TextField, Menu and etc. • Container: The Container is a component in AWT that can contain another components like buttons, textfields, labels etc. The Container class extends Frame and Panel. • Window: The window is the container that have no borders and menu bars. You must use frame for creating a window. • Frame: The Frame is the container that contain title bar and can have menubars. It can have other components like button, textfield etc. • Panel: The Panel is the container that doesn't contain title bar and menu bars. It can have other components like button, textfield etc. INTRODUCTION
  • 7.
    Container class Create simpleAWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. 1. By extending Frame class (inheritance) 2. By creating the object of Frame class (association)
  • 8.
    Container class Create simpleAWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. 1. By extending Frame class (inheritance) 2. By creating the object of Frame class (association)
  • 9.
    Container class By extendingFrame class (inheritance) Ex: class Example extends Frame { …….. }
  • 10.
    Container class By creatingthe object of Frame class (association) Ex: class Example { Frame obj=new Frame(); …….. }
  • 11.
    import java.awt.*; // extendingFrame class to our class AWTExample1 public class AWTExample1 extends Frame { // initializing using constructor AWTExample1() { // creating a button Button b = new Button("Click Me!!"); // setting button position on screen b.setBounds(30,100,80,30); // adding button into frame add(b); // frame size 300 width and 300 height setSize(300,300); // setting the title of Frame setTitle("This is our basic AWT example");
  • 12.
    // no layoutmanager setLayout(null); // now frame will be visible, by default it is not visible setVisible(true); } // main method public static void main(String args[]) { // creating instance of Frame class AWTExample1 f = new AWTExample1(); } }
  • 13.
    Steps in frame Step1 Create an object of type Frame. Step 2 Give the Frame object a size using setSize () method. Step 3 - Make the Frame object appear on the screen by calling setVisible () method. Step 4 - In order to close the window by clicking the close(X) button, you will have to insert the code for window closing event..
  • 14.
    Frame Methods setTitle(String) -used to set display user defined message on title bar. setBackground(color) - used to set background color. setForeground(color) - used to set Foreground or text color. setSize(dimension) - set the width and height for frame setVisible(boolean) - set frame is visible or not. setLayout() - used to set any layout to the frame . add(component) - add component to the frame.
  • 15.
    Frame example1 import java.awt.*; publicclass AwtExample { public static void main(String[] args) { Frame f=new Frame(); f.setSize(400,400); f.setLayout(null); f.setVisible(true); f.setTitle("Simple Example"); } }
  • 16.
    Frame example import java.awt.*; importjava.awt.event.*; Class FrameJavaExample { public static void main (String args[]) { Frame frame = new Frame("Frame Java Example"); //set the size of the frame frame.setSize(300,250); frame.addWindowListener(new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); frame.setVisible(true); } }
  • 17.
  • 18.
    Add component toa Container import java.awt.*; class AddComponent { public static void main(String args[]) { Frame frame = new Frame("Add Components to a Container"); Button button = new Button("OK"); frame.add(button); frame.setSize(300,250); frame.setVisible(true); } }
  • 19.
  • 20.
    Label The object ofthe Label class is a component for placing text in a container. It is used to display a single line of read only text. The text can be changed by a programmer but a user cannot edit it directly.
  • 21.
    Frame example import java.awt.*; importjava.awt.event.*; import java.applet.*; class SampleFrame extends Frame { SampleFrame(String title) { super(title); MyWindowAdapter adapter = new MyWindowAdapter(this); addWindowListener(adapter); } public void paint(Graphics g) { g.drawString("This is in frame window", 40, 40); } } class MyWindowAdapter extends WindowAdapter { SampleFrame sf; public MyWindowAdapter(SampleFrame sf) { this.sf = sf; }
  • 22.
    Frame example (cont.,) publicvoid windowClosing(WindowEvent we) { sfsetVisible(false); } } public class testFrame extends Applet { Frame f; public void init() { f = new SampleFrame("A Frame Window"); f.setSize(500, 500); f.setVisible(true); } public void start() { f.setVisible(true); } public void stop() { f.setVisible(false); } }
  • 23.
  • 24.
  • 25.
  • 26.
    Components defined inthe AWT generate AWTEvents Identify which events you wish to listen for (some components generate more than one type of event) Identify the Listener class which Listens for that event Once we have identified the Listener interface, implement the Listener interface Our listener class must register with the component to received events Call the addXXXListener method where XXX is the Event type. HOW TO USE EVENTS
  • 27.
    The following isa list of events in the java.awt.event package: ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent - Action has occurred (eg. Button pressed) - "Adjustable" Component changed - Component Changed - Container changed (add or remove) - Focus Changed - Item Selected or Deselected - Keyboard event - Mouse event - Text Changed events - Window related Events AWT EVENT
  • 28.
    The Following eventshave Listeners associated with them: ActionEvent AdjustmentEvent ComponentEvent ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent WindowEvent - ActionListener - AdjustmentListener - ComponentListener - ContainerListener - FocusListener - ItemListener - KeyListener - MouseListener - MouseMotionListener - TextListener - WindowListener LISTENER INTERFACE
  • 29.
    The ActionEvent isgenerated when button is clicked or the item of a list is double clicked. To write an Action Listener,follow the steps given below: First declare an event handler class and specify that the class either implements an ActionListener interface or extends a class that implements an ActionListener interface. For example public class MyClass implements ActionListener { //abstract methods of ActionListener inteface } ActionEvent
  • 30.
    ActionEvent Listener (cont) Registeran instance of the event handler class as a listener on one or more components. For example: someComponent.addActionListener(instanceOfMyClass) Include code that implements the methods in listener interface. public void actionPerformed(ActionEvent e) { if(e.getSouce()==someComponent) { //code that reacts to the action } }
  • 31.
    On entering thecharacter from any source generates the key event.This interface has 3 methods. These are public void keyTyped(KeyEvent ae) { //active on typing a code….. } public void keyPressed(KeyEvent ae) { //active on pressing a key…… } public void keyReleased(KeyEvent ae) { //active on realesing a key….. } KeyEvent
  • 32.
    import java.awt.*; import java.awt.event.*; importjava.applet.*; public class Key extends Applet implements KeyListener { int X=20, Y=30; String msg="KeyEvents--->"; public void init() { addKeyListener(this); setBackground(Color.green); setForeground(Color.blue); } public void keyPressed(KeyEvent k) { showStatus("KeyDown"); int key=k.getKeyCode(); Key Event example
  • 33.
    switch(key) { case KeyEvent.VK_UP://constant for non-numpad up arrow key showStatus("Move to Up"); break; case KeyEvent.VK_DOWN: //constant for non-numpad down arrow key showStatus("Move to Down"); break; case KeyEvent.VK_LEFT: //constant for non-numpad left arrow key showStatus("Move to Left"); break; case KeyEvent.VK_RIGHT: //constant for non-numpad right arrow key showStatus("Move to Right"); break; } repaint(); } Key Event example
  • 34.
    OUTPUT public void keyReleased(KeyEventk) { showStatus("Key Up"); } public void keyTyped(KeyEvent k) { msg+=k.getKeyChar(); repaint(); } public void paint(Graphics g){ g.drawString(msg,X,Y); } } Key Event example
  • 35.
    Called just afterthe user presses a mouse button while the cursor is over the listened-to component. Called just after the user releases a mouse button after a mouse press over the listened-to component Called just after the user clicks the listened-to component. Called just after the cursor enters the bounds of the listened-to component. Called just after the cursor exits the bounds of the listened-to component. Mouse Event
  • 36.
    executed when mouseis dragged over the listened-to component.. executed when mouse is moved over the listened-to component MouseMotionEvent
  • 37.
    This class providetwo interface methods: focusGained: Called just after the listened-to component gets the focus. focusLost: Called just after the listened-to component Loses the focus. FocusEvent
  • 38.
    import java.awt.*; import java.awt.event.*; publicclass FocusListenertest extends Frame implements FocusListener { //initialization occur… public FocusListenertest() { Label l; add(b1=new Button ("First"),"South"); add(b2=new Button ("Second"),"North"); add(l); b1.addFocusListener(this); b2.addFocusListener(this); setSize(200,200); Example
  • 39.
    } public void focusGained(FocusEventfe) { if(fe.getSource()==b1) { l.setText("focus gained of first & Lost of second"); } public void focusLost(FocusEvent fe) { if(fe.getSource()==b1) { l.setText("focus Lost of First & Gained of Second "); } Example
  • 40.
  • 41.
  • 42.
    This class provide8 interface methods: windowOpened: Called just after the listened-to window has been shown for the first time. windowClosing: Called in response to a user request for the listened-to window to be closed.To actually close the window ,the listener should invoke the windowsdispose or setVisible(fasle) method. windowClosed: Called just after the listened-to window has closed. windowIconified: Called just after the listened-to window is iconified . windowDeicoified: Called just after the listened-to window is deiconified. WindowEvent Listener
  • 43.
    • windowActivated andwindowDeactivated : WindowEvent Class
  • 44.
  • 45.
    • //where initializationoccurs checkbox.addItemListener(this); ... public void itemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { label.setVisible(true); ... } else { label.setVisible(false); } } Example
  • 47.
    GRAPHICS PROGRAMMING The AWTsupports a rich assortment of graphics methods.All graphics are drawn relative to a window. Coordinates are specified in pixels.
  • 48.
    COORDINATE SYSTEMS 🞭 Eachpixel 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 (0, 0) X (100, 40) 100 40
  • 49.
    DRAWING SHAPES 🞭 Ashape 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
  • 50.
    DRAWING A LINE X 10 20 150 45 Y g.drawLine(int startX,int startY,int endX,int endY); g.drawLine (10, 20, 150, 45);
  • 51.
    DRAWING A RECTANGLE X Y g.drawRect(int top,int left,int width,int height); g.drawRect (50, 20, 100, 40); 50 20 100 40
  • 52.
    DRAWING AN OVAL X Y g.drawOval(int top,int left,int width,int height); g.drawOval (175, 20, 50, 80); 175 20 50 80 bounding rectangle
  • 53.
    DRAWING AN ARC X Y g.drawArc(intx,int y,int width,int height,int sa,int aa); g.drawArc (175, 20, 50, 80,0,90); 175 20 50 80 bounding rectangle
  • 54.
    THE COLOR CLASS 🞭Colors in java are in java.awt.Color class 🞭 Class Constructor 🞭 Color(int r, int g , int b) 🞭 Creates an RGB color with specified red,green and blue values in the range 0 to 255 RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow
  • 55.
    THE COLOR CLASSMETHODS Method name Meaning getBlue() getGreen() getRed() gets the blue component gets the green component gets the red component getColor(String) Gets the specified color property getColor(int) Gets the specified color property of the color value getRGB() Gets the RGB value representing the color in the default RGB color model
  • 56.
    FONTS 🞭 The AWTsupports multiple type fonts.fonts have family name,a logical font name, and a face name. 🞭 Fonts are encapsulated by the Font class.  Font(String name,int fontStyle,int size); Variable Meaning String name Name of the font Float pointsize Size of the font in points Int size Size of the font in points Int style Font style
  • 57.
    THE FONT CLASS MethodDescription static Font decode(String str) Returns a font given its name. boolean equals(Object FontObj) Returns true if the FontObj equals to current Font otherwise it returns false. String getFontName() Returns the face name of current font String getName() Returns the logical name of the font. int getSize() Returns the size Int getStyle() returns the style values boolean isBold() Returns true it the font includes the BOLD style value, otherwise false. boolean isItalic Returns true it the font includes the ITALIC style value, otherwise false. boolean isPlain Returns true it the font includes the PLAIN style value, otherwise false. String toSring() Returns the string equivalent of the invoking font.
  • 58.
    CREATING THE FONT 🞭To use new font, we must first construct a Font object that describes that font. Font(String fontName,int fontStyle,int size) fontName fontStyle ~ ~ name of the font Font.PLAIN, Font.BOLD, Font.ITALIC. To combine use pipeline( | ). 🞭 Set the font to current program by calling the method Void setFont(Font fontObj);
  • 59.
    COLOR AND FONTEXAMPLE i m p o r t j a v a . a wt . * ; i m p o r t j a v a . a p p l e t . * ; p u b l i c c l a s s F o n t D e m o e x t e n d s Ap p l e t { F o n t f 1 ; C o l o r c 1 , c 2 ; p u b l i c v o i d i n i t ( ) { c 1 = n e w C o l o r ( 1 0 0 , 1 2 0 , 1 0 0 ) ; c 2 = n e w C o l o r ( 1 4 0 , 0 , 0 ) ; f 1 = n e w F o n t ( “Ar i a l ” , F o n t . B O LD |F o n t . I TALI C , 4 0 ) ; s e t B a c k g r o u n d ( c 1 ) ; s e t F o r e g r o u n d ( c 2 ) ; s e t F o n t ( f 1 ) ; }
  • 60.
    public void paint(Graphicsg) { g.drawString(“Hello World”,60,40); } } OUTPUT Color and Font example
  • 61.
    AWT CONTROLS 🞭 AWTSupports the following types of controls. List Scroll bar Text box Text area Label Button Check box Check box Group Choice list To add controls you must create an window and add by following method. Component .add(ComponentObj); To remove call the following method void remove(ComponentObj);
  • 62.
    LABEL 🞭 A labeldisplays a single line of read only text ,the label cannot changed by the end user anyway. Creating the Label The following constructor used to create the Label Label(); Label(String text); Label(String text,int alignment); the value of alignment must be one of these three constants : Label.LEFT , Label.RIGHT , Label.CENTER.
  • 63.
    LABEL 🞭 Set thetext of the label by calling void setText(String str); 🞭 Obtain the current label text by calling String getText() 🞭 Set the Alignment of the label by calling Void setAlignment(int align) 🞭 Obtain the current label Alignment by calling int getAlignment()
  • 64.
    This class representsa push-button which displays some specified text. When a button is pressed, it notifies its Listeners. (More about Listeners in the next chapter). To be a Listener for a button, an object must implement the ActionListener Interface. Panel aPanel = new Panel(); Button okButton = new Button("Ok"); Button cancelButton = new Button("Cancel"); aPanel.add(okButton)); aPanel.add(cancelButton)); okButton.addActionListener(this); cancelButton.addActionListener(this); Buttons
  • 65.
    This class isa Component which displays a list of Strings. The list is scrollable, if necessary. Sometimes called Listbox in other languages. Lists can be set up to allow single or multiple selections. The list will return an array indicating which Strings are selected List aList = new List(); aList.add("Calgary"); aList.add("Edmonton"); aList.add("Regina"); aList.add("Vancouver"); aList.setMultipleMode(true); List
  • 66.
    This class representsa GUI checkbox with a textual label. The Checkbox maintains a boolean state indicating whether it is checked or not. If a Checkbox is added to a CheckBoxGroup, it will behave like a radio button. Checkbox creamCheckbox = new CheckBox("Cream"); Checkbox sugarCheckbox = new CheckBox("Sugar"); [ if (creamCheckbox.getState()) { coffee.addCream(); } Checkbox
  • 67.
    This class representsa dropdown list of Strings. Similar to a list in terms of functionality, but displayed differently. Only one item from the list can be selected at one time and the currently selected element is displayed. Choice aChoice = new Choice(); aChoice.add("Calgary"); aChoice.add("Edmonton"); aChoice.add("Alert Bay"); [ String selectedDestination= aChoice.getSelectedItem(); Choice
  • 68.
    This class displaysa single line of optionally editable text. This class inherits several methods from TextComponent. This is one of the most commonly used Components in theAWT TextField emailTextField = new TextField(); TextField passwordTextField = new TextField(); passwordTextField.setEchoChar("*"); […] String userEmail = emailTextField.getText(); String userpassword = passwordTextField.getText(); Text Field
  • 69.
    This class displaysmultiple lines of optionally editable text. This class inherits several methods from TextComponent. TextArea also provides the methods: appendText(), insertText() and replaceText() // 5 rows, 80 columns TextArea fullAddressTextArea = new TextArea(5, 80); [ String userFullAddress= fullAddressTextArea.getText(); Text Area
  • 70.
    Since the Componentclass defines the setSize() and setLocation() methods, all Components can be sized and positioned with those methods. Problem: the parameters provided to those methods are defined in terms of pixels. Pixel sizes may be different (depending on the platform) so the use of those methods tends to produce GUIs which will not display properly on all platforms. Solution: Layout Managers. Layout managers are assigned to Containers. When a Component is added to a Container, its Layout Manager is consulted in order to determine the size and placement of the Component. NOTE: If you use a Layout Manager, you can no longer change the size and location of a Component through the setSize and setLocation methods. Layout Managers
  • 71.
    There are severaldifferent LayoutManagers, each of which sizes and positions its Components based on an algorithm: FlowLayout BorderLayout GridLayout For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the default LayoutManager is FlowLayout. Layout Managers (cont)
  • 72.
    The algorithm usedby the FlowLayout is to lay out Components like words on a page: Left to right, top to bottom. It fits as many Components into a given row before moving to the next row. Panel aPanel = new Panel(); aPanel.add(new Button("Ok")); aPanel.add(new Button("Add")); aPanel.add(new Button("Delete")); aPanel.add(new Button("Cancel")); Flow Layout
  • 73.
    The BorderLayout Managerbreaks the Container up into 5 regions (North, South, East, West, and Center). When Components are added, their region is also specified: Frame aFrame = new Frame(); aFrame.add("North", new Button("Ok")); aFrame.add("South", new Button("Add")); aFrame.add("East", new Button("Delete")); aFrame.add("West", new Button("Cancel")); aFrame.add("Center", new Button("Recalculate")); Border Layout
  • 74.
    Center The regions ofthe BorderLayout are defined as follows: North South West East Border Layout (cont)
  • 75.
    The GridLayout classdivides the region into a grid of equally sized rows and columns. Components are added left-to-right, top-to-bottom. The number of rows and columns is specified in the constructor for the LayoutManager. Panel aPanel = new Panel(); GridLayout theLayout = new GridLayout(2,2); aPanel.setLayout(theLayout); aPanel.add(new Button("Ok")); aPanel.add(new Button("Add")); aPanel.add(new Button("Delete")); aPanel.add(new Button("Cancel")); Grid Layout
  • 76.
    MENU BAR ANDMENU 🞭 A menu bar displays a list of top-level menu choices 🞭 Each choice is associated with a drop-down menu 🞭 This concept is implemented in Java by the following classes 🞭 MenuBar 🞭 Menu 🞭 MenuItem
  • 77.
    MENU BAR ANDMENU (CONT) 🞭 In general, a menu bar contains one or more Menu objects 🞭 Each Menu object contains a list of MenuItem objects 🞭 Each MenuItem object represents something that can be selected by the user
  • 78.
    MENUBAR AND MENU(CONT) 🞭 Following are the constructors for Menu: 🞭 Menu( ) 🞭 Menu(String optionName) 🞭 Menu(String optionName, boolean removable) 🞭 Here, optionName specifies the name of the menu selection 🞭 If removable is true, the pop-up menu can be removed and allowed to float free 🞭 Otherwise, it will remain attached to the menu bar
  • 79.
    MENUBAR AND MENU(CONT) 🞭 MenuItem defines these constructors 🞭 MenuItem( ) 🞭 MenuItem(String itemName) 🞭 MenuItem(String itemName, MenuShortcut keyAccel) 🞭 Here, itemName is the name shown in the menu 🞭 keyAccel is the menu shortcut for this item
  • 80.
    SAMPLE PROGRAM // Illustratemenus. import java.awt.*; import java.awt.event.*; import java.applet.*; /* <applet code="MenuDemo" width=250 height=250> </applet> */ // Create a subclass of Frame class MenuFrame extends Frame { String msg = ""; CheckboxMenuItem debug, test; MenuFrame(String title) { super(title); // create menu bar and add it to frame MenuBar mbar = new MenuBar(); setMenuBar(mbar);
  • 81.
    PROGRAM (CONT.) // createthe menu items Menu file = new Menu("File"); MenuItem item1, item2, item3, item4, item5; file.add(item1 = new MenuItem("New...")); file.add(item2 = new MenuItem("Open...")); file.add(item3 = new MenuItem("Close")); file.add(item4 = new MenuItem("-")); file.add(item5 = new MenuItem("Quit...")); mbar.add(file); Menu edit = new Menu("Edit"); MenuItem item6, item7, item8, item9; edit.add(item6 = new MenuItem("Cut")); edit.add(item7 = new MenuItem("Copy")); edit.add(item8 = new MenuItem("Paste")); edit.add(item9 = new MenuItem("-"));
  • 82.
    PROGRAM (CONT.) Menu sub= new Menu("Special"); MenuItem item10, item11, item12; sub.add(item10 = new MenuItem("First")); sub.add(item11 = new MenuItem("Second")); sub.add(item12 = new MenuItem("Third")); edit.add(sub); // these are checkable menu items debug = new CheckboxMenuItem("Debug"); edit.add(debug); test = new CheckboxMenuItem("Testing"); edit.add(test); mbar.add(edit); // create an object to handle action and item events MyMenuHandler handler = new MyMenuHandler(this);
  • 83.
    PROGRAM (CONT.) // registerit to receive those events item1.addActionListener(handler); item2.addActionListener(handler); item3.addActionListener(handler); item4.addActionListener(handler); item5.addActionListener(handler); item6.addActionListener(handler); item7.addActionListener(handler); item8.addActionListener(handler); item9.addActionListener(handler); item10.addActionListener(handler); item11.addActionListener(handler); item12.addActionListener(handler); debug.addItemListener(handler); test.addItemListener(handler);
  • 84.
    PROGRAM (CONT.) // createan object to handle window events MyWindowAdapter adapter = new MyWindowAdapter(this); // register it to receive those events addWindowListener(adapter); } public void paint(Graphics g) { g.drawString(msg, 10, 200); if(debug.getState()) g.drawString("Debug is on.", 10, 220); else g.drawString("Debug is off.", 10, 220); if(test.getState()) g.drawString("Testing is on.", 10, 240); else g.drawString("Testing is off.", 10, 240); } }
  • 85.
    PROGRAM (CONT.) class MyWindowAdapterextends WindowAdapter { MenuFrame menuFrame; public MyWindowAdapter(MenuFrame menuFrame) { this.menuFrame = menuFrame; } public void windowClosing(WindowEvent we) { menuFrame.setVisible(false); } } class MyMenuHandler implements ActionListener, ItemListener { MenuFrame menuFrame; public MyMenuHandler(MenuFrame menuFrame) { this.menuFrame = menuFrame; }
  • 86.
    PROGRAM (CONT.) // Handleaction events public void actionPerformed(ActionEvent ae) { String msg = "You selected "; String arg = (String)ae.getActionCommand(); if(arg.equals("New...")) msg += "New."; else if(arg.equals("Open...")) msg += "Open."; else if(arg.equals("Close")) msg += "Close."; else if(arg.equals("Quit...")) msg += "Quit."; else if(arg.equals("Edit")) msg += "Edit."; else if(arg.equals("Cut")) msg += "Cut."; else if(arg.equals("Copy")) msg += "Copy.";
  • 87.
    PROGRAM (CONT.) else if(arg.equals("Paste")) msg+= "Paste."; else if(arg.equals("First")) msg += "First."; else if(arg.equals("Second")) msg += "Second."; else if(arg.equals("Third")) msg += "Third."; else if(arg.equals("Debug")) msg += "Debug."; else if(arg.equals("Testing")) msg += "Testing."; menuFrame.msg = msg; menuFrame.repaint(); }
  • 88.
    PROGRAM (CONT.) // Handleitem events public void itemStateChanged(ItemEvent ie) { menuFrame.repaint(); } } // Create frame window. public class MenuDemo extends Applet { Frame f; public void init() { f = new MenuFrame("Menu Demo"); int width = Integer.parseInt(getParameter("width")); int height = Integer.parseInt(getParameter("height")); setSize(new Dimension(width, height)); f.setSize(width, height); f.setVisible(true); }
  • 89.
    public void start(){ f.setVisible(true); } public void stop() { f.setVisible(false); } } Sample output is shown here Fig. 74.1 Output of MenuDemo PROGRAM (CONT.)
  • 90.