0% found this document useful (0 votes)
68 views21 pages

CJ Unit 5

This document provides an overview of the Abstract Window Toolkit (AWT) in Java. It discusses AWT component hierarchy including common components like labels, buttons, text fields. It also provides examples of creating frames and adding components. Constructors and methods of various AWT components like labels, buttons, text fields, checkboxes are described. Recommended books and prerequisites for learning AWT are also listed.

Uploaded by

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

CJ Unit 5

This document provides an overview of the Abstract Window Toolkit (AWT) in Java. It discusses AWT component hierarchy including common components like labels, buttons, text fields. It also provides examples of creating frames and adding components. Constructors and methods of various AWT components like labels, buttons, text fields, checkboxes are described. Recommended books and prerequisites for learning AWT are also listed.

Uploaded by

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

Core Java

Unit 5: Abstract Window Toolkit

Compiled by: Beena Kapadia


Beena.kapadia@vsit.edu.in

Vidyalankar School of
Information Technology
Wadala (E), Mumbai
www.vsit.edu.in
Certificate

This is to certify that the e-book titled “CORE JAVA” comprises all elementary learning tools for a better understating of

the relevant concepts. This e-book is comprehensively compiled as per the predefined eight parameters and guidelines.

Signature

Beena Kapadia
Date: 19-11--2019
Assistant Professor
Department of IT

DISCLAIMER: The information contained in this e- book is compiled and distributed for educational
purposes only. This e-book has been designed to help learners understand relevant concepts with a more
dynamic interface. The compiler of this e-book and Vidyalankar Institute of Technology give full and due
credit to the authors of the contents, developers and all websites from wherever information has been
sourced. We acknowledge our gratitude towards the websites YouTube, Wikipedia, and Google search
engine. No commercial benefits are being drawn from this project.
Unit v Window Toolkit: Window Abstract Fundamentals
Contents:
1. Abstract Window Toolkit: Window Fundamentals
2. Component, Container, Panel, Window, Frame, Canvas
3. Components-Labels, Buttons
4. Check Boxes, Radio Buttons
5. Choice Menus
6. Text Fields
7. Scrolling List, Scrollbars
8. Panel, Frames
9. Event Handling: Delegation Event Model: Events, Event classes, Event listener interfaces using
delegation event model
10. Adapter classes, Inner classes
11. Flow Layout, Grid Layout, Border Layout, Card Layout

 Recommended Books:
1. Core Java 8 for Beginners - Vaishali Shah, Sharnam Shah
2. Java: The Complete Reference - Herbert Schildt McGraw Hill
3. Murach’s beginning Java with Net Beans - Joel Murach , Michael Urban
4. Core Java, Volume I: Fundamentals - Hortsman Pearson
5. Core Java, Volume II: Advanced Features - Gary Cornell and Hortsman
Pearson
3. Core Java: An Integrated Approach - R. Nageswara Rao

 Prerequisites and Linking



Prerequisites
Linking
Sem I Sem. II Sem.III Sem.V Sem. VI

Enterprise Java
IP OOPS DS, Python and Project Project
AWT(Abstract Window Toolkit)
Java AWT (Abstract Window Toolkit) is a package to develop GUI or window-based applications
in java.
Java AWT components are platform-dependent i.e. components are displayed according to the view
of operating system.

AWT classes content in java.awt package

The java.awt package provides:

• classes for AWT api such as TextField, Label, TextArea, RadioButton, CheckBox, Choice,
List etc.
• A complete set of UI components including windows, menus, buttons, check boxes, text
fields, scroll bars and scrolling lists required for use in a UI environment.
• Support for UI containers, which in turn can hold embedded containers.
• An event system for managing system and user events.
• Techniques and code specially for laying out UI components in such a way that permits
platform independent UI design.

AWT component hierarchy


• Component
Component class is the super class to all the other classes from which various GUI elements are
realized. It is primarily responsible for effecting the display of a graphic object on the screen. It also
handles the various keyboard and mouse events of the GUI application.

• Container
It is a component that contains another components like button,labels etc.

• Window
It is a container that has no border and menu bar. you can use frame and dialog to create window.

• Frame
It is a container that has the title and menu bar. It can have another component like label,button etc.

• Panel
It is a container but doesn't have title bar and menu bar. But it can have buttons,labels etc.

