Professional Documents
Culture Documents
• The super class of all event classes is java.util.EventObject. Some of the important classes and
i. Object getSource()
This method is defined in the Event Object class. It returns the object that originated the
event. So if the user has clicked a Push button, the method getSource returns the object
user has clicked on the mouse, the method getID returns the integer defined as
MouseEvent.MOUSE_CLICKED.
of a button is an example of a semantic event. Following event classes are semantic classes:
> ActionEvent
> AdjustmentEvent
> ItemEvent
> TextEvent
> ComponentEvent
> ContainerEvent
> FocusEvent
> KeyEvent
> MouseEvent
> PaintEvent
> WindowEvent
Event types and corresponding EventSource & EventListener
MouseListener,
MouseEvent Component
MouseMotionListener
Event Listener
Event Listener Methods
interface
windowOpened(WindowEvent evt)
- modifiers keys
keys(alt,ctrl,shift,etc) are pressed. getWhen() - time
isShiftDown()
An action event is generated when a button is pressed; a list item is double clicked.
• Constructors:
Here
src - is reference to the object that generated this event. type - is type of
event. cmd - is command string.
modifiers - indicates which modifier keys(ALT, CTRL, META, and /or SHIFT)
were pressed when event was generated. when - parameter specifies when
the event occurred.
• Methods:
• Constructor:
AdjustmentEvent(Adjustable src, int id, int type, int data)
• Methods:
src - is the reference to the component that generates an event. type - type of event is
specified by 'type'.
Entry - item that generated, the item event is parsed. state - current state of the item.
Methods:
1. getItem()-Obtain a reference to the item that generated an event.
2. getItemSelectable()-Obtain a reference to a ItemSelectable object. Lists and
choices are example of user interface elements that implement the
ItemSelectable interface.
3. getStateChange()-return the state change(selected or deselected)
• Constructor:
Src - is the reference to the object that generated this event. type - type of event
is specified by 'type'.
• Constants:
COMPONENT_HIDDEN: the
component is hidden. COMPONENT_MOVED: the component is
moved. COMPONENT_RESIZE: the component is resized. COMPONENT_SHOWN: the
component becomes visible.
• Methods:
• Constructors:
• Constructors:
i. KeyEvent(Component src, int type, long when, int modifiers, int code)
ii. KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
• Constants:
KEY_PRESSED
KEY_RELEASED
KEY_TYPED: event occurs when a character is generated, not all key presses result in
character.
• Methods:
src - is reference to the component that generated an event. type - type of an event is
'type'.
when - the system time at which the mouse event occurred is passed in 'when'.
Modifiers - argument indicates which modifiers were pressed when a mouse event
occurred.
triggersPopup - flag indicates if this event causes a pop-up menu to the button that
caused the event to be specified.
• Constants:
• Constructors:
WINDOW_ACTIVATED-window activated.
WINDOW_CLOSED-window closed.
WINDOW_CLOSING-the user requested that the window be closed.
WINDOW_DEACTIVATED-window deactivated. WINDOW_DEICONIFIED-window
deiconified. WINDOW_GAINED_FOCUS-window gained input focus.
WINDOW_ICONIFIED-window was iconified. WINDOW_LOST_FOCUS-window lost
focus.
WINDOW_OPENED-window was opened. WINDOW_STATE_CHANGED-window state
changed.
Window is subclass of Component event.
• Methods:
1. ActionListener Interface:-
■ It defines the method that is invoked when an action event occurs.
■ void actionPerformed(ActionEvent ae)
2. AdjustmentListener Interface:-
■ It defines the method that is invoked when an adjustment event occurs.
■ void adjustmentValueChanged(AdjustmentEvent ae)
3. ComponentListener Interface:-
■ It defines four methods that are invoked when a component is resized, moved, shown, or hidden.
■ void componentResized(ComponentEvent ce)
■ void componentMoved(ComponentEvent ce)
■ void componentShown(ComponentEvent ce)
■ void componentHidden(ComponentEvent ce)
4. ContainerListener Interface:-
■ It defines two methods that are invoked when a component is added to a container and when a
component is removed from a container.
■ void componentAdded(ContainerEvent ce)
■ void componentRemoved(ContainerEvent ce)
5. FocusListener Interface:-
■ It defines two methods that are invoked when a component gained a focus and when a component loses
a focus.
■ void focusGained(FocusEvent fe)
■ void focusLost(FocusEvent fe)
6. ItemListener Interface:-
■ It defines a method that is invoked when the state of an item changes.
■ void itemStateChanged(ItemEvent ie)
7. KeyListener Interface:-
■ It defines three methods that are invoked when a key of a keyboard is pressed, released and
typed.
■ void keyPressed(KeyEvent ke)
■ void keyReleased(KeyEvent ke)
■ void keyTyped(KeyEvent ke)
8. MouseListener Interface:-
■ It defines five methods that are invoked when mouse is entered, exited, pressed, released
and clicked.
■ void mouseEntered(MouseEvent me)
■ void mouseExited(MouseEvent me)
■ void mousePressed(MouseEvent me)
■ void mouseReleased(MouseEvent me)
■ void mouseClicked(MouseEvent me)
9. MouseMotionListener Interface:-
■ It defines two methods that are invoked when mouse is moved and dragged.
■ void mouseMoved(MouseEvent me)
■ void mouseDragged(MouseEvent me)
x=me.getX();
y=me.getY();
Program on KeyListener:
switch(k)
{
case KeyEvent.VK_F1:
msg+="<F1>";
break;
case KeyEvent.VK_F2:
msg+="<F2>";
break;
case KeyEvent.VK_F3:
msg+="<F3>";
break;
case KeyEvent.VK_PAGE_DOWN:
msg+="<pg down>";
break;
case KeyEvent.VK_PAGE_UP:
msg+="<pg up>";
break;
case KeyEvent.VK_LEFT:
msg+="<left arrow>";
break;
case KeyEvent.VK_RIGHT:
msg+="<right arrow>"; break;
}
repaint();
}
Program on WindowListener:-
Adapter Class:-
public MyMouseAdapter(AdapterDemo d)
{
ad=d;
}
Inner Classes:-
• An inner class is a class declared entirely within the body of another class or interface.
• It is nothing but a nested class.
• It can be used to simplify the code when using event adapter classes.
Example:-
• They are like local classes except that they do not have a name.
Example:-
What is GUI:-
AWT:-
• Java AWT (Abstract Windowing Toolkit) is an API to develop GUI or window-based application 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 uses the resources of system.
• The java.awt package provides classes for AWT API such as TextField, Label, TextArea, RadioButton,
CheckBox, Choice, List etc.
Window Fundamentals:
The AWT defines windows according to a class hierarchy that adds functionality and specificity with each level.
1. Component:-
• It is an abstract class that encapsulates all of the attributes of a visual component.
• All user interface elements that are displayed on the screen and that interact with the user are
subclasses of Component.
• It defines number of public methods that are responsible for managing events.
2. 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.
• It is responsible for laying out any components that it contains.
3. Panel:-
• The Panel is the container that doesn't contain title bar and menu bars.
• It can have other components like button, textfield etc.
• As a component it can be added to another container and as a container it can be added with
components.
• We can also nest the Panels.
4. Window:-
• Window comes with no borders and no menubar.
5. Frame:-
• The Frame is the container that contain title bar and can have menu bars.
6. Canvas:-
• It represents a blank rectangular area of the screen onto which the application can draw.
• It is designed for displaying simple graphics.
• The paint() must be overridden in order to perform custom graphics.
Frame:-
• It works like the main window where components are added.
• Constructors:¬
> Frame () - It creates a standard window without title.
> Frame (String title) - It creates a standard window with title.
• Methods:¬
> void setSize(int width, int height) - It is used to set the dimensions of the window.
> void setVisible(boolean flag) - The component is visible if the flag value is true. Otherwise it is hidden.
> void setTitle(String str) - It allows the user to additionally set the title to the frame.
> void setLocation(int x, int y) - It allows to set the x and y co-ordinates of Frame.
Example:-
import java.awt.*;
Control Fundamentals:-
AWT provides several controls through the classes. Controls are the components that allow a user to interact
with our application in various ways.
1. Label:-
• Constructors:¬
> Label () - It creates a blank label.
> Label (String str) - It creates a label that contains a string specified by str.
> Label (String str, int how) - It creates label that contains a string specified by str using alignment
specified by how. The value of how must be one of these three constants: Label.LEFT, Label.RIGHT, or
Label.CENTER.
• Methods:¬
> void setText(String str) - Assigns a new string to label.
> String getText() - reads the string from label.
> void setAlignment(int how) - sets the alignment as LEFT, RIGHT, CENTER to label.
> int getAlignment() - reads the alignment of a label.
Example:-
import java.awt.*;
public LabelDemo()
{
f=new Frame();
add(l1);
add(l2);
add(l3);
}
public static void main(String a[])
{
LabelDemo ld=new LabelDemo();
}
}
2. Button:-
• It is a component that contains a label and that generates an event when it is pressed.
• Constructors:¬
> Button() - It creates an empty button.
> Button(String str) - It creates a button that contains str as a label.
• Methods:¬
> void setLabel(String str) - sets label of a button.
> String getLabel() - gets a label of a button.
Example:
l1=new Label();
setLayout(new FlowLayout());
add(b1);
add(b2);
add(l1);
bl.addActionListener(this);
b2.addActionListener(this);
if(ae.getSource()==b1)
3. Checkbox:-
• It is used when there are multiple options and multiple selections to turn an option on or off.
• It is a small box that can either contain a check mark or not.
• Constructors:¬
> Checkbox() - create checkbox with blank label.
> Checkbox(String str) - create a checkbox with str label.
> Checkbox(String str, boolean on) - create a checkbox with string label with checked or unchecked.
• Methods:¬
> boolean getState() - gives the state as checked or unchecked.
> void setState(boolean on) - sets the state as checked or unchecked.
> String getLabel() - reads the label of checkbox.
> void setLabel(String str) - assigns the label to checkbox.
Example:-
import java.awt.*; import java.awt.event.*;
public class CheckboxDemo extends Frame implements ItemListener {
Checkbox cb1, cb2, cb3, cb4;
Label l1;
l1=new Label();
setLayout(new FlowLayout());
add(cb1);
add(cb2);
add(cb3);
add(cb4);
add(l1);
cb1.addItemListener(this);
cb2.addItemListener(this);
cb3.addItemListener(this);
cb4.addItemListener(this);
}
4. CheckboxGroup:-
• It is possible to create a set of mutually exclusive checkboxes in which one and only one checkbox in the
group can be checked at any one time.
• It is also known as RadioButton.
• Constructors:¬
> Checkbox(String str, boolean on, CheckboxGroup cbg)
> Checkbox(String str, CheckboxGroup cbg, boolean on)
These constructors create a checkbox whose label is as str and whose group is specified by cbg, the Boolean
value determine the initial state of checkbox.
• Methods:¬
> Checkbox getSelectedCheckbox() - reads the selected radio button from group.
> void setSelectedCheckbox(Checkbox c) - selects radio button option of a group.
Example:-
import java.awt.*; import java.awt.event.*;
cbg=new CheckboxGroup();
cb1=new Checkbox("One", false, cbg); cb2=new Checkbox("Two", false, cbg); cb3=new Checkbox("Three",
false, cbg); cb4=new Checkbox("Four", false, cbg);
l1=new Label();
setLayout(new FlowLayout());
add(cbl);
add(cb2);
add(cb3);
add(cb4);
add(l1);
5. Choice:-
• It provides drop down control for the option selection.
• It takes up only enough space to show the currently selected item.
• When user clicks on it, the whole list of choices pops up, and a new selection can be made.
• Choice class uses default constructor to create it.
• Methods:¬
> void add(String name) - it adds an item in the list.
> String getSelectedItem() - it reads the selected item from the list.
> int getSelectedIndex() - it reads the selected item index number from the list.
> int getItemCount() - it gives the number of items in the list.
> String getItem(int index) - it reads the item at given index.
Example:-
import java.awt.*;
import java.awt.event.*;
public ChoiceDemo()
{
super("Program using choice control");
browser.add("Netscape Navigator");
browser.add("Internet Explorer");
browser.add("Opera"); browser.add("Mozilla
Firefox"); //browser.select("Opera");
add(os);
add(browser);
os.addItemListener(this);
browser.addItemListener(this);
}
}
public void paint(Graphics g)
{
msg="Current OS:";
msg+=os.getSelectedItem();
g.drawString(msg, 200, 200);
msg="Current browser:";
msg+=browser.getSelectedItem();
g.drawString(msg, 200, 300);
}
6. List:-
• It provides a compact, multiple choices, scrolling selection list.
• We can select multiple options from the list.
• Constructors:¬
> List() - it creates normal list with single selection capability.
> List(int numrows) - creates a normal list with only single selection capability with specified number of rows.
> List (int numrows, Boolean multiselect) - create a list with specified number of rows with unabling or
disabling the multiple selection.
• Methods:¬
> void add(String name) - to add an item in the list.
> void add(String name, int index) - to add an item in the list at specified index.
> String getSelectedItem() - Reads the current selection from the list.
> int getSelectedIndex() - gives the index number of current selection.
> int getItemCount() - gives number of items present in the list.
> String getItem(int index) - reads the item from the list at specified index.
Example:
Frame f;
List 11;
String msg=" ";
Label l;
public ListDemo()
{
super("Program using List"); f=new Frame();
setSize(200, 200); setVisible(true); setLayout(new
FlowLayout());
l1.select(2);
add(l1);
l1.addActionListener(this);
7. Scrollbar:-
• When the contents of a window are too large to be displayed entirely within the window, a scroll
bar will appear.
• The scroll bar contains a slider that the user can click and drag to scroll through the window.
• It is a vertical bar on the right side of a window or a horizontal bar at the bottom of a window that
is used to move the window contents up and down or left and right.
• Constructors:¬
> Scrollbar() - it creates a vertical scroll bar.
> Scrollbar(int style) - it creates a scrollbar with specified orientation.
> Scrollbar(int style, int initialvalue, int thumbsize, int min, int max) - it creates a scrollbar with
specified orientation, sets the initial value, represents number of unit by thumbsize, minimum and
maximum value.
• Methods:¬
> void setValues(int initialvalue, int thumbsize, int min, int max)
> int getValue() - it returns current value of scrollbar.
> void setValue(int newValue) - sets the newValue for the scrollbar.
> int getMinimum() - returns the minimum value of scrollbar.
> int getMaximum() - returns the maximum value of scrollbar.
> void setUnitIncrement(int newIncr) - it allows to change increment value
> void setBlockIncrement(int newIncr) - it allows to change block increment value
Example:-
public ScrollBarDemo()
{
//int width=Integer.parseInt(getParameter("width"));
//int height=Integer.parseInt(getParameter("height")); setLayout(new FlowLayout());
add(vs);
add(hs);
vs.addAdjustmentListener(this);
hs.addAdjustmentListener(this);
addMouseMotionListener(this);
vs.setValue(y);
hs.setValue(x);
repaint();
}
}
}
8. TextField:-
• It is a single line text entry area.
• It allows the user to enter strings and to edit the text using the arrow keys, etc.
• It is a subclass of TextComponent.
• Constructors:¬
> TextField() - it creates default text field.
> TextField(int numchars) - it creates a textfield that is numchars characters wide.
> TextField(String str) - it creates a textfield with the string str.
> TextField(String str, int numchars) - it creates a textfield with string and sets its width with numchars.
• Methods:¬
> String getText() - to read the text from textfield
> void setText(String str) - to set the text to textfield.
> String getSelectedText() - reads only the selected text from the textfield.
> void select(int startindex, int endindex) - reads the currently selected text.
> boolean isEditable() - specify whether the textfield is editable or not.
> void setEditable(Boolean canEdit) - sets the text field editable.
> void setEchoChar(Char ch) - to disable the echoing of the characters as they are typed.
> boolean echoCharIsSet() - checks the textfield to see if it is in echochar mode.
> char getEchoChar() - it retrieves the echo character.
Example:
import java.awt.*; import java.awt.event.*;
TextFieldDemo()
{
setLayout(new FlowLayout());
setVisible(true);
setSize(200, 200);
add(l1);
add(name);
add(l2);
add(pass);
name.addActionListener(this);
pass.addActionListener(this);
}
9. TextArea:-
• It is a multiline editor.
• Constructors:¬
> TextArea() - it creates default textarea.
> TextArea(int numlines, int numchars) - it creates textare with specified number of
lines i.e. height and specified number of characters i.e. width.
> TextArea(String str) - creates textarea with specified string.
> TextArea(String str, int numlines, int numchars) - creates textarea with specified string,
height and width.
> TextArea(String str, int numlines, int numchars, int sBars) - creates textarea with
specified string, height, width and orientation of scrollbar.
• Methods:> String getText() - to read the text from textfield
> void setText(String str) - to set the text to textfield.
> String getSelectedText() - reads only the selected text from the textfield.
> void select(int startindex, int endindex) - reads the currently selected text.
> boolean isEditable() - specify whether the textfield is editable or not.
> void setEditable(Boolean canEdit) - sets the text field editable.
> void append(String s) - appends the string specified by s to the end of the current text.
> void insert(String s, int index) - inserts the string passed in s at the specified index.
> void replaceRange(String s, int startIndex, int endIndex) - replaces the character from
startIndex to endIndex-1 with the replacement text passed in s.
Example:-
import java.awt.*;
import java.awt.event.*;
TextAreaDemo()
{
String val="Textareas are almost self contained controls.
Your program incurs virtually no management overhead.
Textareas only generate got focus and lost focus events.
Normally your program simply obtains the current text when it is
needed.";
setLayout(new FlowLayout());
setVisible(true); setSize(200, 200);
add(t);
}
public static void main(String arg[])
{
TextAreaDemo td=new TextAreaDemo();
}
}
Layout Managers:-
• Sometimes we want more control over how GUI components are placed on our programs.
Layout managers are one way to do this.
• There are alternatives to layout managers which includes:
> Specifying the exact position of each component i.e. using setBounds().
> Using tools that design GUI's and generate code for absolute positioning.
• There are different types of layout managers are as:
1. FlowLayout:
■ This is default layout manager for applet.
■ All GUI components are simply placed on the GUI from left to right in the order as they are added.
■ Constructors:
> FlowLayout() - it creates default layout which centers components and leaves five pixels of space between
each component.
> FlowLayout(int how) - it specify how each component is aligned.
> FlowLayout(int how, int horz, int vert) - it specify the horizontal and vertical space between components.
■ Syntax:
setLayout(new FlowLayout());
■ All GUI components are aligned centered in a FlowLayout by default. We can change the alignment using
method setAlignment() or we can pass alignment as: setLayout(new
FlowLayout(FlowLayout.RIGHT));
■ Valid alignments are:
> FlowLayout.LEFT
> FlowLayout.CENTER
> FlowLayout.RIGHT
Example:-
import java.awt.*; import java.awt.event.*;
2. BorderLayout:
■ This is default layout manager for Frame which adds the component in Center by default.
■ It breaks the field up into five areas: north, south, east, west and center.
■ Constructors:
> BorderLayout() - it creates a default border layout.
> BorderLayout(int horz, int vert) - it allows to specify the horizontal and vertical space between
components.
■ Syntax:
setLayout(new BorderLayout());
■ We can set the alignment while adding the component as: add(button1, BorderLayout.NORTH);
Example:-
Frame f;
public BorderLayoutDemo()
setLayout(new BorderLayout());
Button("Left"), BorderLayout.WEST);
String msg="The BorderLayout class implements a common layout style for top-level
windows. It has four narrow, fixed-width components at the edges and one large area in the center.";
}*/
getInsets() methods leave a small amount of space between the container that holds components
and the window that contains it.
It returns Insets object that contains the top, bottom, left and right inset to be used.
3. GridLayout:
■ It lays out component in a two dimensional grid.
■ When we instantiate a GridLayout, we define the number of rows and columns.
■ Specifying number of rows as zero allows for unlimited length columns.
■ Specifying number of columns as zero allows for unlimited length rows.
■ Constructors:
> GridLayout() - it creates a single column grid layout.
> GridLayout(int rows, int columns) - It creates a grid layout with the specified number
of rows and columns.
> GridLayout(int rows, int columns, int horz, int vert) - It allows to specify the
horizontal and vertical space left between components with rows and columns.
■ Syntax:
Example:-
import java.awt.*;
import java.awt.event.*;
public class GridLayoutDemo extends Frame
int c=1;
public GridLayoutDemo() {
setSize(200, 200);
setVisible(true);
c++;
}
public static void main(String a[])
4. CardLayout:
■ It is unique among the other layout managers.
■ It manages the components in such a manner that only one component is visible at a time.
■ It treats each component as a card.
■ 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.
■ This can be useful for user interfaces with optional components that can be dynamically enabled and
disabled upon user input.
■ Constructors:
^ CardLayout() - it creates a layout with zero horizontal and vertical gap.
^ CardLayout(int hgap, vgap) - it creates a layout with the given horizontal and vertical gap.
■ Methods:-
^ void next(Container parent) - it is used to show the next card of the given container.
^ void previous(Container parent) - it is used to show the previous card of the given container.
^ void first(Container parent) - it is used to show the first card of the given container.
^ void last(Container parent) - it is used to show the last card of the given container.
^ void show(Container parent, String name) - it is used to display the card of the specified String name.
Example:-
import java.awt.*; import java.awt.event.*;
Card LayoutDemo()
{
c=new CardLayout();
setLayout(c);
c.show(this, "First");
}