CJ Unit 5
CJ Unit 5
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
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.
• 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.
• 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
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)
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();
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.
3. void setAlignment(int how):- sets the alignment for the text on the label.
Constructor
1. Button()
2. Button(String str)
Methods
2. String getLabel()
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.*;
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".
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)
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()
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)
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.
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.
//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
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)
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:
Frame f;
MouseMotionAdapteEx() {
f.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e )
{
f.dispose();
}
});
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,
Layout Manager
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:
Drawback of Applet
1. Plugin is required at client browser to execute applet.
2. Running state
applet enters the running state when the system calls start() method of Applet class.
public void start()
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){--}