[go: up one dir, main page]

0% found this document useful (0 votes)
117 views41 pages

Unit Iv

Event handling in Java involves three main components: event sources that generate events, listeners that receive notification of events, and event classes that describe the type of event. Common events come from mouse, keyboard, and UI controls. The java.awt.event package defines event classes and listener interfaces. Setting a listener on a source allows it to receive event notifications when the source generates an event.

Uploaded by

uday franklin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
117 views41 pages

Unit Iv

Event handling in Java involves three main components: event sources that generate events, listeners that receive notification of events, and event classes that describe the type of event. Common events come from mouse, keyboard, and UI controls. The java.awt.event package defines event classes and listener interfaces. Setting a listener on a source allows it to receive event notifications when the source generates an event.

Uploaded by

uday franklin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIV - IV

Event Handling: Events, Event sources, Event classes, Event Listeners, Event Delegation model,
handling mouse and key board events, Adapter classes, inner classes.

AWT: Class hierarchy, user- interface components- labels, button, canvas, scrollbars, text
components, checkbox, checkbox groups, choices, list panes-scroll pane, dialogs, menu bar,
graphics, layout manager- layout manager types- boarder, grid, flow, card and grid bag.

Event Handling in Java


Event :
Changing the state of an object is known as an event.
For example, click on button, dragging mouse etc.
The java.awt.event package provides many event classes and Listener interfaces
for event handling.
The object responsible for performing the task when the event occurs is called the
event Handler.
Events are support by the java.awt.event package.
These events are passed by your applet in a variety of ways; with the specific
method depending upon the actual event.
There are several types of events. The most commonly handled events are
those generated by the mouse, the keyboard, and various controls, such as a push
buttons.
Event handling classes are kept in package java.awt.event.
Three objects are involved in the event handling.
1. the source(object that generates an event)
2. listeners(object that is notified when an event occurs)
3. event(object that describe a state change in a source)
The source object (such as Button and TextField) interacts with the user.
Upon triggered , it creates an event object.
This event object will be messaged to all the registered listener objects
and an appropriate event handler method of the listeners is called back to
provide the response.
source object-registers the listeners. when an event occurs, all
registered listeners are notified and receive a copy of the event object.
sources of events : They can be either components of GUI or any other cass derived from a
component which can generate event like mouseclick.

EventSource Description

Button Generates action events when the


button is pressed
CheckBox Generates item events when the
check box is selected or deselected
List Generates actionevents , when an
item is double clicked, or selected or
deselected
ScrollBar Generates adjustment events when
the scroll bar is manipulated
Window Generates window events when a
window is activated, closed,
deactivated, opened or quit

java.awt.event package:
the java.awt.event package provide interfaces and classes for dealing
with different types of events fired by AWT components. This package
includes the definition of events classes, listeners interface and adapters
classes, which form the basics of event handling.
Event classes:
The package java.awt.event defines several types of events that are
generated by various user interface elements.
Event class Description
ActionEvent Generated when a button is pressed, a list item is
double-clicked, or a menu item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved,
resized, or becomes visible.
ContainerEvent Generated when a component is added or removed
from a container
FocusEvent Generated when a component gains or loses
keyboard focus
InputEvent Abstract superclass for all component input event
classes
ItemEvent Generated when a check box or list item is clicked;
also occurs when a choice selection is made or a
checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the
keyboard.
MouseEvent Generated when the mouse is dragged or moved,
clicked, pressed, or released ; also generated when
the mouse enter or exits a component
TextEvent Generated when the value of a text area or text
field is changed.
WindowEvent Generated when a window is activated, closed,
deactivated, deiconified, iconified,opened or quit.

Event listeners :
Event listeners are created by implementing one or more interfaces
defined by the java.awt.event package. whenever a source generates an
event, it basically invokes the appropriate method defined in the listener
interface. The method has an event object passed as an argument to it.
Some of the frequently used listeners are :
Interface Description
ActionListener This interface has only one method having this
signature

void actionPerformed(ActionEvent e){}

it is invoked when any action event is performed.

KeyListener This interface has 3 methods defined as

