Java Unit-Iv
Java Unit-Iv
Object oriented thinking and Java Basics- Need for oop paradigm, summary of oop concepts, History of
Java, Java buzzwords, data types, variables, scope and lifetime of variables, arrays, operators,
expressions, control statements, type conversion and casting, simple java program, concepts of classes,
objects, constructors, methods, access control, this keyword, garbage collection, overloading methods
and constructors, parameter passing, recursion, nested and inner classes, exploring string class.
UNIT - II
Inheritance, Packages and Interfaces – Hierarchical abstractions, Base class object, subclass, subtype,
substitutability, forms of inheritance specialization, specification, construction, extension, limitation,
combination, benefits of inheritance, costs of inheritance. Member access rules, super uses, using final
with inheritance, polymorphism- method overriding, abstract classes, the Object class. Defining,
Creating and Accessing a Package, Understanding CLASSPATH, importing packages, differences
between classes and interfaces, defining an interface, implementing interface, applying interfaces,
variables in interface and extending interfaces. Exploring java.io.
UNIT - III
Exception handling and Multithreading-- Concepts of exception handling, benefits of
exception handling, Termination or resumptive models, exception hierarchy, usage of try,
catch, throw, throws and finally, built in exceptions, creating own exception subclasses.
Exploring java.util. Differences between multithreading and multitasking, thread life cycle,
creating threads, thread priorities, synchronizing threads, inter thread communication, thread
groups, daemon threads. Enumerations, autoboxing, annotations, generics.
UNIT - IV
Event Handling: Events, Event sources, Event classes, Event Listeners, Delegation event
model, handling mouse and keyboard events, Adapter classes. The AWT class hierarchy, user
interface components- labels, button, canvas, scrollbars, text components, check box,
checkbox groups, choices, lists panels – scrollpane, dialogs, menubar, graphics, layout
manager – layout manager types – border, grid, flow, card and grid bag.
UNIT - V
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets. Swing – Introduction,
limitations of AWT, MVC architecture, components, containers, exploring swing- JApplet,
JFrame and JComponent, Icons and Labels, text fields, buttons – The JButton class, Check
boxes, Radio buttons, Combo boxes, Tabbed Panes, Scroll Panes, Trees, and Tables.
TEXT BOOKS:
1. Java the complete reference, 7th edition, Herbert schildt, TMH.
2. Understanding OOP with Java, updated edition, T. Budd, Pearson education.
REFERENCE BOOKS:
1. An Introduction to programming and OO design using Java, J.Nino and F.A. Hosch, John
wiley& sons.
2. An Introduction to OOP, third edition, T. Budd, Pearson education.
3. Introduction to Java programming, Y. Daniel Liang, Pearson education.
4. An introduction to Java programming and object-oriented application development, R.A.
Johnson- Thomson.
5. Core Java 2, Vol 1, Fundamentals, Cay.S. Horstmann and Gary Cornell, eighth Edition,
Pearson Education.
6. Core Java 2, Vol 2, Advanced Features, Cay.S. Horstmann and Gary Cornell, eighth
Edition, Pearson Education
7. Object Oriented Programming with Java, R.Buyya, S.T.Selvi, X.Chu, TMH.
8. Java and Object Orientation, an introduction, John Hunt, second edition, Springer.
9. Maurach’s Beginning Java2 JDK 5, SPD.
Events:
In the delegation model, an event is an object that describes a state change in a source. It canbe
generated as a consequence of a person interacting with the elements in a graphical userinterface.
Some of the activities that cause events to be generated are pressing a button,entering a character
via the keyboard, selecting an item in a list, and clicking the mouse.Many other user operations
could also be cited as examples.
Events may also occur that are not directly caused by interactions with a user
interface.Forexample, an event may be generated when a timer expires, a counter exceeds a
value, asoftware or hardware failure occurs, or an operation is completed. You are free to
defineevents that are appropriate for your application.
Event Sources:
A source is an object that generates an event. This occurs when the internal state of thatobject
changes in some way. Sources may generate more than one type of event.Asourcemust register
listeners in order for the listeners to receive notifications about a specific typeof event. Each type
of event has its own registration method.Here is the general form:
public void addTypeListener(TypeListenerel)
Here, Type is the name of the event and el is a reference to the event listener.
A source must also provide a method that allows a listener to unregister an interest in aspecific
type of event. The general form of such a method is this:
public void removeTypeListener(TypeListenerel)
Here, Type is the name of the event and el is a reference to the event listener.
Event Listeners:
A listener is an object that is notified when an event occurs. It has two majorrequirements.First, it
must have been registered with one or more sources to receivenotifications about specific types
of events. Second, it must implement methods to receiveand process these notifications.The
methods that receive and process events are defined in aset of interfaces found in java.awt.event.
Event Classes:
The ActionEvent Class:
An ActionEvent is generated when a button is pressed, a list item is double-clicked,oramenu item
is selected. The ActionEvent class defines four integer constants that can be usedto identify any
modifiers associated with an action event: ALT_MASK,CTRL_MASK,META_MASK, and
SHIFT_MASK. In addition, there is an integer constant,ACTION_PERFORMED, which can be
used to identify action events.
ActionEvent has these three constructors:
ActionEvent(Object src, int type, String cmd)
ActionEvent(Object src, int type, String cmd, int modifiers)
ActionEvent(Object src, int type, String cmd, long when, int modifiers)
Here, src is a reference to the object that generated this event. The type of the event isspecified
by type, and its command string is cmd. The argument modifiers indicates whichmodifier keys
(ALT, CTRL, META, and/or SHIFT) were pressed when the event wasgenerated. The when
parameter specifies when the event occurred. The thirdconstructor was added by Java 2, version
1.4.
You can obtain the command name for the invoking ActionEvent object by
usingthegetActionCommand( ) method, shown here:
String getActionCommand( )
For example, when a button is pressed, an action event is generated that has a commandname
equal to the label on that button.
The ItemEvent Class
An ItemEvent is generated when a check box or a list item is clicked or when a checkablemenu
item is selected or deselected. (Check boxes and list boxes are described later in thistutorial.)
There are two types of item events, which are identified by the following integerconstants:
DESELECTED The user deselected an item.
SELECTED The user selected an item.
In addition, ItemEvent defines one integer constant, ITEM_STATE_CHANGED,thatsignifies a
change of state.
ItemEvent has this constructor:
ItemEvent(ItemSelectablesrc, int type, Object entry, int state)
Here, src is a reference to the component that generated this event. For example, this mightbe a
list or choice element. The type of the event is specified by type. The specific item thatgenerated
the item event is passed in entry. The current state of that item is in state.ThegetItem( ) method
can be used to obtain a reference to the item that generated an event. Itssignature is shown here:
Object getItem( )
The getItemSelectable( ) method can be used to obtain a reference to the ItemSelectableobject
that generated an event. Its general form is shown here:
ItemSelectablegetItemSelectable( )
Lists and choices are examples of user interface elements that implement the
ItemSelectableinterface.ThegetStateChange( ) method returns the state change (i.e.,
SELECTEDorDESELECTED) for the event. It is shown here: int
getStateChange( )
The KeyEvent Class
A KeyEvent is generated when keyboard input occurs. There are three types of key events,which
are identified by these integer constants: KEY_PRESSED,KEY_RELEASED,
andKEY_TYPED. The first two events are generated when any key is pressed or released.
Thelast event occurs only when a character is generated.Remember, not all key presses result
incharacters. For example, pressing the SHIFT key does not generate a character. There aremany
other integer constants that are defined by KeyEvent. For example,VK_0 through
VK_9 and VK_A through VK_Z define the ASCII equivalents of thenumbers and letters. Here
are some others:
VK_ENTER VK_ESCAPE VK_CANCEL VK_UP
VK_DOWN VK_LEFT VK_RIGHT VK_PAGE_DOWN
VK_PAGE_UP VK_SHIFT VK_ALT VK_CONTROL
THE JAVA LIBRARY
The VK constants specify virtual key codes and are independent of any modifiers, such
ascontrol, shift, or alt. KeyEvent is a subclass of InputEvent. Here are two of its constructors:
KeyEvent(Component src, int type, long when, int modifiers, int code)
KeyEvent(Component src, int type, long when, int modifiers, int code, char ch)
Here, src is a reference to the component that generated the event. The type of the event
isspecified by type. The system time at which the key was pressed is passed in when.
Themodifiers argument indicates which modifiers were pressed when this key event
occurred.Thevirtual key code, such as VK_UP, VK_A, and so forth, is passed in code. The
characterequivalent (if one exists) is passed in ch. If no valid character exists, then
chcontainsCHAR_UNDEFINED. For KEY_TYPED events, code will contain
VK_UNDEFINED.
The KeyEvent class defines several methods, but the most commonly used ones
aregetKeyChar( ), which returns the character that was entered, and getKeyCode( ), whichreturns
the key code. Their general forms are shown here:
char getKeyChar( )
int getKeyCode( )
If no valid character is available, then getKeyChar( ) returns CHAR_UNDEFINED.
When a KEY_TYPED event occurs, getKeyCode( ) returns VK_UNDEFINED.
The MouseEvent Class
There are eight types of mouse events. The MouseEvent class defines the following
integerconstants that can be used to identify them:
MOUSE_CLICKED The user clicked the mouse.
MOUSE_DRAGGED The user dragged the mouse.
MOUSE_ENTERED The mouse entered a component.
MOUSE_EXITED The mouse exited from a component.
MOUSE_MOVED The mouse moved.
MOUSE_PRESSED The mouse was pressed.
MOUSE_RELEASED The mouse was released.
MOUSE_WHEEL The mouse wheel was moved (Java 2, v1.4).
MouseEvent is a subclass of InputEvent. Here is one of its constructors.
MouseEvent(Component src, int type, long when, int modifiers,int x, int y, int
clicks,booleantriggersPopup)
Here, src is a reference to the component that generated the event. The type of the event
isspecified by type. The system time at which the mouse event occurred is passed in when.
Themodifiers argument indicates which modifiers were pressed when a mouse event occurred.
The coordinates of the mouse are passed in x and y. The click count is passed in clicks.
ThetriggersPopup flag indicates if this event causes a pop-up menu to appear on this platform.
Java 2, version 1.4 adds a second constructor which also allows the button that caused theevent
to be specified. The most commonly used methods in this class are getX( ) and getY( ).
These return the X and Y coordinates of the mouse when the event occurred. Their formsare
shown here:
int getX( )
int getY( )
The TextEvent Class:
Instances of this class describe text events. These are generated by text fields and text areaswhen
characters are entered by a user or program. TextEvent defines the integer
constantTEXT_VALUE_CHANGED.
The one constructor for this class is shown here:
TextEvent(Object src, int type)
Here, src is a reference to the object that generated this event. The type of the event isspecified
by type.TheTextEvent object does not include the characters currently in the textcomponent that
generated the event. Instead, your program must use other methodsassociated with the text
component to retrieve that information. This operation differs fromother event objects discussed
in this section. For this reason, no methods are discussed herefor the TextEvent class. Think of a
text event notification as a signal to a listener that itshould retrieve information from a specific
text component.
The WindowEvent Class:
There are ten types of window events. The WindowEvent class defines integer constants thatcan
be used to identify them. The constants and their meanings are shown here:
WINDOW_ACTIVATED The window was activated.
WINDOW_CLOSED The window has been closed.
WINDOW_CLOSING The user requested that the window be closed.
WINDOW_DEACTIVATED The window was deactivated.
WINDOW_DEICONIFIED The window was deiconified.
WINDOW_GAINED_FOCUS The window gained input focus.
WINDOW_ICONIFIED The window was iconified.
WINDOW_LOST_FOCUS The window lost input focus.
WINDOW_OPENED The window was opened.
WINDOW_STATE_CHANGED The state of the window changed.
WindowEvent is a subclass of ComponentEvent. It defines several constructors.
The first is WindowEvent(Window src, int type)
Here, src is a reference to the object that generated this event. The type of the event is type.
Java 2, version 1.4 adds the next three constructors.
WindowEvent(Window src, int type, Window other)
WindowEvent(Window src, int type, int fromState, int toState)
WindowEvent(Window src, int type, Window other, int fromState, int toState)
THE JAVA LIBRARY
Here, other specifies the opposite window when a focus event occurs. The fromStatespecifies the
prior state of the window and toState specifies the new state that the windowwill have when a
window state change occurs.
Sources of Events:
some of the user interface components that can generate the events are listed below
Event Listener Interfaces:
The delegation event model has two parts: sources and listeners. Listeners are created
byimplementing one or more of the interfaces defined by the java.awt.event package. When
anevent occurs, the event source invokes the appropriate method defined by the listener
andprovides an event object as its argument.
The ActionListener Interface:
This interface defines the actionPerformed( ) method that is invoked when an action eventoccurs.
Its general form is shown here:
void actionPerformed(ActionEvent ae)
The AdjustmentListener Interface:
This interface defines the adjustmentValueChanged( ) method that is invoked when anadjustment
event occurs. Its general form is shown here:
void adjustmentValueChanged(AdjustmentEvent ae)
The ItemListener Interface:
This interface defines the itemStateChanged( ) method that is invoked when the state of anitem
changes. Its general form is shown here:
void itemStateChanged(ItemEventie)
The KeyListener Interface:
This interface defines three methods. The keyPressed( ) and keyReleased( ) methods areinvoked
when a key is pressed and released, respectively. The keyTyped( ) method isinvoked when a
character has been entered.
For example, if a user presses and releases the A key, three events are generated in sequence:
key pressed, typed, and released. If a user presses and releases the HOME key, two keyevents are
generated in sequence: key pressed and released. The general forms of thesemethods are shown
here:
void keyPressed(KeyEventke)
void keyReleased(KeyEventke)
void keyTyped(KeyEventke)
The MouseListener Interface:
This interface defines five methods. If the mouse is pressed and released at the same
point,mouseClicked( ) is invoked. When the mouse enters a component, the
mouseEntered( )method is called. When it leaves, mouseExited( ) is called. The
mousePressed( )andmouseReleased( ) methods are invoked when the mouse is pressed and
released,respectively.The general forms of these methods are shown here:
void mouseClicked(MouseEvent me)
void mouseEntered(MouseEvent me)
void mouseExited(MouseEvent me)
void mousePressed(MouseEvent me)
void mouseReleased(MouseEvent me)
The MouseMotionListener Interface:
This interface defines two methods. The mouseDragged( ) method is called multiple times asthe
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse ismoved.
Their general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
THE JAVA LIBRARY
The WindowListener Interface:
This interface defines seven methods. The windowActivated( ) and
windowDeactivated( )methods are invoked when a window is activated or deactivated,
respectively. If a window isiconified, the windowIconified( ) method is called. When a window
is deiconified,thewindowDeiconified( ) method is called. When a window is opened or
closed,thewindowOpened( ) or windowClosed( ) methods are called, respectively.
ThewindowClosing( ) method is called when a window is being closed. The general forms
ofthese methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
The TextListener Interface:
This interface defines the textChanged( ) method that is invoked when a change occurs in atext
area or text field. Its general form is shown here:
void textChanged(TextEventte)
Handling Mouse Events:
// Demonstrate the mouse event handlers.
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import javax.swing.JFrame;
import javax.swing.JLabel;
public class MouseEvents extends JFrame implements MouseListener {
JLabel JL;
public MouseEvents()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(300, 300);
setLayout(new FlowLayout(FlowLayout.CENTER));
JL = new JLabel();
Font f = new Font("Verdana", Font.BOLD, 20);
JL.setFont(f);
JL.setForeground(Color.BLUE);
add(JL);
addMouseListener(this);
setVisible(true);
}
public void mouseExited(MouseEvent m)
{
JL.setText("Mouse Exited");
}
public void mouseEntered(MouseEvent m)
{
JL.setText("Mouse Entered");
}
public void mouseReleased(MouseEvent m)
{
JL.setText("Mouse Released");
}
public void mousePressed(MouseEvent m)
{
JL.setText("Mouse Pressed");
}
public void mouseClicked(MouseEvent m)
{
JL.setText("Mouse Clicked");
}
public static void main(String[] args){
MouseEvents me = new MouseEvents();
}
}
Output:
The java.awt package provides classes for AWT API such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
Components
All the elements like the button, text fields, scroll bars, etc. are called components. In order to
place every component in a particular position on a screen, we need to add them to a container.
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.
There are four types of containers in Java AWT:
Window
Panel
Frame
Dialog
Window: Window is a top-level container that represents a graphical window or dialog box. The
Window class extends the Container class, which means it can contain other components, such as
buttons, labels, and text fields.
Panel: Panel is a container class in Java. It is a lightweight container that can be used for
grouping other components together within a window or a frame.
Frame: The Frame is the container that contains the title bar and border and can have menu bars.
Dialog: A dialog box is a temporary window an application creates to retrieve user input.
Useful Methods of Component Class
Method Description
public void setSize(int width,int height) Sets the size (width and height) of the component.
public void setLayout(LayoutManager m) Defines the layout manager for the component.
AWT UI Elements:
Following is the list of commonly used controls while designed GUI using AWT.
1. Label
2.Button
3.Check Box
A check box is a graphical component that can be in either an on (true) or off (false) state.
5.List
The List component presents the user with a scrolling list of text items.
6.Text Field
A TextField object is a text component that allows for the editing of a single line of text.
7.Text Area
A TextArea object is a text component that allows for the editing of a multiple lines of text.
8.Choice
A Choice control is used to show pop up menu of choices. Selected choice is shown on the
topof the menu.
9.Canvas
A Canvas control represents a rectangular area where application can draw something or can
10 Image
An Image control is superclass for all image classes representing graphical images.
11 Scroll Bar
A Scrollbar control represents a scroll bar component in order to enable user to select from
rangeof values.
12 Dialog
A Dialog control represents a top-level window with a title and a border used to take some
formof input from the user.
13 File Dialog
A FileDialog control represents a dialog window from which the user can select a file.
Label
Label( )
String getText( )
• To set the alignment of the string within the label, call setAlignment( )
int getAlignment( )
Example:
import java.awt.*;
import java.applet.*;
/*
</applet>
*/
add (one);
add (two);
add (three);
OUTPUT:
Button:
The most widely used control is Button. A button is a component that contains a label and that
generates an event when it is pressed.
Creating Button : Button b = new Button(String label);
Button Constructors:
1. Button() throws HeadlessException: It creates an empty button.
2. Button(String str) throws HeadlessException: It creates a button that contains str as a
label.
Button Methods :
1. void setLabel(String str): You can set its label by calling setLabel(). Here, str is the new
Label for the button.
2. String getLabel(): You can retrieve its label by calling getLabel() method.
Example to understand AWT Button Control in Java:
import java.awt.*;
import java.awt.event.*;
Check Box
A checkbox may be a control that’s used to turn an option on or off. It consists of a little box
that will either contain a check or not. There’s a label related to each checkbox that describes
what option the box represents. You modify the state of a checkbox by clicking on.
Checkboxes are often used individually or as a part of a gaggle. Checkboxes are objects of
the Checkbox class.
Checkbox Constructor
3. Checkbox(String str, Boolean on) throws HeadlessException: It allows you to line the
initial state of the checkbox. If one is true, the checkbox is initially checked; otherwise,
it’s cleared.
Methods of Checkbox
2. void setState(boolean on): To line its state, call setState(). Here, if one is true, the box is
checked. If it’s false, the box is cleared.
3. String getLabel(): you’ll obtain the present label related to a checkbox by calling
getLabel().
4. void setLabel(String str): To line the label, call setLabel(). The string passed in str
becomes the new label related to the invoking checkbox.
Example to understand AWT Checkbox Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
add (winXP);
add (winVista);
add (solaris);
add (mac);
winXP.addItemListener (this);
winVista.addItemListener (this);
solaris.addItemListener (this);
mac.addItemListener (this);
repaint ();
OUTPUT:
List
This component will display a group of items as a drop-down menu from which a user can select
only one item. The List class provides a compact, multiple-choice, scrolling selection list. Unlike
the selection object, which shows only the only selected item within the menu, an inventory
object is often constructed to point out any number of choices within the visible window. It also
can be created to permit multiple selections.
Creating List : List l = new List(int, Boolean);
List Constructor
1. List() throws HeadlessException: It creates a list control that allows only one item to be
selected at any one time.
2. List(int numRows) throws HeadlessException: Here, the value of numRows specifies the
number of entries in the list that will always be visible.
3. List(int numRows, booleanmultipleSelect) throws HeadlessException: If multipleSelect
is true, then the user may select two or more items at a time. If it’s false, then just one
item could also be selected.
Method of Lists
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added. It adds items to the end of the list.
2. void add(String name, int index): It also adds items to the list but it adds the items at the
index specified by the index.
3. String getSelectedItem(): It determines which item is currently selected. It returns a string
containing the name of the item. If more than one item is selected, or if no selection has
been made yet, null is returned.
4. int getSelectedIndex(): It determines which item is currently selected. It returns the index
of the item. The first item is at index 0. If more than one item is selected, or if no
selection has yet been made, -1 is returned.
5. String[] getSelectedItems(): It allows multiple selections. It returns an array containing
the names of the currently selected items.
6. int[] getSelectedIndexes(): It also allows multiple selections. It returns an array
containing the indexes of the currently selected items.
7. int getItemCount(): It obtains the number of items in the list.
8. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
9. String getItem(int index): It is used to obtain the name associated with the item at the
given index. Here, the index specifies the index of the desired items.
Example to understand AWT List Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ListDemo" width=300 height=180></applet> */
The TextField component will allow the user to enter some text. It is used to implement a
single-line text-entry area, usually called an edit control. It also allows the user to enter
strings and edit the text using the arrow keys, cut and paste keys, and mouse selections.
TextField is a subclass of TextComponent.
TextField Constructors
3. TextField(String str) throws HeadlessException: It initializes the text field with the string
contained in str.
TextField Methods
1. String getText(): It is used to obtain the string currently contained in the text field.
2. void setText(String str): It is used to set the text. Here, str is the new String.
3. void select(int startIndex, int endIndex): It is used to select a portion of the text under
program control. It selects the characters beginning at startIndex and ending at endIndex-
1.
7. void setEchoChar(char ch): It is used to disable the echoing of the characters as they are
typed. This method specifies a single character that TextField will display when
characters are entered.
8. booleanechoCharIsSet(): By this method, you can check a text field to see if it is in this
mode.
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
*/
public class TextfieldDemo extends Applet implements ActionListener
pass.setEchoChar ('?');
add (namep);
add (name);
add (passp);
add (pass);
name.addActionListener (this);
pass.addActionListener (this);
repaint ();
OUTPUT:
Text Area
Sometimes one line of text input isn’t enough for a given task. To handle these situations, the
AWT includes an easy multiline editor called TextArea.
Creating TextArea : TextArea ta = new TextArea();
TextArea Constructor
3. TextArea(String str) throws HeadlessException: It initializes the text area with the string
contained in str.
1. SCROLLBARS_BOTH
2. SCROLLBARS_NONE
3. SCROLLBARS_HORIZONTAL_ONLY
4. SCROLLBARS_VERTICAL_ONLY
TextArea Methods
1. void append(String str): It appends the string specified by str to the end of the current
text.
2. void insert(String str, int index): It inserts the string passed in str at the specified index.
3. voidReplaceRange(String str, int startIndex, int endIndex): It is used to replace the text. It
replaces the characters from startIndex to endIndex-1.
import java.awt.*;
+ "Moreover, Java has often led the way, charting the\n" + "course for
others to follow.";
add(text);
}
OUTPUT:
Choice
This component will display a group of times as a drop-down menu from which a user can
select only one item. The choice component is used to create a pop-up list of items from
which the user may choose. Therefore, Choice control is a form of a menu. When it is
inactive, a Choice component takes up only enough space to show the currently selected
item. When the user clicks on a Choice component, the whole list of choices pops up, and a
new selection can be made.
Note: Choice only defines the default constructor, which creates an empty list.
Creating Choice : Choice ch = new Choice();
Choice Methods
1. void add(String name): To add a selection to the list, use add(). Here, the name is the
name of the item being added.
2. String getSelectedItem(): It determines which item is currently selected. It returns a
string containing the name of the item.
3. int getSelectedIndex(): It determines which item is currently selected. It returns the
index of the item.
4. int getItemCount(): It obtains the number of items in the list.
5. void select(int index): It is used to set the currently selected item with a zero-based
integer index.
6. void select(String name): It is used to set the currently selected item with a string
that will match a name in the list.
7. String getItem(int index): It is used to obtain the name associated with the item at
the given index. Here, the index specifies the index of the desired items.
Example to understand AWT Choice Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="ChoiceDemo" width=300 height=180></applet> */
Canvas
Canvas encapsulates a blank window upon which you can draw in an application or receive
inputs created by the user.
Canvas Constructor:
1. Canvas() : Constructs a new Canvas.
2. Canvas (GraphicsConfiguration config) : Constructs a new Canvas given a
GraphicsConfiguration object.
Canvas Methods:
1. void addNotify(): It is used to create the peer of the canvas.
2. void createBufferStrategy(int numBuffers): It is used to create a new strategy for
multi-buffering on this component.
3. BufferStrategygetBufferStrategy(): It is used to return the BufferStrategy used by
this component.
Example to understand AWT Canvas Control in Java:
import java.awt.*;
import java.awt.event.*;
public class CanvasDemo
{
private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
public CanvasDemo ()
{
prepareGUI ();
}
mainFrame.add (headerLabel);
mainFrame.add (controlPanel);
mainFrame.add (statusLabel);
mainFrame.setVisible (true);
}
Image
Image control is superclass for all image classes representing graphical images.
Scroll Bar
Scrollbars are used to select continuous values between a specified minimum and
maximum. Scroll bars may be oriented horizontally or vertically. A scroll bar is really a
composite of several individual parts. Each end has an arrow that you simply can click to
get the present value of the scroll bar one unit within the direction of the arrow. The
current value of the scroll bar relative to its minimum and maximum values are indicated
by the slider box for the scroll bar. Scrollbars are encapsulated by the Scrollbar class.
Creating Scrollbar : Scrollbar sb = new Scrollbar();
Scrollbar Constructor
1. Scrollbar() throws HeadlessException: It creates a vertical scrollbar.
2. Scrollbar(int style) throws HeadlessException: It allows you to specify the
orientation of the scrollbar. If the style isScrollbar.VERTICAL, a vertical scrollbar
is created. If a style is Scrollbar.HORIZONTAL, the scroll bar is horizontal.
3. Scrollbar(int style, int initialValue, int thumbSize, int min, int max) throws
HeadlessException: Here, the initial value of the scroll bar is passed in initialValue.
The number of units represented by the peak of the thumb is passed in thumbSize.
The minimum and maximum values for the scroll bar are specified by min and max.
Scrollbar Methods
1. void setValues(int initialValue, int thumbSize, int min, int max): It is used to set the
parameters of the constructors.
2. int getValue(): It is used to obtain the current value of the scroll bar. It returns the
current setting.
3. void setValue(int newValue): It is used to set the current value. Here, newValue
specifies the new value for the scroll bar. When you set a worth, the slider box inside
the scroll bar is going to be positioned to reflect the new value.
4. int getMaximum(): It is used to retrieve the minimum values. They return the
requested quantity. By default, 1 is the increment added to the scroll bar.
5. int getMaximun(): It is used to retrieve the maximum value. By default, 1 is the
increment subtracted from the scroll bar.
Example to understand AWT Scrollbar Control in Java:
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/* <applet code="SBDemo" width=300 height=200></applet> */
File Dialog
Java's FileDialog class is part of the AWT (Abstract Window Toolkit) package, specifically
designed for creating a file dialog box. This dialog box serves as an intermediary between the
user and the underlying file system, allowing users to browse through directories, select files,
and perform operations on the selected files. With its easy-to-use methods, developers can
integrate file-handling capabilities seamlessly into their Java applications.
Example:
import java.awt.FileDialog;
import java.awt.Frame;
fileDialog.setVisible(true);
if (file == null) {
} else {
// A file was selected; print the selected file's name to the console.
}
OUTPUT:
A ScrollPane in AWT is a container that provides a scrollable view for a component (such as a TextArea or
Panel) when the content is larger than the visible area of the container. It automatically adds horizontal and
vertical scrollbars when required.
import java.awt.*;
// Create a frame
TextArea textArea = new TextArea("This is a large text area. Scroll to see more content.\n".repeat(30));
scrollPane.add(textArea);
frame.add(scrollPane);
frame.setSize(500, 500); // You may want to adjust the frame size as well
frame.setLayout(new BorderLayout());
frame.setVisible(true);
frame.addWindowListener(new java.awt.event.WindowAdapter() {
System.exit(0);
});
dialogs,
menubar,
graphics,
The layout will specify the format or the order in which the components have to be placed on the container.
Layout Manager may be a class or component that’s responsible for rearranging the components on the
container consistent with the required layout. A layout manager automatically arranges your controls within
a window by using some algorithm.
Each Container object features a layout manager related to it. A layout manager is an instance of any class
implementing the LayoutManager interface. The layout manager is about by the setLayout( ) method. If no
call to setLayout( ) is formed, the default layout manager is employed. Whenever a container is resized (or
sized for the primary time), the layout manager is employed to position each of the components within it.
The setLayout( ) method has the subsequent general form: void setLayout(LayoutManager layoutObj)
Here, layoutObj may be a regard to the specified layout manager. If you want to manually disable the layout
manager and position components, pass null for layoutObj. If you do this, you’ll get to determine the form
and position of every component manually, using the setBounds() method defined by Component.
1. Flow Layout
2. Border Layout
3. Card Layout
4. Grid Layout
5. GridBag Layout
Flow Layout
This layout will display the components from left to right, from top to bottom. The components
will always be displayed in the first line and if the first line is filled, these components are
displayed on the next line automatically.
In this Layout Manager, initially, the container assumes 1 row and 1 column of the window. Depending on
the number of components and size of the window, the number of rows and columns count is decided
dynamically.
Note: If the row contains only one component, then the component is aligned in the center position of that
row.
Example
import java.awt.*;
import javax.swing.*;
JFrame f;
FlowLayoutDemo ()
f.add (l1);
f.add (tf1);
f.add (b1);
f.setVisible (true);
Output:
Border Layout in Java
This layout will display the components along the border of the container. This layout contains five
locations where the component can be displayed. Locations are North, South, East, west, and Center. The
default region is the center. The above regions are the predefined static constants belonging to the
BorderLayout class. Whenever other regions’ spaces are not in use, automatically container is selected as a
center region default, and the component occupies the surrounding region’s spaces of the window, which
damages the look and feel of the user interface.
Creation of BorderLayout
Example
import java.awt.*;
f1.add (b5);
f1.setVisible (true);
Output:
A card layout represents a stack of cards displayed on a container. At a time, only one card can be visible,
each containing only one component.
add(“Cardname”, Component);
show(Container, cardname): It is used to flip to the specified card with the given name.
Example:
import java.awt.*;
import javax.swing.*;
import javax.swing.JButton;
import java.awt.event.*;
CardLayout cl;
Container c;
CardLayoutDemo ()
{
c = this.getContentPane ();
c.setLayout (cl);
b1.addActionListener (this);
b2.addActionListener (this);
b3.addActionListener (this);
setVisible (true);
setDefaultCloseOperation (JFrame.EXIT_ON_CLOSE);
cl.next (c);
}
OUTPUT:
The layout will display the components in the format of rows and columns statically. The container will be
divided into a table of rows and columns. The intersection of a row and column cell and every cell contains
only one component, and all the cells are of equal size. According to Grid Layout Manager, the grid cannot
be empty.
GridLayout gl = new GridLayout(int rows, int cols, int vgap, int hgap);
Example
import java.awt.*;
import javax.swing.*;
f1.setLayout (ob);
p1.add (l1);
p1.add (tf);
p1.add (b1);
f1.add (p1);
f1.add (p2);
f1.add (l2);
f1.setVisible (true);
OUTPUT:
In GridLayout manager, there is no grid control, i.e., inside a grid, we cannot align the component in a
specific position. To overcome this problem, we have an advanced Layout Manager, i.e., Grid Bag Layout
Manager. This layout is the most efficient layout that can be used for displaying components. In this layout,
we can specify the location, size, etc. In this Layout manager, we need to define grid properties or
constraints for each grid. Based on grid properties, the layout manager aligns a component on the grid, and
we can also span multiple grids as per the requirement. Gris properties are defined using the
GridBagConstraints class.
Properties of GridBagConstraints:
gridx, gridy: For defining x and y coordinate values, i.e., specifying grid location.
gridwidth, grid height: For defining the number of grids to span a document.
fill: Used whenever component size is greater than the area (i.e., VERTICAL or HORIZONTAL).
ipadx, ipady: For defining the width and height of the components, i.e., for increasing component size.
insets: For defining the surrounding space of the component, i.e., top, left, right, bottom.
anchor: Used whenever component size is smaller than area, i.e., where to place in a grid.
The above format is equal to one grid, so we can specify components in any grid position.
7. weightx, weighty: These are used to determine how to distribute space among columns(weightx) and
among rows(weighty), which is important for specifying resizing behavior.
Example
import java.awt.*;
{
public static void main (String[]args)
f1.setLayout (gb);
gc.fill = GridBagConstraints.HORIZONTAL;
gc.weightx = 0.5;
gc.weighty = 0.5;
gc.gridx = 0;
gc.gridy = 0;
gc.gridx = 1;
gc.gridy = 0;
gc.gridx = 2;
gc.gridy = 0;
gc.gridy = 1;
gc.gridwidth = 3;
gc.ipady = 40;
gc.gridx = 2;
gc.gridy = 3;
f1.pack ();
f1.setVisible (true);
OUTPUT: