0% found this document useful (0 votes)
21 views79 pages

Chapter1 AWT

Uploaded by

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

Chapter1 AWT

Uploaded by

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

Advanced Java Programming

(22517)

By Prof. Biradar R.Y.


Department of Computer
Engineering
V.V.P. Polytechnic, Solapur
Teaching and Examination Scheme
AJP: Chapters/Units
Chapter Chapter Name Marks (As per
# Syllabus)
01 Abstract Windowing 12
Toolkit(AWT)

02 Swings 10

03 Event Handling 12

04 Networking Basics 10

05 Interacting with Database 12

06 Servlets 14
Course Outcomes
a) Develop programs using GUI Framework(AWT
and Swing).
b) Handle Events of AWT and Swing components.
c) Develop programs to handle events in java
programming.
d) Develop programs using networking concepts.
e) Develop programs using database.
f) Develop programs using Servlets.
Unit-1
Introduction to
Abstract Windowing
Toolkit (AWT)
4

12 Marks
Unit-1 Outcomes
a) To develop Graphical User Interface (GUI)
programs using AWT components
b) Create Frame window with specified AWT
components
c) Arrange the GUI components using different
layout.
d) Develop programs using Menu and Dialog
boxes
GUI (Graphical User Interface)
• GUI offers user interaction via some graphical
components.
• Graphical components such as Window, frame,
Panel, Button, Textfield, TextArea, Listbox,
Combobox, Label, Checkbox, etc.
• Using these components we can create an
interactive user interface for an application.
• GUI is entirely event based.
• GUI provides result to end user in response to
raised event.
GUI (Graphical User Interface)
button menus title bar menu bar combo box

scroll
bars
AWT (Abstract Window Toolkit)
• AWT contains numerous classes and methods
that allow us to create and manage window.
• import java.awt.*;
• Java AWT 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 components are heavyweight.
1.1 AWT Class Hierarchy
Object

Component

Many more
Container Label Button AWT
conponents

Window Panel

Frame Dialog Applet


Component
• At the top of the AWT hierarchy is the
Component class.
• Component is an object having a graphical
representation that can be displayed on the
screen and that can interact with the user.
• It is abstract class that encapsulates all of the
attributes of a visual component.
• It defines methods that are responsible for
managing events, such as mouse and keyboard
input, positioning and sizing the window,
current foreground and background color,font ,
etc.
Methods of Component class

Method Description
public void inserts a component
add(Component c) on this component.
public void setSize(int sets the size (width
width,int height) and height) of the
component.
public void defines the layout
setLayout(LayoutMan manager for the
ager m) component.
public void changes the visibility
setVisible(boolean of the component, by
status) default false.
Component
• MCQ
• Which object is responsible for remembering
the current foreground and background colors
and the currently selected text font?

A) Container
B) Component
C) Window
D) Panel

13
Container
• Container class is a subclass of Component.

• Holds another components and containers.

• Provided methods that allow other Component


to place on it.
• Container is a component in AWT that can
contain another components like buttons, text
fields, labels etc.
• Responsible for positioning any components that
it contains. It does this through the use of various
layout managers.
Container places its components in one of the
following layout.
• The job of a Container is to hold and
display Components

• A Container is also a Component.

• Some Container subclasses are Panel


(and Applet, JApplet), Window
(Frame, JFrame)
Panel
• Panel is a concrete subclass of Container.
• Panel is the immediate superclass of Applet.
• When screen output is directed to an applet, it is
drawn on the surface of a Panel object.
• Panel is one type of container that does not
contain a title bar, menu bar, or border.
• Default layout is FlowLayout.
• When you run an applet using an applet viewer,
the applet viewer provides the title and border.
• MCQ

• _____ does not contain a title bar, menu bar, or


border.
A)Frame
B)Panel
C)Dialog
D)None of the above

l
Applets
• Applet is a public class which is predefined by
java.applet.Applet.
• It is a small program that can be placed on
web.
• There is no main() method. So run using web
browser or appletviewer.
• Life cycle methods: init, start, paint, stop,
destroy
• Applet is container. Default layout is
FlowLayout.
• Applet is subclass of Panel.
• Applet is superclass of JApplet
• MCQ
1) ____ is a superclass of Applet.
A)Frame
B)Panel
C)Dialog
D)None of the above

2) ____ is a superclass of JApplet.


A)Frame
B)Panel
C)Dialog
D)Applet
Window
• Creates top-level window

• The window is the container that have no


borders and menu bars.
• Use Frame & Dialog class which is subclass of
Window class for creating window.
• Default layout is BorderLayout.
Frame
• It is subclass of Window.
• Frame has a title bar, menu bar, borders, and
resizing corners.
• Default layout is BorderLayout.