void keyPressed(KeyEvent e)

void keyReleased(KeyEvent e)

void keyTyped(KeyEvent e)

they are invoked when a key is pressed , released or


typed
ItemListener Defines one method to recognize when the state of an
item changes

Void itemStateChanged(ItemEvent e)
TextListener Defines one method to recognize change in text or text
area

Void textChanged(TextEvent e)
MouseListener Defines 5 methods to recognize when the mouse is
clicked, enters a component, exits a component, is
pressed or is released.

void mouseClicked(MouseEvent e)

void mouseEntered(MouseEvent e)

void mousePressed(MouseEvent e)
void mouseReleased(MouseEvent e)

void mouseExited(MouseEvent e)
MouseMotionListener Defines two methods to recognize when the mouse is
dragged or moved.

void mouseMoved(MouseEvent e)

void mouseDragged(MouseEvent e)
WindowListener Defines seven methodsto recognize when a window is
activated, closed, deactivated, iconified, deiconified,
opened or quit.

void windowOpened(WindowEvent e)

void windowActivated(WindowEvent e)

void windowClosed(WindowEvent e)

void windowClosing(WindowEvent e)

void windowDeactivated(WindowEvent e)

void windowIconified(WindowEvent e)

void windowDeiconified(WindowEvent e)
AdjustmentListener Defines one method to recognize adjustment event

void adjustmentValueChanged(AdjustmentEvent e)

Event delegation Model


The delegation model is one of the sophisticated technique used to handle
events in GUI programming languages. The modern approach to handling events is
based on the delegation event model, which defines standard and consistent
mechanisms to generate and process events.
The delegation event model provides a standard mechanism for a source to
generate an event and send it to set of listeners. The listener simply waits until it
receives an event. Once received, the listener processes the event and then returns.
The advantage of this design is that the application logic that processes
events is cleanly separated from the user interface logic that generate those events.
In event-driven programming a piece of event handling codes is executed
when an event was fired in response to an user input(such as clicking a mouse
button or hitting the ENTERkey). This is unlike the procedural model, where codes
are executed in a sequential manner.
Handling Mouse Events:
To handle mouse events, we must implement the MouseListener and the
MouseMotionListener interface
Ex : write java program to handle mouse events
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code=MouseApplet.class height=1000 width =1000>
</Applet>*/

public class MouseApplet extends Applet implements MouseListener,


MouseMotionListener
{
String msg;
public void init()
{
addMouseListener(this);
addMouseMotionListener(this);
}

public void mouseClicked(MouseEvent e)


{
msg="mouse clicked";
repaint();
}
public void mouseEntered(MouseEvent e)
{
msg="mouse Entered";
repaint();
}

public void mouseExited(MouseEvent e)


{
msg="mouse Exited";
repaint();
}
public void mousePressed(MouseEvent e)
{
msg="mouse pressed";
repaint();
}

public void mouseReleased(MouseEvent e)


{
msg="mouse released";
repaint();
}

public void mouseMoved(MouseEvent e)


{
msg="mouse moved";
repaint();
}

public void mouseDragged(MouseEvent e)


{
msg="mouse dragged";
repaint();
}

public void paint(Graphics g)


{
g.drawString(msg,75,75);
}

}
save : MouseApplet.java
compile : javac MouseApplet.java
run : appletviewer MouseApplet.java

Ex : write java program to demonstrate key event listeners


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*<Applet code="KeyboardApplet.class" height=1000 width=1000>
</Applet>*/
public class KeyboardApplet extends Applet implements KeyListener
{
String str1="" , str2="";
public void init()
{
addKeyListener(this);
}
public void paint(Graphics g)
{
g.drawString(str1,75,75);
g.drawString(str2,75,100);
}

public void keyPressed(KeyEvent e)


{
str1="you pressed key";
repaint();
}

public void keyReleased(KeyEvent e)


{
str1="you released key";
repaint();
}

public void keyTyped(KeyEvent e)


{
str2= str2+ e.getKeyChar();
repaint();
}
}
save : KeyboardApplet.java
compile : javac KeyboardApplet.java
run: appletviewer KeyboardApplet.java
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the adapter
class, you will not be forced to provide the implementation of all the methods of listener interfaces. So
it saves code.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event packages. The
Adapter classes with their corresponding listener interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