• Canvas
It is not part of the hierarchy for applet or frame windows. It’s a simple, blank, drawing surface. A
canvas is excellent for painting images or performing other graphics operations.
Awt component hierarchy

Methods of component class

Java AWT Example

To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
• By extending Frame class (inheritance)
• By creating the object of Frame class (association)

By extending Frame class (inheritance)

import java.awt.*;
public class LogIn extends Frame {
LogIn()
{
super("LogIn"); //calls the constructor of base class(Frame)
setVisible(true);
setBounds(300,200,300,200);
setBackground(Color.red);

}
public static void main(String[] args) {
new LogIn();

By creating the object of Frame class (association)

import java.awt.*;
public class LogIn {
public static void main(String[] args) {
Frame f=new Frame("LogIn");
f.setVisible(true);
//f.setSize(300,200);
f.setBackground(Color.yellow);
f.setBounds(100, 200, 300, 200);
}
}

https://www.youtube.com/watch?v=8D80vZHcs0g&list=PLDN4rrl48XKoYR1H6l19hvF_8SMHGd
Pvk
Java AWT Label
• The label are passive control that does not support any interaction with users.
• The object of Label class is a component for placing text in a container.
• It is used to display a single line of read only text.

Constructor
1. Label():- creates blank label
2. Label(String str)- Creates Label with specified String str.
String is left justified.
3. Label(String str,int how)- Creates Label with specified String str and using the alignment
specified by how. possible values for parameter "how" are Label.LEFT, Label.RIGHT,
Label.CENTER

Methods
1. void setText(String str):- sets the specified string str on the label.

2. String getText():- Returns the text on the Label.

3. void setAlignment(int how):- sets the alignment for the text on the label.

4. int getAligment():- returns the alignment of the text on the label.

Java AWT Button

It is a component that contains a label and generates an event when it is pressed.

Constructor
1. Button()

2. Button(String str)

Methods

1. void setLabel(String str)

2. String getLabel()

Java AWT TextField

single line user input

Constructor
1. TextField()
2. TextField(int numchars): width of the textfiled
3. TextField(String str,int numchars:-Creates a textfield with specified string "str" and width
"numchars"
4. TextField(string str):-creates a textfied with specified string

Methods:
1. void setText(String str):-
2. String getText():-
3. String getSelectedText():- this method returns selected text from the textfield.
4. void select(int startIndex,int endIndex) :- selects the text from textfield with start
index and end index.
5. void setEditable(boolean canEdit): used to set the status of the textfield whether it is editable or
not.
6. boolean isEditable()-returns true or false depending on whether textfield is editable or not.
7.void setEchoChar(char c):- set character c as a echo character for textfield.this method is used for
password field.
8. char getEchoChar():- returns echo character set for tecxtfield

Example:

import java.awt.*;
import java.awt.event.*;

public class txtExample extends Frame implements ActionListener {

Label l1,l2;
TextField t1;
Button b1;

txtExample ()
{
super("Color changing");
setLayout(new FlowLayout());
l1=new Label("Enter Name:-");
l2=new Label("Welcome ");
t1=new TextField(12);
b1=new Button("Change");
b1.addActionListener(this);
add(l1);add(t1);add(b1);add(l2);
setVisible(true);
setBounds(100,100,300,200);

}
public static void main(String[] args) {
new txtExample();
}

@Override
public void actionPerformed(ActionEvent e) {
t1.setForeground(Color.green);
String s=t1.getText();
l2.setText("Welcome to the world of java "+s);
l2.setForeground(Color.red);

}
}
Java AWT Checkbox
• The Checkbox class is used to create a checkbox.
• It is used to turn an option on (true) or off (false).
• Clicking on a Checkbox changes its state from "on" to "off" or from "off" to "on".

Java AWT CheckboxGroup

• The object of CheckboxGroup class is used to group together a set of Checkbox.


• At a time only one check box button is allowed to be in "on" state and remaining check box
button in "off" state.
• It inherits the object class.
• CheckboxGroup enables us to create radio buttons in AWT. There is no special control
for creating radio buttons in AWT.

constructor
1. Checkbox()
2. Checkbox(String str)
3. Checkbox(String str,boolean on)
4. Checkbox(String str,boolean on,CheckboxGroup cbgrp) //creates radio button
5. Checkbox(String str,CheckboxGroup cbgrp,boolean on) //creates radio button

Methods

1. boolean getState()
2. void setState(boolean on)
3. String getLabel()
4. void setLabel(String str)

Java AWT Choice


• The object of Choice class is used to show popup menu of choices.
• Choice selected by user is shown on the top of a menu.
• It inherits Component class.

Contsructor
1.Choice()

Methods
1. void add(String str)
2. String getSelectedItem()->return the text of selected Item
3. int getSelectedIndex()->returns the index of selected item
4. int getItemCount()-> returns the number of elements in choice box
5. String getItem(int index)-> returns the text of item present at specified index.
Java AWT Scrolling List
• The object of List class represents a list of text items.
• By the help of list, user can choose either one item or multiple items.
• It inherits Component class.
constructor
1. List()
2. List(int numRows)-numRows specifies number of elements to be displayed on the screen
res of them we be seen by scolling the list
3. List(int numRows,boolean multiSelect)-if multiselect is true then user can select multiple
elements from list
Methods
1.String[] getSelectedItems()
2. int[] getSelectedIndexes()

Java AWT Scrollbar


Scrollbar control represents a scroll bar component in order to enable user to select from range of
values.

Constructor
1. Scrollbar()
2. Scrollbar(int orientation)
3. Scrollbar(int orientation, int val, int visible, int min, int max)

Methods
1. int getMaximum()
2. int getMinimum()
3. int getOrientation()
4. int getValue()
5. void setMaximum(int newMaximum)
6. void setMinimum(int newMinimum)
7. void setOrientation(int orientation)
8. void setValue(int newValue)

Java AWT Panel


• The Panel is a simplest container class.
• It provides space in which an application can attach any other component.
• It inherits the Container class.
• It doesn't have title bar.

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event.


most of the events to which your program will respond are generated
when the user interacts with a GUI based program.
There are several types of events
1. generated by the mouse
2. the keyboard
3. various GUI controls such as a push button, scroll bar or checkbox.

The delegation event model:

The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanism to generate and process events.
Its concept is quite simple:
• a source generates an event and sends it to one or more listeners.
• In this scheme, the listener simply waits until it receives an event.
• Once an event is received, the listener processes the event and then returns.

The advantage of this design is that the application logic that processes events is cleanly separated
from the user interface logic that generates those events. A user interface element is able to
“delegate” the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to receive an event
notification. This provides an important benefit: notifications are sent only to listeners that want to
receive them. The following sections define events and describe the roles of sources and listeners.

Events
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user interface.
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. For example, an event may be generated when a timer expires, a counter exceeds a
value, a software or hardware failure occurs, or an operation is completed. You are free to define
events that are appropriate for your application.

Event Sources
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each type of
event has its own registration method.
Here is the general form: public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener.
For example,the method that registers a keyboard event listener is called addKeyListener( ).
The method that registers a mouse motion listener is called addMouseMotionListener( ). When an
event occurs, all registered listeners are notified and receive a copy of the event object. This is
known as multicasting the event. In all cases, notifications are sent only to listeners that register to
receive them. Event Listeners
A listener is an object that is notified when an event occurs. It has two major requirements. First, it
must have been registered with one or more sources to receive notifications about specific types of
events. Second, it must implement methods to receive and process these notifications. The methods
that receive and process events are defined in a set of interfaces found in java.awt.event.
For example, the MouseMotionListener interface defines two methods to receive notifications when
the mouse is dragged or moved. Any object may receive and process one or both of these events if it
provides an implementation of this interface.

Steps to perform Event Handling:


Following steps are required to perform event handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration methods. For
example:
The java.awt.event package provides many event classes and Listener interfaces for event handling.

Java Event classes and Listener interfaces:

https://www.youtube.com/watch?v=UaenPz_ERVU
Button
• public void addActionListener(ActionListener a){}
MenuItem
• public void addActionListener(ActionListener a){}
TextField
• public void addActionListener(ActionListener a){}
• public void addTextListener(TextListener a){}
TextArea
• public void addTextListener(TextListener a){}
Checkbox
• public void addItemListener(ItemListener a){}
Choice
• public void addItemListener(ItemListener a){}
List
• public void addActionListener(ActionListener a){}
• public void addItemListener(ItemListener a){}

ActionListener

• The Java ActionListener is notified whenever you click on the button or menu item.
• It is notified against ActionEvent.
• The ActionListener interface is found in java.awt.event package. It has only one method:
actionPerformed().

actionPerformed() method
The actionPerformed() method is invoked automatically whenever you click on the registered
component.

public abstract void actionPerformed(ActionEvent e);

//Example

import java.awt.*;
import java.awt.event.*;
public class ColorEx extends Frame implements ActionListener{
Label l1,l2;
TextField t1;
Button b1;
ColorEx()
{
super("Color");
setLayout(new FlowLayout());
l1=new Label("Enter Name:-");
l2=new Label();
t1=new TextField(20);
b1=new Button("Display");
b1.addActionListener(this);

add(l1);
add(t1);
add(b1);
add(l2);
setSize(300,300);
setVisible(true);
}
public static void main(String[] args) {
new ColorEx();
}

@Override
public void actionPerformed(ActionEvent e) {
String s=t1.getText();
l2.setText(s);
l2.setForeground(Color.red);
}

ItemListener(Checkbox,Choice,List)

The Java ItemListener is notified whenever you click on the checkbox or when you select the
element from choice or list control . It is notified against ItemEvent. The ItemListener interface is
found in java.awt.event package. It has only one method: itemStateChanged(). It has only one
method: itemStateChanged()
The itemStateChanged() method is invoked automatically whenever you click or unclick on the
registered checkbox component or when you change the selection from list or choice control.

MouseListener
It is notified whenever you chnage the state of mouse. It is notified against MouseEvent.
Methods

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);
4. public abstract void mousePressed(MouseEvent e);
5. public abstract void mouseReleased(MouseEvent e);

KeyListener
It is notofied when the state of key is changed.It is notified against KeyEvent.

Methods
1.public abstract void keyReleased(KeyEvent ke)
2.public abstract void keyPressed(KeyEvent ke)
3.public abstract void keyTyped(KeyEvent ke)

Java Adapter Classes


Adapter class is used to overcome the problem of writing different methods of empty
implementations Normally if we use event listener, then we need to override all its methods in a
program. If we want to override only certain specific method, then in that case event listeners can be
replaced with event adapter class.

Most AWT listener interfaces, unlike ActionListener, contain more than one method. For example,
the MouseListener interface contains five methods: mousePressed, mouseReleased, mouseEntered,
mouseExited, and mouseClicked. Even if you care only about mouse clicks, if your class directly
implements MouseListener, then you must implement all five MouseListener methods. Methods for
those events you don't care about can have empty bodies. Here's an example:

//An example with cluttered but valid code.


MyClass implements MouseListener {
...
someObject.addMouseListener(this);
...
/* Empty method definition. */
public void mousePressed(MouseEvent e) {
}

/* Empty method definition. */


public void mouseReleased(MouseEvent e) {
}

/* Empty method definition. */


public void mouseEntered(MouseEvent e) {
}

/* Empty method definition. */


public void mouseExited(MouseEvent e) {
}

public void mouseClicked(MouseEvent e) {


...//Event handler implementation goes here...
}
}
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, you will not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

Event Class Adapter


ActionEvent ActionListener ActionAdapter
ItemEvent ItemListener ItemAdapter
MouseEvent MouseListener MouseAdapter
KeyEvent KeyListener KeyAdapter
AdjustmentEvent AdjustmentListener AdjustmentAdapter
TextEvent TextListener TextAdapter
ComponentEvent ComponentListener ComponentAdapter
ContainerEvent ContainerListener ContainerAdapter
MouseWheelEvent MouseWheelListener MouseWheelAdapter
WnndowEvent WindowListener WndowAdapter
To use an adapter, you create a subclass of it, instead of directly implementing a listener interface.
For example, by extending MouseAdapter, your class inherits empty definitions of all five of the
methods that MouseListener contains.

/* An example of extending an adapter class instead of


directly implementing a listener interface. */
MyClass extends MouseAdapter {
...
someObject.addMouseListener(this);
...
public void mouseClicked(MouseEvent e) {
...//Event handler implementation goes here...
}
}
//Example
import java.awt.*;
import java.awt.event.*;
public class MouseAdapterEx extends MouseMotionAdapter{
Frame f;
MouseAdapterEx(){
f=new Frame("Mouse Adapter");
//f.addMouseListener(this);
f.addMouseMotionListener(this);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e){
f.dispose();}
});
}
public void mouseDragged(MouseEvent e) {
Graphics g=f.getGraphics();
g.setColor(Color.BLUE);
g.fillOval(e.getX(),e.getY(),30,30);
}
public static void main(String[] args) {
new MouseAdapterEx();
}
}
//Example 2
import java.awt.*;
import java.awt.event.*;