• Frame object can be created from


Application or Applet.
• Through Applet: Warning message will
display “Java Applet Window”.
• Through Program or Application: Normal
window is created.
• MCQ
• _____ has a title bar, menu bar, or border and
resizing corners.
A)Frame
B)Panel
C)Dialog
D)None of the above

e
1.2 Creating Windowed program
and Applets
• Extends Frame class
• Constructors are:
 Frame()
 Frame(String title)
• Setting and Getting window size:

 void setSize(int width, int height)


 void setSize(Dimension newsize)
 Dimension getSize()
1.2 Creating Windowed program
and Applets Cont…
• Showing and Hiding Frame
 void setVisible(boolean visibleFlag)

• Setting title to frame


 void setTitle(String title)
• Closing Frame:
 Implements WindowListener interface.
 Extends WindowAdapter class.
First Windowed Program
import java.awt.*;
public class FirstFrame extends Frame
{
FirstFrame()
{
setVisible(true); //required method
setSize(300,300); //required method
setTitle("FirstFrame");
}
public static void main(String args[])
{
FirstFrame fm=new FirstFrame();
}
}
First Windowed Program: Execution
• D:\> javac FirstFrame.java

• D:\>java FirstFrame
1.3 AWT Controls & Layout
Manager
• AWT Controls: Component which allows you to
interact with application.
• Labels
• Button
• Checkbox
• Checkbox group
• Scrollbars
• Text field
• Text Area
Some types of components
• Layout Manager: Positioning the components in the
container.
• Flow Layout
• Border Layout
• Grid Layout
• Card Layout
• Grid Bag Layout
• Menubars, menus, dialog boxes, file
dialog.
AWT Controls:
• Allows user to interact with application.
• Adding the control in Window
 First create instance of control.
 Call add() method defined by component
 Component add(Component compObj)
• Removing the Control
 Call remove() method defined by component
 void remove(Component obj)
 For remove all: removeAll() method call.
AWT Control: Label
• Used to just display string on window.
• Passive Component
• Constructors:
 Label( )
 Label(String str) //left - justified
 Label(String str, int how) // Label.LEFT,
Label.RIGHT, Label.CENTER
• Methods to perform operation
 About text:
1) void setText(String str)
2) String getText( )
 About Alignment
1) void setAlignment(int how)
2) int getAlignment( )
AWT Control: Button
• It contains a label and that generates an
event when it is
pressed.
• Active Components
• Constructors:
• Button( )
• Button(String str)
• Methods to perform operation: Setter and
Getter Method.
• void setLabel(String str)
• String getLabel( )
AWT Control: Button Handling
• When Button pressed which generates an event
when it is pressed.
• Implements ActionListener interface.
• Interface has defined actionPerformed()
method, called when event is generated.
• ActionEvent object is supplied as argument to
the
method.
• ActionEvent object refers both Button and
Label of
Button
• Label will get by using getActionCommand()
from ActionEvent which passed.
AWT Control: CheckBox
• Used to turn an option on or off.
• Small box: check mark or not.
• Each check box has label.
• Constructors are:
• Checkbox( )
• Checkbox(String str)
• Checkbox(String str, boolean on)
• Checkbox(String str, boolean on, CheckboxGroup
cbGroup)
• Checkbox(String str, CheckboxGroup cbGroup,
boolean on)
AWT Control: CheckBox

• Setter and Getter methods:


• boolean getState( )
• void setState(boolean on)
• String getLabel( )
• void setLabel(String str)
• The value of on determine initial state
(true/false).
AWT Control: CheckBox
Handling
• Check box is selected or deselected, an item event is
generated.
• For handling implements ItemListener interface
• ItemListener interface is defines
itemStateChanged( )
method.
• ItemEvent object is supplied as the argument.
• getState() : Get Status about checkbox.
• Following methods determine and set status:
• Checkbox getSelectedCheckbox( )
• void setSelectedCheckbox(Checkbox which)
AWT Control: Choice Class
• Used to create a pop-up list items.
• Default constructor Choice() create empty list.
• 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.
• For add item in list
• void add(String name)
• To determine selected item:
• String getSelectedItem( )
• int getSelectedIndex( )
• String getItem(int index)
AWT Control: Choice Class
• To get Item Count
• int getItemCount( )
• To select Item
• void select(int index)
• void select(String name)
AWT Control: Handling
Choice
• When Choice selected, an item event is
generated.
• Implements the ItemListener interface.
• Interface defines the itemStateChanged( )
method.
• ItemEvent object is supplied as the argument to
this method.
AWT Control:
List
• List class provides a compact, multiple-
choice, scrolling selection list.
• List object can be constructed to show any
number of choices in the visible window.
• In Choice only one item is shown.
• Constructors
• List( )
• List(int numRows)
• List(int numRows, boolean multipleSelect)
AWT Control:
List

• Following methods are used to add


items:
• void add(String name)
• void add(String name, int index)
• For single selection items:
• String getSelectedItem( )
• int getSelectedIndex( )
• For Multiple selection items:
• String[ ] getSelectedItems( )
• int[ ] getSelectedIndexes( )
AWT Control:
List

• To retrieve item:
• String getItem(int index)
• To get Item Count
• int getItemCount( )
• Active Item
• void select(int index)
AWT Control: List
Handling

• Two types of event generated:


• For double clicked: ActionEvent
generated.
• For select and deselect item: ItemEvent
generated.
• Implements ActionListener interface and
ItemListener.
AWT Control: Scrollbar
• enable user to select from range of values.
• Used to select continuous values between a
specified minimum and maximum.
• Scroll bars may be oriented horizontally or
vertically.
• Each end has an arrow , when clicked moves
the current value of the scroll bar one unit in
the direction of the arrow.
• The current value of the scroll bar is indicated
by the slider box for the scroll bar.
• The slider box can be dragged by the user to a
new position.
AWT Control: Scrollbar
• Constructors:
• Scrollbar( ) : construct new vertical scrollbar
• Scrollbar(int style) : : construct new scrollbar with style
orientation
• Scrollbar(int style, int initialValue, int thumbSize, int min,
int max)
• style : Scrollbar.VERTICAL or Scrollbar.HORIZONTAL
• For set Values:
• void setValues(int initialValue, int thumbSize, int min, int
max)
• For get and set current value:
• int getValue( )
• void setValue(int newValue)
AWT Control: Scrollbar
• For get Min and Max value:
• int getMinimum( )
• int getMaximum( )
• By default unit increment/decrement is 1
and Block page-up and page-down
increment/decrement is 10.
• to change increment :
• void setUnitIncrement(int newIncr)
• void setBlockIncrement(int newIncr)
AWT Control: Handling
Scrollbar
• AdjustmentEvent is generated.
• Implement the AdjustmentListener interface.
• adjustmentValueChanged() method we have to override
• getAdjustmentType( ) method can be used to determine
the type of the adjustment.
• BLOCK_DECREMENT: A page-down event has been
generated.
• BLOCK_INCREMENT: A page-up event has been
generated.
• TRACK: An absolute tracking event has been generated.
• UNIT_INCREMENT : user clicks in the right arrow of a
horizontal scroll bar, or the bottom arrow of a vertical
scroll bar
• UNIT_DECREMENT : User clicks in the left arrow of a
horizontal sc bar, or the top arrow of a vertical scroll
AWT Control: TextField
• TextField is subclass of TextComponent.
TextComponent is subclass of Component.
• 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.
• Constructors:
• TextField( )
• TextField(int numChars)
• TextField(String str)
• TextField(String str, int numChars)
AWT Control: TextField
• Setter and Getter Method of TextField
and TextComponent:
• String getText( )
• void setText(String str)
• Particular Text selection:
• String getSelectedText( )
• void select(int startIndex, int endIndex)
• About Modification of Text:
• boolean isEditable( )
• void setEditable(boolean canEdit)
AWT Control: TextField

• Setting echo character to text field and related


methods:
• void setEchoChar(char ch)
• boolean echoCharIsSet( )
• char getEchoChar( )
• ActionEvent generates.
• Implements ActionListener Class
AWT Control: TextArea

• Sometimes a single line of text input is not enough for


a given task.
• It is multiline text editor
• Subclass of TextComponent.
• Constructors:
• TextArea( )
• TextArea(int numLines, int numChars)
• TextArea(String str)
• TextArea(String str, int numLines, int numChars)
• TextArea(String str, int numLines, int numChars, int
sBars)
AWT Control: TextArea
• The values of sbar:
• SCROLLBARS_BOTH
• SCROLLBARS_NONE
• SCROLLBARS_HORIZONTAL_ONLY
• SCROLLBARS_VERTICAL_ONLY
• It supports: getText( ), setText( ),
getSelectedText( ), select( ), isEditable(), and
setEditable( )
• Other some methods:
void append(String str)
void insert(String str, int index)
void replaceRange(String str, int startIndex, int
endIndex)
int getColumns()
int getRows()
Arranging components :
Layout Manager
• Layout means the arrangement of components
within the container.
• Layout manager automatically positions all the
components within the container.
• LayoutManager:
• Defines the interface for classes that know
how to lay out Containers.
Manually
setLayout(null);

setBounds(int x,int y,int


width,int height)

Button b1=new
Button(“Submit”);
b1.setBounds(50,50,100,50);
add(b1);
Arranging components :
Layout Manager

• Every Container has a layout manager


• The default layout for a Panel and Applet is
FlowLayout
• The default layout for a Window and Frame
is a BorderLayout
• We could set it explicitly with: setLayout()
setLayout (new
lowLayout( ));
Different Layout Manager
• FlowLayout
• The FlowLayout is the default layout.It layouts the
components in a directional/horizontally flow.
• BorderLayout
• The borderlayout arranges the components to fit in the five
regions: east, west, north, south and center.
• GridLayout
• The GridLayout manages the components in form of a
rectangular grid.
• CardLayout
• The CardLayout object treats each component in the
container as a card. Only one card is visible at a time.
• GridBagLayout
• This is the most flexible layout manager class. The object of
GridBagLayout aligns the component vertically, horizontally or
along their baseline without requiring the components of same
size.
FlowLayout

• Use add(component); to add to a component


when using FlowLayout
• Components are added left-to-right,top-to-
bottom
• If no room, a new row is started
• Exact layout depends on size of Applet
• Components are made as small as possible
• FlowLayout is convenient but often not good.
FlowLayout
alignment is determined by the align
property. The possible values are:
• LEFT
• RIGHT
• CENTER
• LEADING
• TRAILING
FlowLayout ()
Constructs a new FlowLayout with a centered
alignment and a default 5-unit horizontal and vertical
gap.
FlowLayout (int align)
Constructs a new FlowLayout with the
specified alignment and a default 5-unit horizontal
and vertical gap.
FlowLayout (int align, int hgap, int vgap)
Creates a new flow layout manager with the
indicated alignment and the indicated horizontal and
example:
FlowLayout
import java.awt.*;
import java.applet.*;
public class
FlowLayoutExample extends
Applet
{
public void init ()
{
setLayout (new FlowLayout ()); // default
add (new Button ("One"));
add (new Button ("Two"));
add (new Button ("Three"));
add (new Button ("Four"));
add (new Button ("Five"));
add (new Button ("Six"));
}
}
BorderLayout
• At most five components can be added
• If you want more components, add a Panel, then add
components to it.
• BorderLayout provides five constants for
each region:
public static final int NORTH
public static final int SOUTH
public static final int EAST
public static final int WEST
public static final int CENTER
BorderLayout
BorderLayout ()
Constructs a border layout with a with no
horizontal and vertical gap.
BorderLayout( int hgap, int vgap)
Constructs a border layout with a with given
horizontal and vertical gap.

• Ex: setLayout (new BorderLayout());


• While adding components foll. add() needs
to be used
void add(Component obj, int region)
Example : add (new Button("NORTH"),
BorderLayout.NORTH);

If region is not specified, then default is


center.
example:
BorderLayout
import java.awt.*;
import java.applet.*;
public class BorderLayoutExample extends Applet
{ public void init ()
{
setLayout (new BorderLayout());
add(new Button("One"), BorderLayout.NORTH);
add(new Button("Two"), BorderLayout.WEST);
add(new Button("Three"), BorderLayout.CENTER);
add(new Button("Four"), BorderLayout.EAST);
add(new Button("Five"), BorderLayout.SOUTH);
add(new Button("Six"), BorderLayout.SOUTH);
}
}
GridLayout
• The GridLayout manager divides the container up
into a given number of rows and columns:
• All sections of the grid are equally sized and as large
as possible
GridLayout ()
Constructs a grid layout with one column per
component in a row with no gap.

GridLayout ( int row, int col)


creates a grid layout with the given rows and
columns but no gaps between the components.
GridLayout ( int row, int col,int hgap, int
vgap)
creates a grid layout with the given rows and
columns and gaps between the components.
example: GridLayout
import java.awt.*;
import java.applet.*;
public class GridLayoutExample extends Applet
{
public void init ()
{
setLayout(new GridLayout(2, 3));
add(new Button("One"));
add(new Button("Two"));
add(new Button("Three"));
add(new Button("Four"));
add(new Button("Five"));
}
}
CardLayout
 The class CardLayout arranges each
component in the container as a card. Only one
card is visible at a time, and the container acts
as a stack of cards.
 Constructors:

CardLayout()
Creates a new card layout with gaps of size zero.

