[go: up one dir, main page]

0% found this document useful (0 votes)
38 views85 pages

CH 2-Abstract Window Toolkit

Uploaded by

Suhani Modi
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)
38 views85 pages

CH 2-Abstract Window Toolkit

Uploaded by

Suhani Modi
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/ 85

UNIT 2

ABSTRACT WINDOW
TOOLKIT
Introduction

 Java AWT (Abstract Window 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.
AWT Class Hierarchy
AWT Class Hierarchy
AWT Class Hierarchy

 Component
 A graphical user interface is built using different graphical elements called
components.

 A component is an object having a graphical representation that can be displayed on


the screen and that can interact with the user.

 Examples of components are the buttons, checkboxes, and scrollbars of a


typical graphical user interface.

 In AWT we have classes for each component as shown in the above diagram.
AWT Class Hierarchy

 Container
 Subclass of component

 A container contains and controls the layout of components.

 A container itself is a component (shown in the above hierarchy diagram).

 The classes that extends Container class are known as container such as Frame,
Dialog and Panel.

 Example of Container : Frame, Dialog and Panel etc.


AWT Class Hierarchy

 Window
 The window is the container that have no borders and menu bars. You must use frame,
dialog or another window for creating a window.

 Window is a rectangular area which is displayed on the screen.

 In different window we can execute different program and display different


data.

 Window provide us with multitasking environment.


AWT Class Hierarchy

 Panel
 The Panel is the container that doesn't contain title bar and menu bars.

 It can have other components like button, textfield etc.


 It is a generic container for holding components.
 An instance of the Panel class provides a container to which to add
components.
AWT Class Hierarchy

 Frame
 A Frame is a top-level window with a title and a border.

 The size of the frame includes any area designated for the border.

 Frame encapsulates window.

 A frame has title, border and menu bars.

 It can contain several components like buttons, text fields, scrollbars etc.

 This is most widely used container while developing an application in AWT.


AWT Class Hierarchy

 canvas
 Generally, it’s not part of a any hierarchy. But its another valuable type of
window.

 A Canvas component represents a blank rectangular area of the screen onto


which the application can draw or from which the application can trap input
events from the user.
Frame windows

 How to Creating a frame window in an applet

 First, create a subclass of Frame.

 Next, override any of the standard applet methods, such as init( ), start( ), and stop(
), and paint to show or hide the frame as needed.

 Finally, implement the windowClosing( ) method of the WindowListener interface,


calling setVisible(false) when the window is closed.

 By this the frame window only comes into existence, but it will not visible. It will be
visible by calling setVisible() method.

 After creating it has default size, which can be changed by using setSize().
Frame windows

 Frame’s constructors:

Frame( )
Frame(String title)

 Note:
 first form will create standard window without having any title.
 Second will create window with the specified title.
Frame windows

 We cannot specify the dimensions of the window.

 We must set the size of the window after it has been created.

 Some of the methods used when working with windows are as follows:
Frame windows

 SETTING THE WINDOW'S DIMENSIONS:

The setSize( ) method is used to set the dimensions of the window.

 Its signature is shown here:

void setSize(int newWidth, int newHeight)


void setSize(Dimension newSize)

 The new size of the window is specified by newWidth and newHeight, or by the
width and height fields of the Dimension object passed in newSize. The
dimensions are specified in terms of pixels.
Frame windows

 The getSize( ) method is used to obtain the current size of a window.

 Its signature is shown here:

Dimension getSize( )

 This method returns the current size of the window contained within the width
and height fields of a Dimension object.
Frame windows

 HIDING AND SHOWING A WINDOW:

After a frame window has been created, it will not be visible until you call
setVisible().

 Its signature is shown here:

void setVisible(boolean visibleFlag)

 The component is visible if the argument to this method is true. Otherwise, it is


hidden.
Frame windows

 SETTING A WINDOW'S TITLE:

You can change the title in a frame window using setTitle( ).

 Its signature is shown here:

void setTitle(String newTitle)

 Here, newTitle is the new title for the window.


Frame windows

 CLOSING A FRAME WINDOW:

 When using a frame window, your program must remove that window
from the screen when it is closed, by calling setVisible(false).

 To intercept a window-close event, you must implement the


windowClosing( ) method of the WindowListener interface. Inside
windowClosing( ), you must remove the window from the screen.
Creating Frame windows in Applet

// Create a child frame window from within an applet.


import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/*
<applet code="AppletFrame" width=400 height=60>
</applet>
*/
Creating Frame windows in Applet

import java.awt.Frame;
public class CreateFrameWindowExample extends Frame
{
CreateFrameWindowExample(String title)
{
super();
this.setTitle(title);
this.setVisible(true);
}
Creating Frame windows in Applet

public static void main(String args[])


{
CreateFrameWindowExample window =
new CreateFrameWindowExample("Create Window Example");
}
}
Creating Frame windows in Applet
AWT Controls

 Every user interface considers the following three main aspects:

 GUI elements : These are the core visual elements the user eventually
sees and interacts with. AWT provides a huge list of widely used and
common elements varying from basic to complex.

 Layouts: They define how GUI elements should be organized on the screen
and provide a final look and feel to the GUI (Graphical User Interface).

 Behavior: These are events which occur when the user interacts with GUI
elements.
AWT Controls

Every AWT controls inherits


properties from Component class.

Component
A Component is an abstract super
class for GUI controls and it represents
an object with graphical
representation.
AWT UI Elements

 Label: A Label object is a component for placing text in a container.


 Button :This class creates a labeled button.
 Check Box: A check box is a graphical component that can be in either an on (true) or off
(false) state.
 Check Box Group : The CheckboxGroup class is used to group the set of checkbox.
 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.
AWT UI Elements

 Choice : A Choice control is used to show pop up menu of choices. Selected choice is
shown on the top of the menu.
 Canvas : A Canvas control represents a rectangular area where application can draw
something or can receive inputs created by user.
 Image : An Image control is superclass for all image classes representing 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 File Dialog control represents a dialog window from which the user can
select a file.
Useful Methods of Component class

Method Description
public void add(Component c) inserts a component on this component.

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.

public void setVisible(boolean status) changes the visibility of the component, by


default false.
Label

 Label is a passive control because it does not create any event when accessed
by the user.
 The label control is an object of Label.
 A label displays a single line of read-only text.
 However the text can be changed by the application programmer but cannot be
changed by the end user in any way.
Class declaration
 Following is the declaration for java.awt.Label class:
public class Label
extends Component
implements Accessible
Continue….

 Field : Following are the fields for java.awt.Component class:


 static int CENTER -- Indicates that the label should be centered.
 static int LEFT -- Indicates that the label should be left justified.
 static int RIGHT -- Indicates that the label should be right justified.

Constructor Description
Label() Constructs an empty label.
Label(String text) Constructs a new label with the specified string of text,
left justified.
Label(String text, int Constructs a new label that presents the specified string of
alignment) text with the specified alignment.
Continue…

Method Description

int getAlignment() Gets the current alignment of this label.

String getText() Gets the text of this label.

protected String Returns a string representing the state of this Label.


paramString()
void setAlignment(int Sets the alignment for this label to the specified
alignment) alignment.
void setText(String text) Sets the text for this label to the specified text.
/*
Create AWT Label With Text Alignment Example
This java example shows how to create a label and align label text using AWT Label class.
*/
import java.applet.Applet;
import java.awt.Label;
/*
<applet code="CreateLableWithAlignment" width=100 height=200>
</applet>
*/

public class CreateLableWithAlignment extends Applet{

public void init(){

/*
* To create a label with it's text alignment use
* Label(String text, int alignment)
* constructor of AWT Label class.
*
* The possible alignment values are
* Label.LEFT, Label.RIGHT, and Label.CENTER
*/
Label label1 = new Label("Left Aligned Label", Label.LEFT);

Label label2 = new Label("Right Aligned Label", Label.RIGHT);

Label label3 = new Label("Center Aligned Label", Label.CENTER);

//add labels
add(label1);
add(label2);
add(label3);

/*
* To change alignment of label's text use
* void setAlignment(int alignment)
* method of AWT Label class.
*/

Label label4 = new Label("Set Center Alignment");


add(label4);
label4.setAlignment(Label.CENTER);

}
}
TextField

 The object of a TextField class is a text component that allows


the editing of a single line text.
 It inherits TextComponent class.

AWT TextField Class Declaration

public class TextField extends TextCompon


ent
TextField Example

import java.awt.*;
class TextFieldExample
{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Java");
t1.setBounds(50,100, 200,30);
TextField Example

t2=new TextField("AWT Tutorial");


t2.setBounds(50,150, 200,30);
f.add(t1);
f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Button

 It’s a control component.


 Has a label and generates an event.
 When button is pressed and released, AWT sends an instance of ActionEvent
to the button.
 Also able to get mouse actions for that an object of MouseEvent is passed to
button.
 To perform any action based on a button being pressed or released , it should
implement ActionListner and register the new listener.
 This can be done by calling the button’s addActionLisener() method.
Continue…

 Constructors
 Button()
 Button( String text)

Method Description
String getLabel() Get the label on the button
void setLabel(String text) Sets the label of button
Example

import java.applet.Applet;
import java.awt.*;

public class ButtonExample {


public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Continue…
Layout Manager

 Term Layout refers to positioning and sizing of components.

 A Layout manager is an object that

 Controls the positions and sizes of components

 Makes adjustment when necessary

 Definition : Layout manager means placing the components at a particular


position within the container and they can be different for each container.

 Layout manager tells java where to put components when they are added to
container.


Layout Managers

 Layouts allow you to format components on the screen in a platform-


independent way.
 The standard JDK provides many classes that implement the LayoutManager
interface, including:
 FlowLayout

 GridLayout

 BorderLayout

 CardLayout
Flow Layout

 FlowLayout is the default layout manager for Container objects.

 It will used to add components in a line, one after another(flow).

 When you add components to the screen, they will flow left to right
(centered) based on the order added and the width of the screen.

 Very similar to wrap text.

 If the screen is resized, the component’s flow will change based on


the new width and height.
Continue…

 Constructors
 FlowLayout()
 FlowLayout(int alignType)
 FlowLayout(int alignType, int hGap, int vGap)

• Here alignType int constants (FlowLayout.CENTER, FlowLayout.LEFT,


FlowLayout.RIGHT)
• Flowlayout inserts gap of 5 pixels between components (horizontally &
vertically)
• This value can be override by specifying values of hGap and vGap.
Example

import java.awt.*;

public class FlowLayoutDemo extends Frame{


// constructor
public FlowLayoutDemo(String title)
{
/* It would create the Frame by calling
* the constructor of Frame class.
*/
super(title);
Example

//Setting up Flow Layout


setLayout(new FlowLayout());

//Creating a button and adding it to the frame


Button b1 = new Button("Button:1");
add(b1);

/* Adding other components to the Frame


*/
Button b2 = new Button("Button:2");
add(b2);
Example

Button b3 = new Button("Button:3");


add(b3);

Button b4 = new Button("Button:4");


add(b4);

Button b5 = new Button("Button:5");


add(b5);

Button b6 = new Button("Button:6");


add(b6);
Example

Button b7 = new Button("Button:7");


add(b7);

Button b8 = new Button("Button:8");


add(b8);
}
public static void main(String[] args)
{ FlowLayoutDemo screen =
new FlowLayoutDemo("Flow Layout example");
screen.setSize(400,150);
screen.setVisible(true);
}}
Output
49
BorderLayout

 BorderLayout provides 5 areas to hold components.

 These are named after the four different borders of the screen, North,

South, East, West, and Center.

 When a Component is added to the layout, you must specify which area to

place it in.

 The order in which components are added is not important.

 The center area will always be resized to be as large as possible


50
BorderLayout

 Constructors

 BorderLayout(): creates a border layout but with no gaps between the


components.

 BorderLayout(int hgap, int vgap): creates a border layout with the


given horizontal and vertical gaps between the components.
Example

import java.awt.*;

public class BorderDemo extends Frame{


// constructor
public BorderDemo(String title)
{
/* It would create the Frame by calling
* the constructor of Frame class.
*/
super(title);
Example

setLayout(new BorderLayout());

Button b1 = new Button("NORTH");


add(b1, BorderLayout.NORTH);

Button b2= new Button("CENTER");


add(b2, BorderLayout.CENTER);

Button b3= new Button("WEST");


add(b3, BorderLayout.WEST);
Example

Button b4= new Button("SOUTH");


add(b4, BorderLayout.SOUTH);
Button b5= new Button("EAST");
add(b5, BorderLayout.EAST);
}
public static void main(String[] args)
{
BorderDemo screen = new BorderDemo("Border Layout Example");
screen.setSize(500,250);
screen.setVisible(true);
}}
Output
Grid Layout

 The GridLayout is used to arrange the components in rectangular


grid inside the container.

 One component is displayed in each rectangle.

 Components added to the container with the GridLayout manager are


arranged in order from left to right.

 Divide the container into equal-sized rectangles and arrange each


component into one of these cells.
Continue…

 Constructors of GridLayout class:

 GridLayout(): creates a default grid layout with default row and column.

 GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.

 GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns along with given horizontal and
vertical gaps.
Example

import java.awt.*; JButton b1=new JButton("1" f.add(b1);f.add(b2);f.add(b3);f.add(b


); 4);f.add(b5); f.add(b6);f.add(b7);f.ad
import javax.swing.*; d(b8);f.add(b9);
JButton b2=new JButton("2"
);
public class MyGridLayo JButton b3=new JButton("3" f.setLayout(new GridLayout(3,3));
ut{ ); f.setSize(300,300);
JFrame f; JButton b4=new JButton("4" f.setVisible(true); }
);
MyGridLayout(){
JButton b5=new JButton("5"
public static void main(String[] arg
f=new JFrame(); );
s)
JButton b6=new JButton("6"
{ new MyGridLayout(); } }
);
JButton b7=new JButton("7"
);
Output
Card Layout

 The CardLayout manager treats each component as a card. Only


one card/component visible at a time. So it is known as CardLayout.

 Each component in a container with this layout fills the entire container.

 The name card layout evolves from a stack of cards where one card is piled
upon another and only one of them is shown.

 In this layout, the first component that you add to the container will be at
the top of stack and therefore visible and the last one will be at the bottom.
Continue…

 Constructors of CardLayout

Constructor Description
Cardlayout() Creates a card layout with zero horizontal
and vertical gap.
CardLayout(int hgap, int Creates a card layout with the given
vgap) horizontal and vertical gap.
Summary of Layout Managers
Graphical User Interface with Swing

 It is part of Java Foundation Classes (JFC) that is used to create window-based applications.

 Java Swing provides platform-independent and lightweight components.

 The Swing components are 100% pure java window implementation to support them.

 Swing provides programmer the facility to change the look and feel of components being displayed on
any system. This is called ‘plaf’(pluggable look and feel)

 Look refers to the appearance

 Feel represents how the user can interact with the component.

 The javax.swing package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Difference between AWT and Swing
Hierarchy of Java Swing Classes
Methods of Component Class

Method Description

public void add(Component c) add a component on another component.

public void setSize(int width,int height) sets size of the component.

public void setLayout(LayoutManager m) sets the layout manager for the component.

public void setVisible(boolean b) sets the visibility of the component. It is by default false.
Continue…

 JFrame, JPanel, JWindow is the Swing's version of Frame, Panel and Windows
respectively.
 JApplet
 The JApplet class extends the Applet class.
 We can use JApplet that can have all the controls of swing.
 JLabel
 A JLabel is a single line label similar to java.awt.Label. Constructor:
Constructor Description
Jlabel() Creates label with no image and with an empty string for the title.
JLabel(Icon image) Creates a label with the specified image.
JLabel(String text) Creates a label with the specified text.
Continue…

 JTextField : The class JTextField is a component which allow the editing of a single
line of text.
 Jbutton : A JButton can be used in a GUI just like a java.awt.Button. It behaves like
an AWT Button, notifying ActionListener list elements when pushed.
 JCheckBox : A JCheckBox is similar to an AWT Checkbox that is not in a
CheckboxGroup.
 Purpose of the check box - an item that can be selected or deselected, and which displays its
state to the user.
 JRadioButton : The JRadioButton class is used to create a radio button.
 It is used to choose one option from multiple options.
 It should be added in Group to select one radio button only by using ButtonGroup class.
 By default radio button is not selected.
Continue…

 Menus : Every top-level window has a menu bar associated with it.
 This menu bar consists of various menu choices available to the end user.

 Further each choice contains list of options which is called drop down menus.

 Menu and MenuItem controls are subclass of MenuComponent class.

 JMenuItem : The JMenuItem class represents the actual item in a menu.


 All items in a menu should derive from class JMenuItem, or one of its subclasses.
EXAMPLE

 There are two ways to create a frame:


 By creating the object of Frame class (association)
 By extending Frame class (inheritance)

 We can write the code of swing inside the main(), constructor or any
other method.
EXAMPLE

import javax.swing.*;
public class SwingExample {

public static void main(String[] args) {


JFrame f = new JFrame();// creating instance of JFrame
JButton b = new JButton("click");// creating instance of JButton
b.setBounds(130, 100, 100, 40);// x axis, y axis, width, height
f.add(b);// adding button in JFrame
f.setSize(400, 500);// 400 width and 500 height
f.setLayout(null);// using no layout managers
f.setVisible(true);// making the frame visible
}
}
EXAMPLE
Events

 When the user interacts with a GUI application, an event is generated.

 Example : Pressing a button, Entering a character in Textbox., selecting an item or


closing a window.

 Definition: An Event describes the change of state of any object.

 The super class of all event classes is java.util.EventObject.

 Event handling has three main components:


 Events : An event is a change of state of an object.

 Events Source : Event source is an object that generates an event.

 Listeners : A listener is an object that listens the event. A listener gets notified when an event occurs.
Continue…

 A source generates an Event and sends it to one or more listeners registered with the
source.
 Once event is received by the listener, they process the event and then return.
 Events are supported by a number of Java packages, like java.util, java.awt and
java.awt.event.

Reacts to
the event
EVENT SOURCE EVENT LISTENER
Fires an event
object
Source
registers
listener
Continue…

 Every time user types a character or clicks mouse an event occurs.


 Any object can be notified of any particular event.
 To be notified for an event
1. Object has to be registered as an event listener on appropriate event source.
2. The object has to implement the appropriate interface on it to listen the event
occurrence.
 Each type of event has its own registration method in general form it is
 public void addTypeListener (TypeListener el)
 Here type can be replaced with name of event
 Example: keyboard event listener is registered by addKeyListener()
Event Classes
At the root of Java event class
hierarchy is EventObject which is in
java.util. It is a super class for all
events.
Constructors :
EventObject(Object src)
‘src’ is object that generates event.
Method
getSource()-returns the source of the
event.
toString()-returns string equivalent of
object.
Event Source

 It is the visual component with which user has interacted. Event source creates
the event object when event has occurred.

 User interface objects are as follow

 Button: Action event when button pressed

 Check Box: ItemEvent when selected or deselected

 Choice: ItemEvent when choice changed.

 List : ActionEvent when double-clicked; ItemEvent when selected or


deselected.
Event Listeners

 The Event listener represents the interfaces responsible to handle events.


 It is a main interface which every listener interface has to extend.
 This class is defined in java.util package.
 ActionListener : The class which processes the ActionEvent should implement
this interface.
 The object of that class must be registered with a component.
 The object can be registered using the addActionListener() method.
Mouse Listener
 The class which processes the MouseEvent should implement this interface.
 The object of that class must be registered with a component.
 The object can be registered using the addMouseListener() method.
Windows Listener
 The class which processes the WindowEvent should implement this interface.
 The object of that class must be registered with a component.
 The object can be registered using the addWindowListener() method.
Key Listener
 The class which processes the KeyEvent should implement this
interface.
 The object of that class must be registered with a component.
 The object can be registered using the addKeyListener() method.
Adapter Classes

 Some listener interfaces define several methods like MouseListener requires 5


methods , WindowListener requires 7 methods. But every time it is not needed
that all those methods to be implemented.

 For example if we want just one method to implement still we need to define
other methods also due to rule of interface implementation.

 For that java API provides several Adapter classes for each Listener interface.

 So if we only need some of methods to be overridden, we can extend the


appropriate adapter class rather than its listener interface.
Continue…

Listener Adapter

ComponentListener ComponentAdapter

ContainerListener ContainerAdapter

FocusListener FocusAdapter

KeyListener KeyAdapter

MouseListener MouseAdapter

You might also like