ComponentAdapter ComponentListener

ContainerAdapter ContainerListener

HierarchyBoundsAdapter HierarchyBoundsListener

Java inner class :

Java inner class or nested class is a class that is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place to be more
readable and maintainable.

Additionally, it can access all the members of the outer class, including private data
members and methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
}
}

AWT:
Java AWT (Abstract Window Toolkit) is an API( Application Program
Interface) to develop GUI or window-based applications in java.

Java AWT components are platform-dependent i.e. components are


displayed according to the view of operating system. AWT is
heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT API such


as TextField, Label, TextArea, radioButton, CheckBox, Choice, List etc.

why AWT?
Each application developed in a programming languages must have a user
interface, which is actually that part of the application that is responsible for
directly interacting with the user.
These user interfaces can either be
1. command line interface
2. graphical user interface
The awt is a well – designed object-oriented interface between the application
and the low level resources. So that programmers need not worry about tracking
the mouse movements or reading the keyboard characters or writing to the
screen.
The hierarchy of Java AWT classes are given below.
Container
The Container is a component in AWT that can contain another components
like buttons, textfields, labels etc. The classes that extends Container class are
known as container such as Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use
frame, dialog or another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have
other components like button, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can
have other components like button, textfield etc.
Useful Methods of Component class

Method Description

public void add(Component c) inserts a component on this component.

public void setSize(int width,int height) sets the size (width and height) of the component.

public void setLayout(LayoutManager m) defines the layout manager for the component.

public void setVisible(boolean status) changes the visibility of the component, by default false.

Component class :

component class is sub class of object class and super class of various
classes such as Button, Label , CheckBox etc.

In order to have a particular component in a window , you must add that


particular component to the window using add method.

Ex :

Label l = new Label(“RollNo”);

add(l);

If we wish to remove a component from a window, we can use remove() method.

Button:
The button class is used to create a labeled button that has platform
independent implementation. The application result in some action when
the button is pushed.
constructors for creating a Button:

1. Button() throws HeadlessException

This will create a Button with no label displayed on it.

syntax : Button buttonname = new Button();

2. Button(String str) throws Headless Exception

This will create a Button displaying the string ‘str’ on it.

Syntax: Button buttonname = new Button(str)

Once the object for Button is created, it needs to be added to the


applet, frame or any other container as

add(buttonname);

Ex: Button b= new Button(“yes”);

add(b);

Ex : write java program to create a Button


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="MyButton.class" height=800 width=800>
</Applet>
*/

public class MyButton extends Applet implements ActionListener


{
String s="";
public void init()
{
Button b1= new Button("yes");
Button b2= new Button("no");
add(b1);
add(b2);
b1.addActionListener(this);
b2.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
s=a.getActionCommand()+" Button pressed";
repaint();
}
public void paint(Graphics g)
{
g.drawString(s,50,50);
}
}
Ex: Java program to change the background color when button is pressed
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=MyButton1.class height=600
width=600>
</Applet>
*/
public class MyButton1 extends Applet

implements ActionListener
{
String s="";
public void init()
{
Button b1 =new Button("red");
Button b2 =new Button("Green");
Button b3 =new Button("Yellow");
add(b1);
add(b2);
add(b3);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
s=a.getActionCommand();
repaint();
}
public void paint(Graphics g)
{
if(s.equals("red"))
setBackground(Color.red);
if(s.equals("Green"))
setBackground(Color.green);
if(s.equals("Yellow"))
setBackground(Color.yellow);
}
}

Label :
Labels consist of a text String for display only and they never call an action
method.
The Constructors responsible for creating labels are:
Label() : creates an empty label
Label(String label):creates a new label with the specified string of text, left
justified
Label(String label,int alignment) : constructs a new label that presents the
specified string of text with the specified alignment.

syntax :
Label labelname = new Label(str);
Ex :
Label l = new Label(“Rollno”);

after creating a label add it using add(labelname)


Ex : java program to create labels

import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <Applet code=MyLabel.class height=600
width=600>
</Applet>
*/
public class MyLabel extends Applet
{
public void init()
{
Label l1=new Label("RollNo");
Label l2=new Label("Name");
Label l3=new Label("Marks");
add(l1);
add(l2);
add(l3);
}
}
Checkbox():

checkboxes are used as on-off (or) yes –no switches since every time you
click on one, you toggle to the opposite selection, i.e, if you click on an unchecked
checkbox, it will get checked and if you click on the checked box, it will get
unchecked.
The checkboxes are the objects of Checkbox class, which support the
following constructors.
Checkbox()
Checkbox(String s)
Checkbox(String s, boolean b)
Checkbox(String s,CheckBoxGroup cbg, Boolean b)

Ex :
Checkbox c= new Checkbox(“Names”, null,false)
false indicates it is unchecked. once after creating the checkbox, add it to
the applet as
add(c);
Ex:write java program to create check boxes
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code="MyCheckbox" height=600 width=600>
</Applet>
*/
public class MyCheckbox extends Applet implements ActionListener
{
Button b;
Checkbox c1;
Checkbox c2;
Checkbox c3;
Font f;
public void init()
{
c1=new Checkbox("rama");
c2=new Checkbox("sita");
c3=new Checkbox("laxman");
Button b = new Button("SUBMIT");
f=new Font("Arial" , Font.ITALIC,20);
add(c1);
add(c2);
add(c3);
add(b);
b.addActionListener(this);
}
public void actionPerformed(ActionEvent a)
{
String s= a.getActionCommand();
if(s.equals("SUBMIT"))
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.setFont(f);
if(c1.getState())
g.drawString("Rama",50,50);

if(c2.getState())
g.drawString("Sita",50,90);

if(c3.getState())
g.drawString("Laxman",50,120);
}}

Radio Butons :
Radio buttons, which are also called checkboxgroups, are a special
kind ofcheckboxes, where within a particular group, only one box can be selected
at a time.
CheckboxGroup class is used to group together a set of checkboxes and
there after only a single selection is allowed among them i.e, they behave as radio
buttons. There is only one constructor which creates an empty group. The
following line will create a checkbox group named fruits.
CheckboxGroup fruits=new CheckboxGroup();
once you create the checkbox group, add the individual checkboxes to that
group as
add(new Checkbox(“mango”,fruits,false));
add(new Checkbox(“papaya”,fruits,false));
add(new Checkbox(“apple”,fruits,false));etc
Ex : write java program to create radio buttons
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*
<Applet code=MyRadio.class height=800 width=800>
</Applet>
*/
public class MyRadio extends Applet implements ItemListener
{
Checkbox c1;
Checkbox c2;
CheckboxGroup cbg;
String s="";

public void init()


{
cbg=new CheckboxGroup();
c1=new Checkbox("Male",cbg,false);
c2=new Checkbox("Female",cbg,false);
add(c1);
add(c2);
Label l=new Label("click the button to select the gender");
add(l);
c1.addItemListener(this);
c2.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
g.setColor(Color.red);
s="Your gender is " + cbg.getSelectedCheckbox().getLabel();
g.drawString(s,10,100);
}
}

List boxes:
list class provides a compact, multiple choice scrolling selection list. List object can
be constructed to show any no of choices in the visible window.
constructors used for creating list are
List()
List(int norows)
List(int norows,boolean multiselection);
to add a selection to the list call add
void add(String name);
void add(String, int index);
for lists that allow only single selection we use
String getSelectionItem()
int getSelectedIndex()
for lists that allow multiple selection we use
String[] getSelectedItem();
int[] getSelectedIndexes();

