Java Unit 4 Notes_23_24
Java Unit 4 Notes_23_24
Event Handling
.
Introduction:
The java.awt.event package provides many event classes and Listener interfaces for event
handling
• Event
• Source
• Listener
Events:
Changing the state of an object is known as an Event. For example, click on button, dragging
mouse etc.
Events to be generated are pressing a button, entering a character via the keyboard, selecting
an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value,a
software or h ardware failure occurs, or an operation is completed.
Event Sources:
A source is an object that generates an event.Sources may generate more than one type of
event. A source must register listeners in order for the listeners to receive notifications about
a specific type of event.
Here, Type is the name of the event, and el is a reference to the event listener.
For example, the method that registers a keyboard event listener is called addKeyListener( ).
When an event occurs, all registered listeners are notified and receive a copy of the event
object. This is known as multicasting the event. In all cases, notifications are sent only to
listeners that register to receive them.
A source must also provide a method that allows a listener to unregister an interest in a
specific type of event.
Here, Type is the name of the event, and el is a reference to the event listener.
Event Listerners:
A listener is an object that is notified when an event occurs.
First, it must have been registered with one or more sources to receive notifications
about specific types of events.
Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event.
In the above examples, the method actionPerformed() is known as a call back method. In
other words, you never invoke actionPerformed() in your codes explicitly. The
actionPerformed() is called back by the graphics subsystem under certain circumstances in
response to certain user actions.
200
Three kinds of objects are involved in the event-handling: a source, listener(s) and an event
object.
The source object (such as Button and Textfield) interacts with the user. Upon triggered, the
source object creates an event object to capture the action (e.g., mouse-click x and y, texts
entered, etc). This event object will be messaged to all the registered listener object(s), and an
appropriate event-handler method of the listener(s) is called-back to provide the response. In
other words, triggering a source fires an event to all its listener(s), and invoke an appropriate
event handler of the listener(s).
To express interest for a certain source's event, the listener(s) must be registered with the
source. In other words, the listener(s) "subscribes" to a source's event, and the source
"publishes" the event to all its subscribers upon activation. This is known as subscribe-
publish or observable-observer design pattern.
1. The source object registers its listener(s) for a certain type of event.(A source fires an
event when
triggered. For example, clicking a Button fires an ActionEvent, clicking a mouse
button fires MouseEvent, typing a key fires KeyEvent, and etc.).
2. The source is triggered by a user.
3. The source create a XxxEvent object, which encapsulates the necessary information
about the activation. For example, the (x, y) position of the mouse pointer, the text
entered, etc.
4. Finally, for each of the XxxEvent listeners in the listener list, the source invokes the
appropriate handler on the listener(s), which provides the programmed response
Event Classes
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown here:
EventObject(Object src);
MouseWheelEvent MouseWheelListener
Keyboard KeyEvent KeyListener
CheckBox,Choice,List ItemEvent ItemListener
TextField,TextArea TextEvent TextListener
AdjustmentEvent AdjustmentListener
Window WindowEvent WindowListener
Component ComponentEvent ComponentListener
202
Mouse Event:
A MouseEvent is fired when you press, release, or click (press followed by release) a
mouse-button (left or right button) at the source object; or position the mouse-pointer
at (enter) and away (exit) from the source object.
A MouseEvent listener must implement either MouseListener interface or
MouseMotionListener interface or both dependending a action.
The Java MouseListener is notified whenever you change the state of mouse
The Java MouseMotionListener is notified whenever you move or drag mouse
The Java MouseListener is notified whenever you change the state of mouse. It is
notified against MouseEvent.
The MouseListener interface is found in java.awt.event package.
203
Methods Description
public abstract void Called-back when the mouse-button has
mouseClicked(MouseEvent e); been clicked on the
source.
public abstract void Called-back when the mouse-pointer has
mouseEntered(MouseEvent e); entered the source
public abstract void mouseExited(MouseEvent Called-back when the mouse-pointer has
e); exited the source
public abstract void mousePressed(MouseEvent Called-back when a mouse-button has been
e); pressed on the source
The Java MouseMotionListener is notified whenever you move or drag mouse. It is notified
against MouseEvent. The MouseMotionListener interface is found in java.awt.event package.
It has two methods.
import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
l.setText("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
l.setText("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
l.setText("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
l.setText("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
l.setText("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}
Output:
205
import java.awt.*;
import java.awt.event.*;
public class MouseMotionListenerExample extends Frame implements
MouseMotionListener
{
MouseMotionListenerExample(){
addMouseMotionListener(this);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseDragged(MouseEvent e) {
Graphics g=getGraphics();
g.setColor(Color.Black);
g.fillOval(e.getX(),e.getY(),20,20);
}
public void mouseMoved(MouseEvent e) {}
Output:
206
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
l.setBounds (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
area.setBounds (20, 80, 300, 300);
// adding the KeyListener to the text area
area.addKeyListener(this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
setSize (400, 400);
setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the
label when key is pressed
public void keyPressed (KeyEvent e) {
l.setText ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the
label when key is released
public void keyReleased (KeyEvent e) {
l.setText ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the
label when a key is typed
207
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 with their corresponding listener interfaces are given below
MouseMotionAdapter MouseMotionListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
import java.awt.*;
import java.awt.event.*;
public class KeyAdapterExample extends KeyAdapter{
Label l; TextArea area; Frame f;
KeyAdapterExample(){
f=new Frame("Key Adapter");
l=new Label();
l.setBounds(20,50,200,20);
area=new TextArea();
area.setBounds(20,80,300, 300);
f.add(l);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
area.addKeyListener(this);
}
public void keyReleased(KeyEvent e) {
String text=area.getText();
String words[]=text.split("\\s");
l.setText("Words: "+words.length+" Characters:"+text.length());
}
public static void main(String[] args) {
new KeyAdapterExample();
}
}
Output:
209
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterExample extends MouseAdapter{
Label l;
Frame f;
MouseAdapterExample(){
f=new Frame("MOUSE Adapter");
l=new Label();
l.setBounds(20,50,200,20);
f.add(l);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
l.addMouseListener(this);
}
public void mousePressed(MouseEvent e)
{
l.setText("mouse Pressed");
}
Output:
210
AWT Introduction
Computer users today expect to interact with their computers using a graphical user
interface (GUI). Java can be used to write GUI programs ranging from simple applets which
run on a Web page to sophisticated stand-alone applications.
•Applets.
•Stand-Alone Applications
A stand-alone application is a program that runs on its own, without depending on a Web
browser. You’ve been writing stand-alone applications all along. Any class that has a main()
routine defines a stand-alone application; running the program just means executing this
main() routine.
The user uses a mouse and keyboard to interact with GUI components such as windows,
menus, buttons, check boxes, text input boxes, scroll bars, and so on..
Because the AWT components use native code they are referred to as heavy weight.
AWT Components
A Component is an abstract super class for GUI controls and it represents an object with
graphical representation
List of Components:
Component Description
Label The easiest control to use is a label. A label is an object of type Label,
and it contains a string, which it displays. Labels are passive controls
that do not support any interaction with the user. Label defines the
following constructors
Check Box A check box is a graphical component that can be in either an on (true)
or off (false) state.
Check Box The CheckboxGroup class is used to group the set of checkbox.
Group
List The List component presents the user with a scrolling list of text items.
Text Field A TextField object is a text component that allows for the editing of a
single line of text.
Text Area A TextArea object is a text component that allows for the editing of a
multiple lines of text.
graphical images.
Scroll Bar A Scrollbar control represents a scroll bar component in order to enable
user to select from range of values.
Dialog A Dialog control represents a top-level window with a title and a border
used to take some form of input from the user.
File Dialog A FileDialog control represents a dialog window from which the user
can select a file.
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(intwidth,int height) sets the size (width and height) of the
component.
public void setLayout(LayoutManager m) defines the layout manager for the
component.
Component:Labels
The easiest control to use is a label. A label is an object of type Label, and it contains a
string,which it displays. Labels are passive controls that do not support any interaction with
theuser.
Constructor of Label
Constructors Description
Label( ) throws HeadlessException creates a blank label.
Label(String str) throws HeadlessException creates a label that contains thestring
specified by str. This string is left-justified
Label(String str, int how) throws creates a label that contains the string
specified by str using the alignment specified
HeadlessException
by how(Label.LEFT,
Label.RIGHT, orLabel.CENTER)
Methods of Label:
Method Description
void setText(String str) For setText( ), str specifies the new label
String getText( ) For getText( ), the current label is returned.
214
Example on Label:
import java.awt.*;
Component:Buttons
A push button is a component thatcontains a label and that generates an event when it is
pressed. Push buttons are objects oftype Button
Constructor of Button
Constructors Description
Button( ) throws HeadlessException The first version creates an empty button.
Button(String str) throws HeadlessException The second creates a button that contains str
as a label
Methods of Button:
Method Description
void setLabel(String str) After a button has been created, you can set
its label,Here, str becomes the new label for
the button
String getLabel( ) You can retrieve its label
import java.awt.*;
public class ButtonExample {
public static void main (String[] args) {
Component: Canvas
The Canvas class controls and represents a blank rectangular area where the application can
draw or trap input events from the user. It inherits the Component class.
Class methods
Example on Canvas:
// importing awt class
import java.awt.*;
// creating a frame
Frame f = new Frame("Canvas Example");
// adding canvas to frame
f.add(new MyCanvas());
f.setVisible(true);
}
// main method
public static void main(String args[])
{
new CanvasExample();
}
}
// adding specifications
g.setColor(Color.red);
g.fillOval(75, 75, 150, 75);
}
}
219
Component: Scrollbars
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.
It can be added to top-level container like Frame or a component like Panel. The Scrollbar
class extends the Component class.
3 Scrollbar(int orientation, int Constructs a new scroll bar with the specified
value, int visible, int minimum, int orientation, initial value, visible amount, and
maximum) minimum and maximum values.
Value: specify the starting position of the knob of Scrollbar on its track.
13. protected void processEvent(AWTEvent e) It processes the events on the scroll bar.
16. void setMaximum (int newMaximum) It sets the maximum value of the scroll
bar.
17. void setMinimum (int newMinimum) It sets the minimum value of the scroll
bar.
18. void setOrientation (int orientation) It sets the orientation for the scroll bar.
19. void setUnitIncrement(int v) It sets the unit increment for the scroll
bar.
20. void setValue (int newValue) It sets the value of scroll bar with the
given argument value.
22. void setValues (int value, int visible, int It sets the values of four properties for
minimum, int maximum) scroll bar: value, visible amount,
minimum and maximum.
23. void setVisibleAmount (int newAmount) It sets the visible amount of the scroll
bar.
Example on ScrollBar:
// class constructor
ScrollbarExample1() {
// creating a frame
Frame f = new Frame("Scrollbar Example");
// creating a scroll bar
Scrollbar s = new Scrollbar();
// main method
public static void main(String args[]) {
new ScrollbarExample1();
}
}
224
In the following example, we are creating a Scrollbar and adding it into the Frame. Here, we
are using addAdjustmentListener() method of Scrollbar class which receives the instances of
AdjustmentEvent and eventually we display it in the form of Label.
// class constructor
ScrollbarExample2() {
// creating a Frame with a title
Frame f = new Frame("Scrollbar Example");
// main method
225
TextComponents
1. Text Field
2. Text Area
TextField
The TextField class implements a single-line text-entry area, usually called an edit
control.Text fields allow the user to enter strings and to edit the text using the arrow keys, cut
and paste keys, and mouse selections. TextField is a subclass of TextComponent
Constructor of TextField
Constructors Description
TextField(String str, int numChars) creates a text field that the string contained in
226
with
Methods of TextField
Method Description
void setText(String str) To set the text Here, str is the new string.
void select(int startIndex, int endIndex) The user can select a portion of the text in a
text field. Also, you can select a portion of
text under program control. The select(
)method selects the charactersbeginning at
startIndex and ending at endIndex–1.
Example programming:
f.add(t2);
// setting size, layout and visibility of frame
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Output:
TextArea
Sometimes a single line of text input is not enough for a given task. To handle these
situations,the AWT includes a simple multiline editor called TextArea
Constructor of TextArea
Constructors Description
TextArea(int numLines, int numChars) Here, numLines specifies the height, in lines, of the
text area, and numChars specifies its width,in
228
TextArea(String str, int numLines, int Initial text can be specified by strHere, numLines
numChars) throws HeadlessException specifies the height, in lines, of the text area, and
numChars specifies its width,in characters
TextArea(String str, int numLines, int you can specify the scroll bars that you want the
numChars, int sBars) throws control to have. sBars must be one of these values:
HeadlessException
SCROLLBARS_BOTH, SCROLLBARS_NONE,
SCROLLBARS_HORIZONTAL_ONLY,
SCROLLBARS_VERTICAL_ONLY
Methods of TextArea
Method Description
void append(String str) appends the string specified by str to the end
of the current text
void insert(String str, int index) inserts the string passed in str at the specified
index
void replaceRange(String str, int startIndex, It replaces the characters from startIndex to
int endIndex) endIndex–1, with the replacement text passed
in str
229
Output:
230
Component:Check Box
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group. Check boxes are objects of the
Checkbox class.
Constructors Description
Checkbox( ) throws HeadlessException creates a check box whose label is initially
blank. The state of the check box
isunchecked.
Checkbox(String str) throws creates a check box whose label is
HeadlessException specified by str. The state of the check box
is unchecked
Checkbox(String str, boolean on) throws set the initial state of the checkbox. If on
HeadlessException is true, the check box is initially checked;
otherwise, it is cleared.
Checkbox(String str, boolean on, create a check box whose label is
CheckboxGroupcbGroup) throws specified by str and whose group is
HeadlessException specified by cbGroup. If this check box is
Checkbox(String str, not part of a group, then cbGroup must be
CheckboxGroupcbGroup, boolean on) throws null
HeadlessException The value of on determines the initial state
of the check box
Method Description
booleangetState( ) To retrieve the current state of a check box
void setState(boolean on) To set its state,Here, if on is true, the box is
checked. If it is false, the box is cleared
Component:CheckboxGroup
Example on CheckBox component:
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons
Methods of CheckboxGroup
Method Description
Checkbox getSelectedCheckbox( ) You can determine which check box in a
group is currently selected
void setSelectedCheckbox(Checkbox which) You can set a check boxHere, which is the
check box that you want to be selected.
The previously selected check box will be
turned off
Example on CheckBoxGroup:
import java.awt.*;
public class CheckboxGroupExample
{
CheckboxGroupExample(){
Frame f= new Frame("CheckboxGroup Example");
CheckboxGroupcbg = new CheckboxGroup();
Checkbox checkBox1 = new Checkbox("C++", cbg, false);
checkBox1.setBounds(100,100, 50,50);
Checkbox checkBox2 = new Checkbox("Java", cbg, true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxGroupExample();
}
}
233
Component:Choice
The Choice class is used to create a pop-up list of items from which the user may choose.
Thus, a Choice control is a form of menu. When inactive, a Choice component takes up only
enough space to show the currently selected item. When the user clicks on it, the whole list of
choices pops up, and a new selection can be made.
Each item in the list is a string that appears as a left-justified label in the order it is added to
the Choice object.
Choice only defines the default constructor, which creates an empty list.
Here, name is the name of the item being added. Items are added to the list in the order
inwhich calls to add( ) occur.
Methods of Choice
Method Description
int getItemCount( ) To obtain the number of items in the list
void select(int index) You can set the currently selected item with a zero-
based integer index
void select(String name) You can set the currently selected item with a string
that will match a name in the list
String getItem(int index) you can obtain the name associated with the item at that
index
Here, index specifies the index of the desired item
String getSelectedItem( ) returns a string containing the name of the item
int getSelectedIndex( ) returns the index of the item. The first item is at index
0By default,the first item added to the list is selected
234
Example on Choice:
// importing awt class
import java.awt.*;
public class ChoiceExample1 {
// class constructor
ChoiceExample1() {
// creating a frame
Frame f = new Frame();
// main method
public static void main(String args[])
{
new ChoiceExample1();
}
}
235
Component:Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike theChoice
object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections.
Constructor of Lists
Constructors Description
List( ) throws HeadlessException The first version creates a List control that
allows only one item to be selected at any
onetime.
List(int numRows) throws In the second form, the value of numRows
HeadlessException specifies the number of entries in the list
that will always be visible (others can be
scrolled into view as needed).
List(int numRows, In the third form, if multipleSelect is true,
booleanmultipleSelect) throws then the user may select two or more items
at a time. If it is false, then only one item
HeadlessException
may be selected
Methods of Lists
Method Description
void add(String name) adds items to the end of the list
void add(String name, int adds the item at the index specified by index. Indexing
index) begins at zero--You can specify –1 to add the item to the
end of the list
String[ ] getSelectedItems() returns an array containing the names of the currently
selected items
int[ ] getSelectedIndexes( ) returns an array containing the indexes of the currently
selected items
int getItemCount( ) To obtain the number of items in the list,
void select(int index) You can set the currently selected item
String getItem(int index) you can obtain the name associated with the item
Here, index specifies the index of the desired item
236
Example on List:
// main method
public static void main(String args[])
{
new ListExample1();
}
}
Output:
237
AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach
any other component. It inherits the Container class.
Panel Example
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
238
}
}
JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited,
we use a scroll pane to display a large component or a component whose size can change
dynamically.
Constructors
Constructor Purpose
JScrollPane(Component,
int, int)
Useful Methods
void setColumnHeaderView(Component) It sets the column header for the scroll pane.
void setRowHeaderView(Component) It sets the row header for the scroll pane.
void setCorner(String, Component) It sets or gets the specified corner. The int parameter
specifies which corner and must be one of the
following constants defined in ScrollPaneConstants:
Component getCorner(String) UPPER_LEFT_CORNER,
UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
Example on JScrollPane
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JtextArea;
scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBA
R_ALWAYS);
scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AL
WAYS);
frame.getContentPane().add(scrollableTextArea);
}
public static void main(String[] args) {
241
javax.swing.SwingUtilities.invokeLater(new Runnable() {
Dialog
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize buttons
but Dialog doesn't have.
242
Dialog(Dialog owner)
1 Constructs an initially invisible, modeless Dialog with the specified owner
Dialog and an empty title.
Dialog(Frame owner)
5 Constructs an initially invisible, modeless Dialog with the specified owner
Frame and an empty title.
void addNotify()
1
Makes this Dialog displayable by connecting it to a native screen resource.
AccessibleContext getAccessibleContext()
2
Gets the AccessibleContext associated with this Dialog.
Dialog.ModalityType getModalityType()
3
Returns the modality type of this dialog.
String getTitle()
4
Gets the title of the dialog.
243
void hide()
5
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
boolean isModal()
6
Indicates whether the dialog is modal.
boolean isResizable()
7
Indicates whether this dialog is resizable by the user.
boolean isUndecorated()
8
Indicates whether this dialog is undecorated.
void setVisible(boolean b)
15
Shows or hides this Dialog depending on the value of parameter b.
void show()
16
Deprecated. As of JDK version 1.5, replaced by setVisible(boolean).
void toBack()
17 If this Window is visible, sends this Window to the back and may cause it
to lose focus or activation if it is the focused or active Window.
244
Example1:
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}
245
Example 2 on Dialog:
import javax.swing.*;
class SimpleDialog{
frame.setSize(350,350);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
Output:
MenuBar Class
AWT MenuBar
The MenuBar class helps manage the menu bar of a particular frame. The menu bar handles the
menu items that are a part of it. It helps set keyboard shortcuts for easy access and passes them
along to its child menus.
The MenuBar class provides menu bar bound to a frame and is platform specific.
Class declaration
Class constructors
S.N. Constructor & Description
MenuBar()
1
Creates a new menu bar.
Functions
247
Example On MenuBar
import java.awt.*;
class MenuExample
MenuExample(){
menu.add(i1);
menu.add(i2);
menu.add(i3);
submenu.add(i4);
submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
248
new MenuExample();
Graphics
It is passed as an argument to paint and update methods and therefore can be accessed inside these
methods. paint() and update() methods are present in the Component class and thus can be overridden
for the component to be painted.
void paint(Graphics g)
void update(Graphics g)
249
example on Graphics
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
public GraphicsDemo()
setVisible(true);
setSize(300, 300);
addWindowListener(new WindowAdapter() {
@Override
System.exit(0);
});
}
250
new GraphicsDemo();
Output:
251
Layout Manager
A container has a so‐called layout manager to arrange its components. The layout
managers provide a level of abstraction to map your user interface on all windowing systems,
so that the layout can be platform‐independent.
Flow Layout
Border Layout
Grid Layout
Card Layout
Grid Bag Layout
Container's setLayout() method: container has a setLayout() method to set its layout manager
To set up the layout of a Container (such as Frame, JFrame, Panel, or JPanel), you
have to:
1.Construct an instance of the chosen layout object, via new and constructor, e.g., new
FlowLayout())
2.Invoke the setLayout() method of the Container, with the layout object created as
the argument;
3.Place the GUI components into the Container using the add() method in the correct
order; or into the correct zones.
import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTFlowLayoutDemo extends Frame
{
private Button btn1, btn2, btn3, btn4, btn5, btn6;
public AWTFlowLayoutDemo ()
{
setLayout(new FlowLayout());
btn1 = new Button("Button 1");
btn2 = new Button("This is Button 2");
btn3 = new Button("3");
btn4 = new Button("Another Button 4");
btn5 = new Button("Button 5");
btn6 = new Button("One More Button 6");
add(btn1); add(btn2); add(btn3); add(btn4); add(btn5);add(btn6);
setTitle("FlowLayout Demo"); // "super" Frame sets title
setSize(280, 150); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}
// The entry main() method
public static void main(String[] args)
{
new AWTFlowLayoutDemo(); // Let the constructor do the job
}
}
Output:
253
Constructors
public GridLayout(int rows, int columns);
public GridLayout(int rows, int columns, int hgap, int vgap);
// By default: rows = 1, cols = 0, hgap = 0, vgap = 0
import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTGridLayoutDemo extends Frame
{
private Button btn1, btn2, btn3, btn4, btn5, btn6;
// Constructor to setup GUI components and event handlers
public AWTGridLayoutDemo ()
{
setLayout(new GridLayout(3, 2, 3, 3));
BorderLayout.NORTH(orPAGE_START),
BorderLayout.CENTER.
You need not place components to all the 5 zones. The NORTH and SOUTH
components may be stretched horizontally; the EAST and WEST components may be
stretched vertically; the CENTER component may stretch both horizontally and vertically to
fill any space left over
Constructors
public BorderLayout();
import java.awt.*;
import java.awt.event.*;
// An AWT GUI program inherits the top-level container java.awt.Frame
public class AWTBorderLayoutDemo extends Frame
{
private Button btnNorth, btnSouth, btnCenter, btnEast, btnWest;
// Constructor to setup GUI components and event handlers
public AWTBorderLayoutDemo ( )
{
setLayout(new BorderLayout(3, 3));
// "super" Frame sets layout to BorderLayout, horizontal and vertical gaps of 3
pixels The components are added to the specified zone
btnNorth = new Button("NORTH");
add(btnNorth, BorderLayout.NORTH);
btnSouth= new Button("SOUTH ");
add(btnSouth, BorderLayout.SOUTH);
btnCenter = new Button("CENTER");
add(btnCenter, BorderLayout.CENTER);
btnEast = new Button("EAST");
add(btnEast, BorderLayout.EAST);
btnWest = new Button("WEST");
add(btnWest, BorderLayout.WEST);
setTitle("BorderLayout Demo"); // "super" Frame sets title
setSize(280, 150); // "super" Frame sets initial size
setVisible(true); // "super" Frame shows
}
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2); c.add("c",b3);
}
public void actionPerformed(ActionEvent e)
{
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}
Output:
258
Method Description
import java.awt.*;
public class GridBagLayoutExample extends Frame{
public GridBagLayoutExample()
{
setLayout(new GridBagLayout());
setTitle("GridBag Layout Example");
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
this.add(new Button("Button One"), gbc);
gbc.gridx = 1;
gbc.gridy = 0;
this.add(new Button("Button two"), gbc);
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.gridwidth = 2;
this.add(new Button("Button three"), gbc);
setSize(300, 300);
setVisible(true);
}
public static void main(String[] args)
{
new GridBagLayoutExample();
}
}
Output: