Abstract Window Toolkit: (AWT) : Java AWT Classes Hierarchy
Abstract Window Toolkit: (AWT) : Java AWT Classes Hierarchy
Class Description
o Component class is at the top of AWT hierarchy.
o Component is an abstract class that encapsulates all attribute of visual
component.
Component
o Component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user.
Examples: buttons, checkboxes, list, scrollbars etc.
o Container is a component that can contain other components like
buttons, textfields, labels etc. in a specific layout.
o It is a subclass of component class.
Container o It keeps track of components that are added to another component.
o In “Front to back” order components are listed within the container.
o The classes that extend Container class are known as container such as
Frame, Dialog and Panel.
o Window is the container that has no borders and menu bars.
Window o It is a rectangular area which is displayed on the screen.
o You must use frame, dialog or another window for creating a window.
o Panel is the container that doesn't contain title bar and menu bars.
o It can have other components like button, textfield etc.
Panel
o It is concrete subclass of Container.
o The default LayoutManager of Panel is Flow Layout.
o Frame is the container that has title bar, menu bar, borders, and resizing
corners.
Frame
o It is a top-level window & subclass of the Window class.
o It can have other components like button, textfield etc.
o Dialog is a window that takes input from the user.
Dialog
o It is used to display message, list of options etc.
Constructor Description
Canvas() This constructor creates instance of a Canvas.
Canvas(GraphicsConfiguration This constructor creates instance of a Canvas with the given object
config) of Graphics Configuration.
Methods of Canvas
Method Description
Paint(Graphics g) Paint the Canvas.
Update(Graphics g) Update the Canvas.
Example:
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
public static void main(String args[])
{
DemoCanvas dc = new DemoCanvas();
}
}
class Canvascls extends Canvas
{
public void paint(Graphics g)
{
g.setColor(Color.blue);
g.fillOval(75, 10, 150, 75);
}
}
Working With Graphics: AWT Controls
AWT provides many ready- made and reusable GUI components.
All the AWT controls inherit from java.awt.* where * represents all class like label, button etc..
The frequently used are: Button, TextField, Label, Checkbox, CheckboxGroup (radio buttons), List, and
Choice, as given below table.
Component Description
Label o It is used to display information that should not be modified by users.
o It is useful for obtaining information from users. It considers only single
TextField
line input.
TextArea o It is a text component that allows for the editing of a multiple lines of text.
Button o It creates a labeled button.
o It is a graphical component that can be in either an on (true) or off (false)
CheckBox
state.
CheckboxGroup o It is used to group the set of checkbox.
List o It presents the user with a scrolling list of text items.
o It is used to show drop-down menu of choices. Selected choice is shown
Choice
on the top of the menu.
o A Scrollbar control represents a scroll bar component in order to enable
ScrollBar
user to select from range of values.
o It represents a rectangular area where application can draw something or
Canvas
can receive inputs created by user.
Labels
It is used to display information that should not be modified by users.
Constructor of Label
Constructor Description
Label() Create an empty label.
Create a new label with the specified string of text, which is left
Label(String)
justified.
Create a label with specified text and alignment indicated by the int
Label(String, int)
Argument: Label.Right, Label.Left, Label.Center
Method of Label
Method Description
int getAlignment() Gets the current alignment of the label.
String getText() Gets the text of the label.
Set the alignment for the label to specified alignment. Possible
void setAlignment(int align)
values are Label.LEFT, Label.RIGHT and Label.CENTER.
void setText(String label) Sets the text for the label to the specified text.
Syntax:
Label L1 = new Label(“UserName”);
add(L1);
TextField
It is useful for obtaining information from users. It considers only single line input.
Constructor of TextField
Constructor Description
TextField() Create a default text field.
Create a new empty text field with the specified number of
TextField(int numChar)
character.
TextField(String text) Create a new text field initialized with the specified text.
Create a new text field initialized with the specified text to be
TextField(String text, int
displayed, and wide enough to hold the specified number of
numChar)
columns.
Method of TextField
Method Description
getText() Return the text this text field contains (as a string).
setText() Puts the given text string into the field.
getColumns() Returns the width of this text field.
Select the text between the two integer positions (position start
select(int, int)
from 0).
getSelectedText( ) Get the currently selected text.
isEditable() Return true or false based on whether the text is editable.
setEditable(boolean) True (the default) enables text to be edited, False not editable.
Syntax:
TextField t1 = new TextField (12);
add(t1);
TextArea
It is a text component that allows for the editing of a multiple lines of text.
We can set number of rows and columns of the TextArea.
The text in a TextArea appears left justified, and the justification is not customizable.
Constructors of TextArea
Constructor Description
TextArea() Creates an empty text area.
Creates an empty text area with the given number of rows and
TextArea(int, int)
columns.
TextArea(String) Creates a text area displaying the given string.
Creates a text area displaying the given string and with the given
TextArea(String, int, int)
number of rows and columns.
Creates a new text area with the specified text, and with the rows,
TextArea(String, int , int , columns, and scroll bar visibility as specified. SCROLLBARS_BOTH,
int ) SCROLLBARS_HORIZONTAL_ONLY, SCROLLBARS_NONE and
SCROLLBARS_VERTICAL_ONLY.
Method of TextArea
Method Description
getColumns() Returns the number of columns of the text area.
setColumns(int columns) Sets the number of columns for the text area.
getRows() Returns the number of rows in the text area.
setRows(int rows) Sets the number of rows for the text area.
insert(String text, int pos) Inserts the specified text at the specified position in the text area.
append(String str) Appends the given text at the end of the text area's current text.
replaceRange (String text, Replaces text between the indicated start and end positions with the
int start, int end) specified replacement text.
Syntax :
TextArea T2 = new TextArea (10,20);
add(T2);
Button (Push Button)
The Button component is rectangular button that has label and generate event when pressed.
Constructors of Button
Constructor Description
Button() Creates a button with an empty string for its label.
Button(String text) Creates a button with the given string as a label.
Method of Button
Method Description
getLabel() Get the label of the Button.
setLabel(string text) Set the label of the Button with given text.
setEnable(boolean) Enable or disable this Button. Disabled Button cannot be clicked.
Syntax :
Button b = new Button (“Hello”);
add (b);
CheckBox
The Checkbox class is used to display checkbox controls.
The Checkbox has a label to indicate its meaning. Checkbox component is toggle box that can be either
selected or deselected indicating presence or absence of choice.
If a Checkbox object is not in a CheckboxGroup object, it is implemented as a simple checkbox.
If a Checkbox object is with a CheckboxGroup object, it is implemented as a radio button.
Constructors of Checkbox
Constructor Description
Checkbox() Creates a check box with an empty string for its label.
Checkbox(String text) Creates a checkbox with the given string as a label.
Checkbox(String text, boolean Creates a check box with the given string as a label and sets the
state) specified state (Selected/Deselected by True/False).
Checkbox(String text, Creates a check box with the given string as a label, in the
CheckboxGroup group, boolean specified check box group, and set to the specified state. The null
state) is used for a group argument. Only radio button have groups.
Method of Checkbox
Method Description
getLabel() Returns the label of the check box.
setLabel(String text) Sets the check box's label to by given text.
Returns true or false, based on whether the check box is
getState()
selected or not.
Sets the state of the check box to the specified state
setState(boolean)
(True/False).
setCheckboxGroup(CheckboxGroup
Sets the check box's group to the specified check box group.
grp)
getCheckboxGroup() Return the check box's group.
Syntax :
Checkbox C = new Checkbox (“Java”);
add (C);
CheckboxGroup
To create a group of checkboxes, you use the CheckboxGroup class.
The CheckboxGroup class is used with the Checkbox class to implement radio buttons.
All Checkbox that are associated with a CheckboxGroup are treated as a single radio button.
It allows only one button in group to be set at a time.
Constructors of CheckboxGroup
Constructor Description
CheckboxGroup() Creates a new instance of CheckboxGroup.
Method of CheckboxGroup
Method Description
getSelectedCheckbox() Returns the current choice from the check box group.
setSelectedCheckbox(Checkbox The method of CheckboxGroup is used to make one of the box
box) selected among all the check boxes.
Choice
It is used to show drop-down list of choices. Selected choice is shown on the top of the menu
Form this lists a single choice can be selected, similar to a group of checkboxes.
Constructors of Choice
Constructor Description
Choice() Creates a new choice List.
Method of ChoiceList
Method Description
add(String text) Add an item to the choice list.
getItem(int index) Returns the string at the specified index from the Choice list.
getItemCount() Returns the number of items in the choice list.
getSelectedIndex() Return the index of the currently selected item.
getSelectedItem() Returns the currently selected item as a string.
insert(String item, int
Inserts the item into the choice list at the specified position.
index)
remove(int position) Removes an item from the choice list at the specified position.
remove(String item) Removes the first occurrence of item from the Choice list.
removeAll() Removes all items from the choice list.
select(int) Selects the item at the given position.
select(String) Selects the item with the given string.
Lists
The List component is a Scrolling list of string from which one or more string can be selected.
The List class is use for creating single and multiple selection list.
The List class provides facility to set display size (number of elements) and also allow selecting multiple
items from the list.
Constructors of List
Constructor Description
List() Creates an empty scrolling list.
Creates a new scrolling list initialized with the specified number of visible
List(int rows)
lines.
Creates a scrolling list with the given number of visible lines on the
List(int rows, boolean
screen. The Boolean indicates whether this list enables multiple selection
multipleMode)
(true) or not (false).
Method of List
Method Description
add() Used to build the scrolling list.
add(String item) Adds the specified item to the end of scrolling list.
Adds the specified item to the scrolling list at the position indicated
add(String item, int index)
by the index.
getItem(int index) Returns the item at given index.
getItemCount() Returns the number of items in the list.
String[] getItems() Gets the items in the list.
Gets the index of the selected item on the list (used for lists that
getSelectedIndex()
allow only single selections).
Returns a integer array of selected indexes positions (used for lists
int[] getSelectedIndexes()
that allow multiple selections).
getSelectedItem() Returns the currently selected item on the list.
Returns a string array of selected items on the list. (used for lists
String[] getSelectedItems()
that allow multiple selections).
deselect(int index) Deselects the item at the specified index.
remove(int position) Removes an item from the list at the specified position.
remove(String item) Removes the first occurrence of item from the list.
removeAll() Removes all items from the list.
select(int index) Select the item at the given index.
replaceItem(String newValue, Replaces the item at the specified index in the list with the new
int index) string.
Determines if the specified item in this scrolling list is selected or
isIndexSelected(int index)
not.
isMultipleMode() Determines whether this list allows multiple selections or not.
Sets the flag that determines whether this list allows multiple
setMultipleMode(boolean b)
selections.
Syntax:
List L1 = new List(2,true);
L1.add(“Java”);
L1.add(“DWSL”);
add(L1);
The MenuBar class provides menu bar bound to a frame and is platform specific.
MenuBar contains one or more Menu objects.
Menu are used to display and control menu items.
Each Menu object contains a list of MenuItem objects.
An ActionListener can be added to a MenuItem object.
First create a menu bar by creating an instance of menuBar.
Constructor of Menu and Menubar
Constructor Description
MenuBar() Creates a new menu bar.
Menu() To create a default menu.
Menu(String str) str specifies the name of the Menu selection
Menu(String str, Boolean str specifies the name of the Menu selection flag represents the popup
flag) menu if set true.
MenuItem() To create a default MenuItem.
MenuItem(String str) Str is the name shown in the Menu.
MenuItem(String str,
Key is the short cut key for that Menu Item.
MenuShortcut key)
CheckboxMenuItem
CheckboxMenuItem is checkable menu item, which provides selection (on or off) listed in menus.
CheckboxMenuItem can be controlled by the ItemListener interface.
Constructor of CheckboxMenuItem
Constructor Description
CheckboxMenuItem() To create a default CheckBoxMenuItem.
CheckboxMenuItem(Stri
Str is the name shown in the menu.
ng str)
CheckboxMenuItem(Stri
Flag can be set on for the Item to be checkable.
ng str, boolean flag)
Method of Menu
Method Description
setEnabled(boolean flag) To enable or disable menu item
isEnabled() To retrieve the status of the menu item.
setLabel(String str) To change the name of the menu item.
String getLabel() To retrieve the current name of the menu item.
boolean getState() Return true if the item is checked otherwise false.
setState(Boolean flag) To check an item, pass true and to clear an item, pass false.
add (MenuItem m) Used to add menu item in Menu.
add(Menu menu) Add the specified menu to the menu bar.
getItem(int index) Return the menu item at the given index
getItemCount() Return the number of item inside the menu.
remove(MenuComponent item) Remove menu item from menu.
Remove the menu located at the specified index and remove all
remove(int index), removeAll()
menu from the menu bar.
Example:
import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
m = new Menu("File");
m.add(new MenuItem("New"));
m.add(new MenuItem("Open"));
m.add(new MenuItem("Save"));
m.add(new MenuItem("Save As"));
m.add(new MenuItem("Print"));
m.addSeparator();
m.add(new MenuItem("Quit"));
mbar.add(m);
m = new Menu("Help");
m.add(new MenuItem("Help"));
m.addSeparator();
m.add(new MenuItem("About"));
mbar.add(m);
setMenuBar(mbar);
addWindowListener(new WindowAdapter(){
public void windowClosing(WindowEvent we){
System.exit(0);
}
});
}
public static void main(String args[])
{
MenuDemo MD= new MenuDemo();
}
}
Layout Managers **
The Layout Mangers are used to arrange components in particular manner.
Layout Manager is an interface that is implemented by all the classes of layout managers.
The layout manager set by the SetLayout() method. If we don’t use this method then default layout
manager is used.
There are following classes that represents the layout managers:
1) java.awt.BorderLayout
2) java.awt.FlowLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
Layout Manager Classes
Some possible Layout Managers are listed in the table below:
Layout Manager Description Constants
Arranges components to the top, NORTH, SOUTH, EAST, WEST,
BorderLayout bottom, left, right, and center of a CENTER –positions in the
container. container.
It is used to arrange the components LEFT, CENTER, RIGHT – these tell it
FlowLayout in a line, one after another (in a flow) how to align the components in
from left to right. each row.
Divide the container into equal-sized GridLayout(int rows, int columns)
GridLayout rectangles and arrange each To specify the number of rows
component into one of these cells. and columns in the grid.
It manages the components in such a CardLayout(int hgap, int vgap):
CardLayout way that only one component is visible creates a card layout with the
at a time. given horizontal and vertical gap.
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow).
It is the default layout of applet or panel.
FlowLayout arranges swing component from left to right until there’s no more space available.
Then it begins a new row below it and moves from left to right again.
LEFT, CENTER, RIGHT – these tell it how to align the components in each row.
It can be used like FlowLayout.LEFT.
Constructor of FlowLayout
Constructor Description
Create a flow layout with centered alignment and a default 5 unit
FlowLayout()
horizontal and vertical gap.
Create a flow layout with the given alignment and a default 5 unit
FlowLayout(int align)
horizontal and vertical gap.
FlowLayout(int align, int Create a flow layout with the given alignment and given horizontal and
hgap, int vgap) vertical gap.
Border layout
The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only.
It is the default layout of frame or window.
The BorderLayout provides five constants for each region: NORTH, SOUTH, EAST, WEST, CENTER.
These constants are used like BorderLayout.NORTH.
While adding the component these constants are used by using following form of add() method.
add (Component compObj, Object region);
Constructors of BorderLayout
Constructor Description
BorderLayout() Creates a border layout with no gaps between the components.
BorderLayout(int hgap, int Creates a border layout with the given horizontal and vertical gaps
vgap) between the components.
Grid Layout
The GridLayout is used to arrange the components in rectangular grid inside the container.
One component is displayed in each rectangle.
Components added to the container with the GridLayout manager are arranged in order from left to
right.
Constructors of GridLayout
Constructor Description
Creates a grid layout with one column per component in a
GridLayout ()
row.
Creates a grid layout with the given rows and columns but
GridLayout (int rows, int columns)
no gaps between the components.
GridLayout (int rows, int columns, int Creates a grid layout with the given rows and columns along
hgap, int vgap) with given horizontal and vertical gaps.
CardLayout
The CardLayout manager treats each component as a card. Only one card/component visible at a
time. So it is known as CardLayout.
Constructors of CardLayout
Constructor Description
CardLayout() Creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap) Creates a card layout with the given horizontal and vertical gap.
Methods Description
void first(Container a) It is used to flip to the first card of the given container.
void last(Container a) It is used to flip to the last card of the given container.
void next(Container a) It is used to flip to the next card of the given container.
void previous(Container a) It is used to flip to the previous card of the given container.
void show(Container a, String
It is used to flip to the specified card with the given name.
cardName)
o ‘a’ is a reference to the container (usually a panel) that holds the cards, and cardName is the name
of a card.
JApplet
The JApplet class extends the Applet class.
We can use JApplet that can have all the controls of swing.
JLabel
Constructor of JLabel
Constructor Description
JLabel() Creates label with no image and with an empty string for the title.
JLabel(Icon image) Creates a label with the specified image.
JLabel(String text) Creates a label with the specified text.
JLabel(Icon image, int
Creates a label with the specified image and horizontal alignment.
horizontalAlignment)
Methods of JLabel
Constructor Description
getText() Returns the string that associate with the label.
setText(String text) Set the specified text to label.
getIcon() Returns the image that displays the label.
setIcon(Icon image) Set the image to the label.
getHorizontalAlignment() Returns the alignment of the label along the X axis.
setHorizontalAlignment(int
Sets the alignment of the label along the X axis
alignment)
getVerticalAlignment() Returns the alignment of the label along the Y axis.
setVerticalAlignment(int
Sets the alignment of the label along the Y axis.
alignment)
JTextField
The class JTextField is a component which allow the editing of a single line of text.
Constructor of JLabel
Constructor Description
JTextField() Creates a default text field.
Creates a new empty text field with the specified number of
JTextField(int columns)
character.
JTextField(String text) Creates a new text field initialized with the specified text.
Creates a new text field initialized with the specified text to be
JTextField(String text, int
displayed, and wide enough to hold the specified number of
columns)
columns.
Methods of JTextField
Method Description
getText() Return the text this text field contains (as a string).
setText() Puts the given text string into the field.
getColumns() Returns the width of this text field.
getSelectedText( ) Get the currently selected text.
JButton
A JButton can be used in a GUI just like a java.awt.Button. It behaves like an AWT Button, notifying
ActionListener list elements when pushed.
Constructors of JButton
Constructor Description
JButton() Creates a button with an empty string for its label.
JButton(String text) Creates a button with the given string as a label.
JButton(Icon image) Creates a button with an specified image.
JButton(String text, Icon
Creates a button with specified text and an image.
icon)
Methods of JButton
Method Description
getLabel() Get the label of the Button.
setLabel(string text) Set the label of the Button with given text.
setEnable(boolean) Enable or disable this Button. Disabled Button cannot be clicked.
JCheckBox
A JCheckBox is similar to an AWT Checkbox that is not in a CheckboxGroup.
Purpose of the check box - an item that can be selected or deselected, and which displays its state to
the user.
Constructors of the checkbox
Constructor Description
JCheckbox() Creates a check box with no image and text
JCheckbox(String text) Creates a checkbox with the given string as a label.
JCheckBox(Icon image) Creates a check box with an image.
JCheckbox(String text, boolean Creates a check box with the given string as a label and sets the
state) specified state (Selected/Deselected by True/False).
JCheckBox(String text, Icon
Creates a checkbox with specified text and image
image)
Checkbox(String text, Icon Creates a check box with the given string as a label, image, and
image, boolean state) set to the specified state.
Methods of JCheckBox
Method Description
getTextl() Returns the label of the check box.
setText(String text) Sets the check box's label by given text.
isSelected() Check whether checkbox is selected or not.
JRadioButton
The JRadioButton class is used to create a radio button.
It is used to choose one option from multiple options.
It should be added in Group to select one radio button only by using ButtonGroup class.
By default radio button is not selected.
Constructors of JRadioButton
Constructor Description
JRadioButton() Creates radio button with no text.
JRadioButton(Icon image) Creates radio button with the specified image but no text
JRadioButton(String text) Creates radio button with the specified text.
JRadioButton(String text, Icon
Creates radio button with the specified image and text.
image)
JRadioButton(Icon image, Creates a radio button with the specified image and selection
boolean selected) state, but no text.
JRadioButton(String text,
Creates a radio button with the specified text and selection state.
boolean selected)
JRadioButton(String text, Icon Creates a radio button with the specified text, image, and
image, boolean selected) selection state.
Methods of JRadioButton is same as JCheckBox.
JComboBox
The JComboBox class is used to create drop-down list. At a time only one item can be selected from
the item list.
The JComboBox offers an editable option.
Constructors of JcomboBox
Constructor Description
JComboBox() Creates a JComboBox with a default data model.
JComboBox(Object[] items) Creates a JComboBox that takes its items from an existing array.
Creates a JComboBox that contains the elements in the
JComboBox(Vector<?> items)
specified Vector.
Methods of JcomboBox
Method Description
addItem(Object object) It is used to add an item to the item list.
setEditable(boolean b) It is used to determine whether the JComboBox is editable.
removeItem(Object object) It is used to delete an item from the item list.
removeAllItems() It is used to remove all the items from the list.
getItemAt(int index) Returns the list item at the specified index.
getItemCount() Returns the number of items in the list.
getSelectedIndex() Returns the index of the selected item.
setSelectedIndex(int index) Selects the item at given index.
getSelectedItem() Returns the selected item.
setSelectedItem(Object object) Set the selected item specified as object.
isEditable() Returns true if the JComboBox is editable.
addActionListener(ActionListener
It is used to add the ActionListener.
a)
addItemListener(ItemListener i) It is used to add the ItemListener.
Menus
Every top-level window has a menu bar associated with it.
This menu bar consists of various menu choices available to the end user.
Further each choice contains list of options which is called drop down menus.
Menu and MenuItem controls are subclass of MenuComponent class.
Menu hierarchy is as given below:
JMenuBar
Constructor of JMenuBar
Constructor Description
JMenuBar() Creates a new menu bar.
Methods of JMenuBar
Method Description
JMenu add(JMenu c) Appends the specified menu to the end of the menu bar.
getComponentIndex(Component c) Returns the index of the specified component.
Returns the margin between the menubar's border and its
Insets getMargin()
menus.
void setMargin(Insets m) Sets the margin between the menubar's border and its menus.
JMenu getMenu(int index) Returns the menu at the specified position in the menu bar.
int getMenuCount() Returns the number of items in the menu bar.
Returns true if the menu bar currently has a component
boolean isSelected()
selected.
JMenuItem
The JMenuItem class represents the actual item in a menu.
All items in a menu should derive from class JMenuItem, or one of its subclasses.
Constructor of JMenuItem
Constructor Description
JMenuItem() Creates a JMenuItem with no set text or image.
JMenuItem(Icon image) Creates a JMenuItem with the specified image.
JMenuItem(String text) Creates a JMenuItem with the specified text.
JMenuItem(String text, Icon
Creates a JMenuItem with the specified text and icon.
image)
JMenuItem(String text, int Creates a JMenuItem with the specified text and keyboard
mnemonic) mnemonic.
Methods of JMenuItem
Method Description
addMenuKeyListener
Adds a MenuKeyListener to the menu item.
(MenuKeyListener l)
getComponent() Returns Component.
init(String text, Icon icon) Initializes the menu item with the specified text and icon.
setEnabled(boolean b) Enables or disables the menu item.
JMenu
The JMenu class represents pull-down menu component which is deployed from a menu bar.
Constructor of JMenu
Constructor Description
JMenu() Creates a JMenu with no text.
JMenu(String text) Creates a JMenu with the specified text.
Creates a JMenu with the specified text and specified as a tear-off
JMenu(String s, boolean b)
menu or not.
Methods of JMenu
Method Description
Component add(Component c) Appends a component to the end of this menu.
Component add(Component c, Adds the specified component to this container at the given
int index) position.
JMenuItem add(JMenuItem
Appends a menu item to the end of this menu.
menuItem)
Creates a menu item with the specified text and appends it to the
JMenuItem add(String text)
end of this menu
void addSeparator() Appends a new separator to the end of the menu.
JMenuItem getItem(int pos) Returns the JMenuItem at the specified position.
int getItemCount() Returns the number of items on the menu, including separators.
Component
Returns the component at position n.
getMenuComponent(int n)
int getMenuComponentCount() Returns the number of components on the menu.
JMenuItem insert(JMenuItem
Inserts the specified JMenuitem at a given position.
item, int pos)
Inserts a new menu item with the specified text at a given
void insert(String text, int pos)
position.
void insertSeparator(int index) Inserts a separator at the specified position.
boolean isSelected() Returns true if the menu is currently selected.
void remove(Component c) Removes the component c from this menu.
void remove(int pos) Removes the menu at the specified index from this menu
void remove(JMenuItem item) Removes the specified menu item from this menu.
void removeAll() Removes all menu items from this menu.
Event
When the user interacts with a GUI application, an event is generated.
Example : Pressing a button, Entering a character in Textbox., selecting an item or closing a window
The super class of all event classes is java.util.EventObject.
Event handling has three main components:
o Events : An event is a change of state of an object.
o Events Source : Event source is an object that generates an event.
o Listeners : A listener is an object that listens the event. A listener gets notified when an event
occurs.
A source generates an Event and sends it to one or more listeners registered with the source.
Once event is received by the listener, they process the event and then return.
Events are supported by a number of Java packages, like java.util, java.awt and java.awt.event.
The list of Event classes are as follow:
Event Class Description Listener Interface
ActionEvent Generated when button is ActionListener
pressed, menu-item is
selected, list-item is double
clicked.
MouseEvent Generated when mouse is MouseListener and
dragged, moved, clicked, MouseMotionListener
pressed or released also when
the enters or exit a
component.
WindowEvent Generated when window is WindowListener
activated, deactivated, opened
or closed.
ItemEvent Generated when check-box or ItemListener
list item is clicked.
KeyEvent Generated when input is KeyListener
received from keyboard.
MouseWheelEvent Generated when mouse wheel MouseWheelListener
is moved.
ComponentEvent Generated when component is ComponentEventListener
hidden, moved, resized or set
visible.
ContainerEvent Generated when component is ContainerListener
added or removed from
container.
ActionEvent class
This class is defined in java.awt.event package.
Constructor of ActionEvent
Constructor Description
ActionEvent (Object source, int
Constructs an ActionEvent object
id, String command)
ActionEvent (Object source, int
id, String command,
Constructs an ActionEvent object with modifier keys.
int modifiers)
Method of ActionEvent
Method Description
String getActionCommand() Returns the command string associated with this action.
int getModifiers() To return a value that indicates which modifier keys were pressed.
MouseEvent class *
Method of MouseEvent
Method Description
int getX()
To obtain X and Y co-ordinates of the mouse when an event
int getY()
occurred.
int getClickCount() To obtain the number of mouse click for this event.
Point getPoint() The location where the event happened.
WindowEvent class
Method of WindowEvent
Method Action
Window getWindow() To return the window object that generated the event.
ActionListener
The class which processes the ActionEvent should implement this interface.
The object of that class must be registered with a component.
The object can be registered using the addActionListener() method.
Method of ActionListener
Method Description
void actionPerformed
Invoked when an action occurs.
(ActionEvent e)
MouseListener *
The class which processes the MouseEvent should implement this interface.
The object of that class must be registered with a component.
The object can be registered using the addMouseListener() method.
Method of MouseListener
Method Description
void mouseClicked Invoked when the mouse button has been clicked (pressed and
(MouseEvent e) released) on a component.
void mouseEntered Invoked when the mouse enters a component’s coordinates
(MouseEvent e) space.
void mouseExited (MouseEvent
Invoked when the mouse exits a component’s coordinates space.
e)
void mousePressed
Invoked when a mouse button has been pressed on a component.
(MouseEvent e)
void mouseReleased
Invoked when a mouse button has been released on a component.
(MouseEvent e)
WindowListener
The class which processes the WindowEvent should implement this interface.
The object of that class must be registered with a component.
The object can be registered using the addWindowListener() method.
Method of MouseListener
Method Description
void windowActivated
Invoked when the Window is activated.
(WindowEvent e)
void windowClosed
Invoked when a window has been closed.
(WindowEvent e)
void windowClosing Invoked when the user attempts to close the window from the
(WindowEvent e) window's system menu.
void windowDeactivated
Invoked when a Window is no longer the active Window.
(WindowEvent e)
void windowOpened
Invoked the first time a window is opened.
(WindowEvent e)
void windowIconified
Invoked when a window is minimized.
(WindowEvent e)
void windowDeiconified Invoked when a window is changed from a minimized to a normal
(WindowEvent e) state.
KeyListener
The class which processes the KeyEvent should implement this interface.
The object of that class must be registered with a component.
The object can be registered using the addKeyListener() method.
Method of KeyListener
Method Description
void keyPressed(KeyEvent e) Invoked when a key has been pressed.
void keyReleased(KeyEvent e) Invoked when a key has been released.
void keyTyped(KeyEvent e) Invoked when a key has been typed (pressed or released).