public class MouseMotionAdapteEx extends MouseMotionAdapter {

Frame f;

MouseMotionAdapteEx() {

f=new Frame("MOuse Motion Exapmle");


f.addMouseMotionListener(this);
f.setLayout(null);
f.setSize(200,200);
f.setVisible(true);

f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e )
{
f.dispose();
}
});

public void mouseDragged(MouseEvent e)


{
Graphics g=f.getGraphics();
g.setColor(Color.red);
g.drawLine(e.getX(),e.getY(), 10, 10);
}
public static void main(String[] args) {
new MouseMotionAdapteEx();
}
}
Inner Class
In Java, just like methods, variables of a class too can have another class as its member. Writing a
class within another is allowed in Java. The class written within another class is called the inner
class, and the class that holds the inner class is called the outer class. Creating an inner class is quite
simple. You just need to write a class within a class. Unlike a class, an inner class can be private and
once you declare an inner class private, it cannot be accessed from an object outside the class.

Example of Inner class:


class Outer_Demo
{
int num;
// inner class
private class Inner_Demo
{
public void print()
{
System.out.println("This is an inner class");
}
}
// Accessing he inner class from the method within
void display_Inner()
{
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}
public class My_class {

public static void main(String args[])


{
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}
}

If you don't want to inherit your event-handling class from an adapter class then you can use concept
of Inner classes. For Example, suppose you write an applet, and you want your Applet subclass to
contain some code to handle mouse events. Since the Java language doesn't permit multiple
inheritance, your class can't extend both the Applet and MouseAdapter classes. The solution is to
define an inner class -- a class inside of your Applet subclass -- that extends the MouseAdapter
class,

//An example of using an inner class.


MyClass extends Applet {
...
someObject.addMouseListener(new MyAdapter());
...
class MyAdapter extends MouseAdapter {
public void mouseClicked(MouseEvent e) {
...//Event handler implementation goes here...
}
}
}
Inner classes work well even if your event handler needs access to private instance variables from
the enclosing class. As long as you don't declare an inner class to be static, an inner class can refer to
instance variables and methods just as if its code is in the containing class.

Layout Manager

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an


interface that is implemented by all the classes of layout managers. There are following classes that
represents the layout managers:

1. FlowLayout()

The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is the
default layout of applet or panel.

constructor:
1. FlowLayout()
2. FlowLayout(int how)-> FlowLayout.LEFT,RIGHT,CENTER,LEADING,TRAILING
3. FlowLayout(int how,int horz,int vert)

2. GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed
in each rectangle.

Constructor:
1. GridLayout()
2. GridLayout(int rows,int cols)
3. GridLayout(int row,int cols,int horz,int vert)
3. BorderLayout(default layout)

The BorderLayout is used to arrange the components in five regions: north, south, east, west and
center. Each region (area) may contain one component only. It is the default layout of frame or
window.

Constructor
1.BorderLayout()
2.BorderLayout(int horz,int vert)

4. CardLayout
manages the control in a such a way that only one component is visible at a time.
Constructor
1. CardLayout()
2. CardLayout(int horz,int vert)

Methods
1.void next(Container parent)
2. void previous(Container parent)
3. void first(Container parent)
4. void last(Container parent)
5. void show(Container parent,String name)

Applet
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. It runs inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:

1. It works at client side so less response time.


2. Secured
3. It can be executed by browsers running under many platforms, including Linux, Windows, Mac
Os etc.

Drawback of Applet
1. Plugin is required at client browser to execute applet.

Applet Life Cycle

applet life cycle includes following states


1. Initialization state:
applet enters the initialization state when it is first loaded. this is achievednby calling init()
method of Applet class. at this stage following task are erformed if required
a. create objects needed by the applet
b. set up initial values
c. Load images or fonts
d. Set up colors

public void init()


{
----
}

2. Running state
applet enters the running state when the system calls start() method of Applet class.
public void start()

3. Idle or Stopped state


An applet becomes idle when it is stopped from running or by callin stop()method explicitly.
public void stop(){----}

4. Dead State
an applet is said to be dead when it is removed from memory. This occurs automatically by invoking
the destoy()method.
public void destroy(){---}

5. Display state
Applet moves to display state whenever it has to perform some output operations on the screen. the
paint() method is called to accomplish this task.
public void paint(Graphics g){--}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy