javaprogramming framework-ppt frame.pptx

DrDGayathriDevi 56 views 90 slides Jun 11, 2024
Slide 1
Slide 1 of 90
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39
Slide 40
40
Slide 41
41
Slide 42
42
Slide 43
43
Slide 44
44
Slide 45
45
Slide 46
46
Slide 47
47
Slide 48
48
Slide 49
49
Slide 50
50
Slide 51
51
Slide 52
52
Slide 53
53
Slide 54
54
Slide 55
55
Slide 56
56
Slide 57
57
Slide 58
58
Slide 59
59
Slide 60
60
Slide 61
61
Slide 62
62
Slide 63
63
Slide 64
64
Slide 65
65
Slide 66
66
Slide 67
67
Slide 68
68
Slide 69
69
Slide 70
70
Slide 71
71
Slide 72
72
Slide 73
73
Slide 74
74
Slide 75
75
Slide 76
76
Slide 77
77
Slide 78
78
Slide 79
79
Slide 80
80
Slide 81
81
Slide 82
82
Slide 83
83
Slide 84
84
Slide 85
85
Slide 86
86
Slide 87
87
Slide 88
88
Slide 89
89
Slide 90
90

About This Presentation

Java


Slide Content

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 The AWT 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 C reate simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. By extending Frame class (inheritance) 2. By creating the object of Frame class (association)

Container class C reate simple AWT example, you need a frame. There are two ways to create a GUI using Frame in AWT. 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. set L a y o u t() - used to set any layout to the frame . add(component) - add component to the frame.

Frame example 1 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: Acti o n E ve n t AdjustmentEvent C o mp o n e ntEv e nt 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 C o mp o n e ntEv e nt ContainerEvent FocusEvent ItemEvent KeyEvent MouseEvent TextEvent Win d o w Ev e nt 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.*; p u b l ic cl a ss Key e x te n ds A p p l et im p l e me n ts K e y L i ste n er { int X=20, Y=30; String msg="KeyEvents--->"; public void init() { addKeyListener(this); setB a ckgr o u n d ( C o l o r.gre e n ); setForeground(Color.blue); } p u b l ic vo i d ke y Press ed (K e y E v e n t 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

O U T PUT 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 Mous e Moti o nEvent

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. FocusEve n t

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.addFo c u s Lis t ener ( thi s ); b2.addFo c u s Lis t ener ( thi s ); 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

O U TP U T

O U TP U T

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 ( , ) 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 r e c t a ng l e

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 r e c t a ng l e

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, 255 0, 255, 255 255, 200, 255, 255, 255 255, 255, O b j e c t Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow

THE COLOR CLASS METHODS Method name Meaning getBlue() g e t G re e n () 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

F ON T S 🞭 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 w t . * ; 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 A p 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 , 1 2 , 1 ) ; c 2 = n e w C o l o r ( 1 4 , , ) ; f 1 = n e w F o n t ( “ A r i a l ” , F o n t . B O L D | F o n t . I T A L I C , 4 ) ; 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 C o lor a n d F o nt e x a m ple

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(c a ncel B ut t o n )); 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(" E dmon t o n"); aLi s t . ad d ("Regina" ) ; aList.add("Vancouver"); aLi s t . s e t M ultipleMod e (t ru e); L i s t

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(); } C h eckbox

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(); C h oice

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 the AWT TextField emailTextField = new TextField(); TextField passwordTextField = new TextField(); passwordTextField.setEchoChar("*"); […] String userEmail = emailTextField.getText(); String userpassword = passwordTextField.getText(); T e x t F i e l d

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(); T e x t A r e a

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. L a y out M a n a g e rs

There are several different LayoutManagers, each of which sizes and positions its Components based on an algorithm: FlowLayout Borde r Layout GridLayout For Windows and Frames, the default LayoutManager is BorderLayout. For Panels, the default LayoutManager is FlowLayout. L a y out M a n a g e rs ( c ont)

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")); F l o w L a y out

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")); B o rder L a y out

C e nter The regions of the BorderLayout are defined as follows: North South W est East B o rder L a y out ( c on t )

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")); G r i d L a y o u t

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 AN D MENU ( CON T ) 🞭 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); item 1 0. a d d Acti o n L iste n er( h a n d l er); item11.addActionListener(handler); item 1 2. a d d Acti o n L iste n er( h a n d l er); debug.addItemListener(handler); test.addItemListener(handler);

P R OGRAM ( CON T .) // 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); } }

P R OGRAM ( CON T .) 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; }

P R OGRAM ( CON T .) // 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.";

P R OGRAM ( CON T .) 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 . set V is i b l e (fals e ); } } Sample output is shown here Fig. 74.1 Output of MenuDemo PROGRAM (CONT.)

THANK YOU