Ex : java program to create list box


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/*<Applet code=MyList.java height=600 width=600>
</Applet>
*/
public class MyList extends Applet implements ItemListener
{
String s="";
List li;
public void init()
{
Label l=new Label("select fruits you like");
add(l);
li=new List(4,true);
li.add("Apple");
li.add("Mango");
li.add("banana");
li.add("pine apple");
add(li);
li.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
String a[]=li.getSelectedItems();
s= "Fruits i like are";
for(int i=0;i<a.length;i++)
s=s+" , " + a[i];
g.drawString(s,10,100);
}

choice boxes :

The choice class is lot like a list, but it allows you to conserve space , since
it provides a pop up menu of text string choices. The current choice is displayed on
top.Inorder to work with a choice box, an instance of choice class must be created
as

Choice c = new Choice();

now we can add items as

c.add(“India”);

c.add(“America”) etc.

Ex : Java program to create choice box


import java.awt.*;
import java.applet.*;
import java.awt.event.*;
/* <Applet code=MyChoice.class height=600 width=600>
</Applet>
*/
public class MyChoice extends Applet implements ItemListener
{
String msg="";
Choice c;
public void init()
{
Label l=new Label("select ur country");
add(l);
c=new Choice();
c.add("India");
c.add("America");
c.add("Japan");
c.add("Germany");
add(c);
c.addItemListener(this);
}
public void itemStateChanged(ItemEvent e)
{
repaint();
}
public void paint(Graphics g)
{
msg="Your country is "+c.getSelectedItem();
g.drawString(msg,10,100);
}
}

Container class :
containers allow us to organize components into manageable
groups which are extremely important in order to create a good user
interface. The AWT provides 4 container classes.
1.Panels
2.Window
3.Dialog
4.Frame
1.Panel :
It is a generic container for holding components. An instance of the
panel class provides a container to which components can be added.
The definition of Panel class is
public class Panel extends Container implements Accessible
constructors of Panel class:
Panel() -> creates a new panel using the default layout manager.
Panel(LayoutManager layout)-> creates a new panel with specified
layout.
How to use Panels:
Steps to follow while creating a panel are:
1. Create the panel by writing the following piece of code.
Panel panel = new Panel();
2. Add components to Panel by using add() method.
Panel.add(componenet) ;etc

2.Window:
This class creates a top-level window. Top-level window means
that it is not contained within any other object. It has the following
signature.
public class Window extends Container implements Accessible

3.Frame:
If you are not creating an applet, then you will be most likely
creating a Frame window.
The constructors responsible for creating a Frame are
1. Frame() -> creates a frame without title.
2. Frame(String title) -> creates a frame with title.
steps to create a Frame are
1. create an instance of the main frame
2. set the frame width and height
3. display the frame

Ex: Demonstration of Frame class


import java.awt.*;
public class MyFrame extends Frame
{
public MyFrame(String title)
{
super(title);
}
public static void main(String[] args)
{
MyFrame f= new MyFrame("Frame Demo");
f.setSize(200,300);
f.setVisible(true);
}
}
Layout:
A layout manager automatically arranges AWT controls within a
window by using some type of algorithm.
Each container object has a layout manager associated with it.
The layout manager is set by the setLayout() method. If no call to
setLayout() method is made, then the default layout manager is used.
General format of setLayout() is
void setLayout(LayoutManager obj);
If we wish to position the controls manually make obj as null.
Different layouts are :
1.FlowLayout
2.BorderLayout
3.GridLayout
4.CardLayout
5.GridBagLayout
1.FlowLayout:
Here the components are arranged in a row/line, within a container
when the row is filled completely, the components begin to group in the
next row.
constructors:
1.FlowLayout()
2.FlowLayout(int how)
3.FlowLayout(int how,int horz, int ver)
how is how each line is aligned, it can be
FlowLayout.LEFT
FlowLayout.RIGHT
FlowLayout.CENTER
horz,ver are horizontal and vertical gaps.

Example of flowlayout
2.BorderLayout:
Here the components can be arranged and resized to fit in five
different regions : north, east, south, west and center. There can be only
one component in each region and the regions are identified as constants
NORTH, SOUTH,EAST,WEST and CENTER.
Any of these five constant names can be used while adding a component
to a container.
constructors :
BorderLayout()
BorderLayout(int horz, int ver)
3. GridLayout():
The GridLayout class is a layout manager which can be used to
arrange controls in a container component in a rectangular grid. It has
specified number of rows and columns , where the container is divided
into equal sized rectangles and one component is placed in each
rectangle.
constructors:
1.GridLayout()->creates single column layout
2. GridLayout(int rows, int cols) ->creates a layout with no of rows
and columns.

Example of gridlayout:
4.CardLayout:
It stores several different layouts. Each layout can be thought of as
being on a separate index card in a deck that can be shuffled so that any
card is on top at a given time.
constructors
CardLayout()
CardLayout(int horz,int ver)
5.GridBagLayout:
using GridBagLayout class, we can arrange components in a
more controlled way on horizontal as well in vertical direction.
Ex:java program to illustrate FlowLayout.
import java.awt.*;
public class MyFlow extends Frame
{
MyFlow()
{
Button b1=new Button("NORTH");
Button b2=new Button("SOUTH");
Button b3=new Button("EAST");
Button b4=new Button("WEST");
Button b5=new Button("CENTER");
setLayout(new FlowLayout());
add(b1);
add(b2);
add(b3);
add(b4);
add(b5);
setSize(500,500);
setVisible(true);
}
public static void main(String args[])
{
new MyFlow();
}}
Ex: java program to illustrate Borderlayout
import java.awt.*;
public class MyBorder extends Frame
{
MyBorder()
{
Button b1=new Button("NORTH");
Button b2=new Button("SOUTH");
Button b3=new Button("EAST");
Button b4=new Button("WEST");
Button b5=new Button("CENTER");
//setLayout(new FlowLayout());
setLayout(new BorderLayout());
add(b1,BorderLayout.NORTH);
add(b2,BorderLayout.SOUTH);
add(b3,BorderLayout.EAST);
add(b4,BorderLayout.WEST);
add(b5,BorderLayout.CENTER);
setSize(500,500);
setVisible(true);
}
public static void main(String args[])
{
new MyBorder();
}
}
Ex: java program to illustrat Grid Layout
import java.awt.*;

public class MyGridLayout


{
Frame f;
MyGridLayout()
{
f=new Frame();
Button b1=new Button("1");
Button b2=new Button("2");
Button b3=new Button("3");
Button b4=new Button("4");
Button b5=new Button("5");
Button b6=new Button("6");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);

f.setLayout(new GridLayout(2,3));
//setting grid layout of 2 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args)
{
new MyGridLayout();
}
}

Menubar:
Java AWT MenuItem and Menu:
The object of MenuItem class adds a simple labeled menu item on menu.
The items used in a menu must belong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on
the menu bar. It inherits the MenuItem class.

AWT MenuItem class declaration

public class MenuItem extends MenuComponent implements Accessible

AWT Menu class declaration

public class Menu extends MenuItem implements MenuContainer, Accessible

Example
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class MyMenu
{
Frame f;
MyMenu()
{
f=new Frame("Testing Menus");
}
public void createmenu()
{
MenuBar mb=new MenuBar();
f.setMenuBar(mb);
Menu m1=new Menu("File");
Menu m2=new Menu("Edit");
MenuItem mt1=new MenuItem("New");
MenuItem mt2=new MenuItem("Open");
MenuItem mt3=new MenuItem("cut");
MenuItem mt4=new MenuItem("copy");
m1.add(mt1);
m1.add(mt2);
m2.add(mt3);
m2.add(mt4);
mb.add(m1);
mb.add(m2);
f.setVisible(true);
f.setSize(500,500);
}
public static void main(String a[])
{
MyMenu m = new MyMenu();
m.createmenu();
}
}
output:

Scrollbar:
The object of Scrollbar class is used to add horizontal and vertical
scrollbar.Scrollbar is a GUI component allows us to see invisible
number of rows and columns.
AWT Scrollbar class declaration:
public class Scrollbar extends Component implements djustable,Accessible

Example:

import java.awt.*;
class ScrollbarExample
{
ScrollbarExample()
{
Frame f=new Frame(“Scrollbar Example”);
Scrollbar s = new Scrollbar();
s.setBounds(100,100,50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ScrollbarExample();
}
}

output:

You might also like