CardLayout(int hgap, int vgap)
Creates a new card layout with the specified
horizontal and vertical gaps.
CardLayout
 Cards are typically held in an object of type Panel.
 Panel must have CardLayout selected as its layout
manager.
 For Add component:

void add(Component panelObj, Object name);
 Methods:

void first(Container deck)

void last(Container deck)

void next(Container deck)

void previous(Container deck)

void show(Container deck, String cardName)
GridBagLayout
 GridBagLayout arranges components in a
horizontal and vertical manner.
 GridBagLayout is the most complex and flexible
of the standard layout managers.
 The components may not be of same
size. and can occupy multiple rows or
columns.
 Each component occupies one or
more cells known as its display area.
 The position and behavior of each component
.
is specified by an instance of the
GridBagConstraints class.
GridBagLayout
.
 GridBagConstraints that specifies how the
component is laid out within its display
area.
 With the help of the constraints object, we
arrange the component's display area on
the grid.
 Constructor:
 GridBagLayout()

 For customize a GridBagConstraints object by setting


one or more of its instance variables:

gridx, gridy:

Specifies the cell at the upper left of the component's
display area, The leftmost column has
address gridx=0 and the top row has
address gridy=0
GridBagLayout

gridwidth, gridheight:

Specifies the number of columns(for gridwidth) or rows
(for gridheight) in the component's display area. The default
value is 1.

fill:

Used when the component's display area is larger than the
component's requested size to determine whether (and how)
to resize the component.

Valid values:
GridBagConstraints.HORIZONTAL
GridBagConstraints.VERTICAL
GridBagConstraints.BOTH
GridBagConstraints.NONE
GridBagLayout

Anchor
Used when the component is smaller than its display
area to determine where (within the area) to place the
component.


ipadx, ipady:
Specifies the internal padding: how much
to add to the size of the component. The
default value is zero
MenuBar and
Menu
MenuBar and Menu
 Top-level window can have a menu bar associated with
it.
 A menu bar displays a list of top-level menu choices.
 Each choice is associated with a drop-down menu.
 Classes:

MenuBar : Contains one or more Menu objects

Menu : Contains one or more MenuItem objects

MenuItem : Object something selected by user.
 It is also possible to include checkable menu items
 These are menu options of type CheckboxMenuItem
and will have a check mark next to them when they are
selected.
MenuBar and Menu
 To create a menu bar, first create an instance of
MenuBar.
 Set MenuBar using setMenuBar(MenuBarObject)
 Next, create instances of Menu that will define the
selections displayed on the bar.
 Constructors:

Menu( )

Menu(String optionName)

Menu(String optionName, boolean removable)
 Individual menu items constructors:

MenuItem( )

MenuItem(String itemName)

MenuItem(String itemName, MenuShortcut keyAccel)
MenuBar and Menu
 Disable or enable a menu item by using:

void setEnabled(boolean enabledFlag)

boolean isEnabled( )
 Label set and get using:

void setLabel(String newName)

String getLabel( )
 Checkable menu item by using a subclass of
MenuItem
called CheckboxMenuItem. :

CheckboxMenuItem( )

CheckboxMenuItem(String itemName)

CheckboxMenuItem(String itemName, boolean on)
Dialog
Box
 Dialog boxes are primarily used to obtain user input.
 They are similar to frame windows, except that dialog
boxes are always child windows of a top-level window.
 Dialog boxes don’t have menu bars.
 In other respects, dialog boxes function like frame
windows.
 Dialog boxes may be modal or modeless.
 When a modal dialog box is active, all input is directed to
it until it is opened. For ex: open dialogbox, save
dialogbox, print dialogbox
 When a modeless dialog box is active, input focus can be
directed to another window in your program.
For ex: find & replace dialogbox, spelling and grammer
check dialog box
Dialog
Box
 Constructors:.
 Dialog(Frame parentWindow, boolean mode)
 Dialog(Frame parentWindow, String title, boolean

mode)
 To create Dialog Box:
 Create Frame or Applet

 Create another class which extends Dialog class.

 Call this new class from Frame/Applet class.

 In constructor of Extended Dialog class, use super

method and pass vales to constructor of Dialog.


FileDialog
 Java provides a built-in dialog box that lets the
user specify a file.
 To create a file dialog box, instantiate an object of type
FileDialog.
 Constructor:

 FileDialog(Frame parent, String boxName)

 FileDialog(Frame parent, String boxName, int how)

 FileDialog(Frame parent)

how: FileDialog.LOAD, FileDialog.SAVE

Methods:
String getDirectory( ) String getFile( )

You might also like