Professional Documents
Culture Documents
JAVA_UNIT_3
JAVA_UNIT_3
JAVA_UNIT_3
2. Layouts
Layouts are useful for managing the different UI elements on the screen and
provide a well-organized look to the application.
3. Behavior
It explains how the UI elements act on triggering events performed by the
user.
1. Component
In the AWT class hierarchy, the component class is derived from the
Object class. Component class is an abstract class. It is superclass of all the
GUI element classes like container, button, label, checkbox, choice and list.
Therefore, component class is responsible for an overall graphical interface.
The component class encapsulates the visual component properties and
attributes.
2. Container
A container in AWT is a component, which holds all the other components
used for building the interface. Container can contain other components like
text, labels, buttons, tables, lists, etc. The container keeps a tab on other
components that are added to the GUI. We can insert another container inside
the main container.
2.2. Frame
A frame is a subclass of window. It has a border, menu bar, title bar. The
size of the frame can also be changed. It can hold all other AWT
components like buttons, checkboxes, etc. frames are the most widely
used type of AWT container.
2.3. Dialog
Dialog is a subclass of window. It contains a border and title bar. To
create a dialog object, an instance of the associated frame class is
always needed.
2.4. Panel
A panel is a subclass of container. The panel does not have border, title
bar, or menu bar. It is a generic container that holds other GUI
components. An instance of panel class is necessary in order to insert
the components.
3. Button
The button class allows the developer to create a button with an appropriate
label on it. It also provides a way to define functionality after clicking the
button. An event is generated when button is clicked.
4. List
A list class is used to display a list of required items. Using a list, the user can
select one or multiple items in it.
5. Checkbox
A checkbox can be used when an application wants the user to choose from
either true or false. It is used to provide options. When clicked, it changes the
state of the checkbox from ‘on’ to ‘off’ or vice-versa.
6. Label
As the name suggests, it is used as a label, or a method to display text on the
screen. The user cannot change the content of a label. It represents a read-
only text. A label provides descriptive text information on the application
window. It is placed inside a container.
7. Choice
A choice class is used to display a drop- down menu. The selected choice can
be seen on the head.
8. TextField
It is used to take single-line text input from the user. It can also be used to
display editable text. Unlike a label, which provides read- only text, the text
in the text field can be edited by the user.
9. TextArea
It allows the display of multiple lines of text. It provides ‘an area’ where text
can be displayed and also edited by the user.
The component class is an abstract class and hence we cannot use new
component() to create an instance of component. However, we can use the
constructors of concrete subclasses of component to create component
instances.
Example:
The helper classes, such as Graphics, color, font, fontMetrics, dimension, and
LayoutManager, are not subclasses of component. They are used to describe the
properties of GUI components, such as graphics context, colors, fonts, and
dimension, as described in below table:
Helper class Description
java.awt.Graphics It is an abstract class that provides the methods
for drawing strings, lines, and simple shapes.
java.awt.Color It deals with the colors of GUI components. For
example, we can specify background or
foreground colors in components like frame and
panel, or we can specify colors of lines, shapes,
and strings in drawings.
java.awt.Font It specifies fonts for the text and drawings on GUI
components. For example, we can specify the
font type (e.g., SansSerif), style (e.g., bold), and
size (e.g., 24 points) for the text on a button.
java.awt.FontMetrics It is an abstract class used to get the properties
of the fonts.
java.awt.Dimension It encapsulates the width and height of a
component (in integer precision) in a single
object.
java.awt.LayoutManager It specifies how components are arranged in a
container.
The frame is a subclass of window. It has a border, title bar, and menu bar.
Frame is a container which is used to hold components in it. Components such
as a button, checkbox, radio button, menu, list, table, etc.
Constructor Description
Frame() Creates a new frame object.
Frame(String name) Creates a new frame with a name passes as a title of
the frame.
Method Description
void setTitle(String t) Changes the title of the frame with the
new title specified.
public void add(component comp) This method adds the component, comp,
to the container frame.
public void setLayout(LayoutManager This method sets the layout of the
object)
components in a container, frame.
public void remove(component comp) This method removes a component,
comp, from the container, frame.
public void setSize(int widthPixel, This method sets the sizeof a frame in
int heightPixel)
terms of pixels.
When working with frame objects, the following steps are basically followed
to get a window to appear on the screen.
frame class.
import java.awt.*;
public class FrameDemo
{
FrameDemo()
{
Frame fm = new Frame();
fm.setTitle(“My First Frame”);
Label lb=new Label (“welcome to GUI Programming”);
fm.add(lb);
fm.setSize(300,300);
fm.setVisible(true);
}
public static void main(String args[])
{
FrameDemo ta= new FRameDemo();
}
}
//program to creating a frame by extending the frame class
import java.awt.*;
public class FrameDemo extends Frame
{
public FrameDemo()
{
Button btn= new Button(“submit”);
add(btn);
setSize(250,250);
setTitle(“my frame”);
setVisible(true);
}
public static void main(String args[])
{
FrameDemo ta=new FrameDemo();
}
}
An AWT panel in java can act as a container and a component. A container can
hold components like Buttons. For example, a frame window in AWT is a
container which can accommodate or add components. Unlike frame window,
the panel does not have the title and borders. However, one can assign a layout
manager to a panel.
Layout Managers
In many other window systems, the user- interface components are arranged by
using hardcoded pixel measurements. For example, put a button at location
(10, 10) in the window. Using hard-coded pixel measurements, the user interface
might look fine on one system but be unusable on another.
Flow layout
Flow layout is the simplest layout manager. The components are arranged in the
container from left to right in the order in which they were added. When one
row is filled, a new row is started.
According to this layout, the container will be divided int rows and columns
depending upon the components and their size. The components would be added
row- wise i.e., first row column-1, column-2, etc., if the row is filled, then the
next component would be added to first column of second row and so on.
import java.awt.*;
public class FlowLayoutDemo()
{
FlowLayoutDemo()
{
Frame f=new Frame();
Label l1=new Label(“enter name:”);
TextField t1=new TextField(10);
Label l2=new Label(“enter age:”);
TextField t2=new TextField(10);
Button b1=new Button(“submit”);
f.add(l1);
f.add(t1);
f.add(12);
f.add(t2);
f.add(b1);
f.setLayout(new FlowLayout(FlowLayout.RIGHT));
f.setSize(250,250);
f.setVisible(true);
}
public static void main(String[] args)
{
FlowLayoutDemo fl=new FlowLayoutDemo();
}
}
Output:
• The BorderLayout manager divides the window container in five regions i.e.
east, west, north, south and center.
• It is used to add the component at specified region.
• Components of the BorderLayout Manager
BorderLayout.NORTH
BorderLayout.EAST
BorderLayout.CENTER
BorderLayout.SOUTH
BorderLayout.WEST
Constructor Description
BorderLayout() It is used to create a new border layout with no
gaps between components.
BorderLayout(int hgap, It is used to construct a border layout with the
int vgap) specified gaps between components.
//program BorderLayout Demonstration
import java.awt.*;
public class BorderLayoutDemo
{
BorderLayoutDemo()
{
Frame frame= new Frame(“Border Layout”);
Button b1=new Button(“north”);
Button b2=new Button(“south”);Button b3=new
Button(“east”);
Button b4=new Button(“west”);
Button b5=new Button(“middle”);
frame.add(b1, BorderLayout.NORTH);
frame.add(b2, BorderLayout.SOUTH);
frame.add(b3, BorderLayout.EAST);
frame.add(b4, BorderLayout.WEST);
frame.add(b5, BorderLayout.CENTER);
frame.setSize(250.250);
frame.setVisible(true);
}
public static void main(String args[])
{
BorderLayoutDemo bl=new BorderLayoutDemo();
}
}
GridLayout
• The container will be divided into specific number of rows and columns of
equal size. Each division is called a cell or a grid.
• In the Grid Layout, only one component can be added to a grid and the
component occupies the entire grid.
Constructor Description
GridLayout() Creates a grid layout with a default of one
column per component in a single row.
GridLayout(int rows, Creates a grid layout with the specified number
int cols) of row and column.
GridLayout(int rows, Constructed a grid layout with the specified
int cols, int hgap, int number of rows and columns along with given
vgap) horizontal and vertical gaps.
import java.awt.*;
public class GridDemo
{
Frame frame=new Frame(“GridLayoutDemo”);
Button b1=new Button(“A”);Button b2=new Button(“B”);
Button b3=new Button(“C”);
Button b4=new Button(“D”);
Button b5=new Button(“E”);
Button b6=new Button(“F”);
frame.add(b1);
frame.add(b2);
frame.add(b3);
frame.add(b4);
frame.add(b5);
frame.add(b6);
frame.setLayout(new GridLayout(2,3));
frame.setSize(200,200);
frame.setVisible(true);
}
public static void main(String args[])
{
GridDemo gd=new GridDemo();
}
}
EVENT HANDLING
o Background events
Background events are those that require end-user interaction. Operating
system interrupts and hardware or software failure are examples of
background events.
o Events source
Event source is an object that generates an event. In java, nearly everything
is an object. The button is an object too. Source is the object generates an
event.
o Event listeners
A listener is an object that listens to the event. A listener gets notified when
an event occurs. Listener are also called as event handlers as they are the ones
responsible to handle events occurring at the source.
The image below shows the flow chart of the event delegation model.
Steps involved in the event delegation model are:
Step 1: We should attach an appropriate listener to a component. This is done
using addxxxListener() method. Similarly, to remove a listener from a
component, we can use removexxxListener () method.
Step 2: Implement the methods of the listener, especially the method which
handles the event.
Step 3: When an event is generated on the component, then the method in step2
will be executed and the event is handled.
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends Frame
{
public static void main(String args[])
{
MyFrame f=new MyFrame();
f.setTitle (“My Frame”);
f.setSize (400,250);
f.setVisible (true);
f.addWindowListener (new MyClass());
}
}
class MyClass implements WindowListener
{
public void windowActivated (WindowEvent e)
{
}
public void windowClosed (WindowEvent e)
{
}
public void windowClosing(WindowEvent e)
{
}
System.exit (0);
}
Mouse events
The user may click, release, drag, or move a mouse while interacting with the
application. If the programmer knows what the user has done, he can write the
code according to the mouse events. To trap the mouse events, mouseListener
and MouseMotionListener interfaces of java.awt.event package are used.
1. int getButton ()
This method returns a value representing a mouse button, when it is clicked
it return 1 if left button is clicked, 2 if middle button, and 3 if right button is
clicked.
2. int getX ()
This method returns the horizontal x position of the event relative to the
source component.
3. int getY ()
This method returns the vertical y position of the event relative to the source
component.
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
public class MouseListenerExample implements MouseListener
{
Label lbl1, lbl2;
Frame fr;
String s;
MouseListenerExample()
{
fr=new Frame (“java mouse listener example”);
lbl1=new Label (“demo for the mouse event”,
Label.CENTER);
lbl2= new Label ();
fr.setLayout (new FlowLayout ());
fr.add (lbl1);
fr.add(lbl2);
fr.addMouseListener (this);
fr.setSize (250,250);
fr.setVisibile (true);
}
public void mouseClicked(MouseEvent ev)
{
lbl2.setText(“Mouse button Clicked”);
fr.setVisible (true);
}
public void mouseEntered(MouseEvent ev)
{
lbl2.setText(“mouse has entered the area of window”);
fr.setVisible(true);
}
public void mouseExited( MouseEvent ev)
{
1b12.setText("Mouse has left the area of window");
fr.setVisible(true);
}
public void mousePressed (MouseEvent ev)
{
1b12.setText("Mouse button is being pressed");
fr.setVisible(true);
}
public void mouseReleased (MouseEvent ev)
{
1b12.setText (" Mouse Released");
fr.setVisible(true);
}
public static void main(String args[])
{
MouseListenerExample ml= new MouseListenerExample();
}
}
Key Events
KeyListener interface of java.awt.event package helps to know which key is
pressed or released by the user. It has 3 methods;
keyEvent class has the following methods to know which key is typed by the
user.
1. char getKeyChar ()
This method returns the key name (or character) related to the key pressed
or released.
2. int getKeyCode()
This method returns an integer number which is the value of the key pressed
by the user
//Program Key Events Demo
import java.awt.*;
import java.awt.event.*;
public class KeyListenerExample extends Frame implements
KeyListener
{
Label lbl;
TextArea ta;KeyListenerExample()
{
1b1 = new Label();
Lbl.setBounds (20, 50, 100, 20);
ta= new TextArea();
ta setBounds (20, 80, 300, 300);
ta addkeyListener(this);
add(lbl);
add(ta);
setSize (350, 350);
setLayout (null);
setVisible (true);
}
public void keyPressed(KeyEvent e)
{
lbl.setText (“key Pressed");
}
public void keyReleased (KeyEvent e)
{
lbl.setText("Key Released");
}
public void keyTyped (KeyEvent e)
{
lbl.setText("Key Typed");
}
public static void main(String[] args)
{
new KeyListenerExample();
}
}
The various AWT components are Label, Button, CheckBox, CheckBox Group,
List, Text Field, Text Area, Choice, Canvas, Image, Scrollbar, Dialog. File Dialog,
etc that creates or draw various components on web and manage the GUI based
application.
Label
• A label is a GUI control which can be used to display static text. Label can be
created using the Label class.
• The easiest control to use is a label. A label contains a string and is an object
of type Label. Labels are passive controls that do not support any interaction
with the user.
• Only single line text is allowed and the text can not be changed directly.
• Example:
Label n-new Label("Name:");
Label n=new Label("Age:", Label CENTER);
The second parameter specifies the text alignment. Valid values are Label.LEFT,
Label.CENTER or Label.RIGHT
import java.awt.*;
public class LabelDemo
{
public static void main(String args[])
{
Frame fr = new Frame("Label Demo");
Label lab1, lab2, lab3;
lab1 = new Label("Java Programming", Label.CENTER);
lab1.setBounds(50, 50, 200, 30);
lab2 = new Label("Database Management Systems");
lab2.setBounds(50, 100, 200, 30);
lab3 = new Label("Computer Architecture", Label.RIGHT);
lab3.setBounds(50, 150, 200, 30);
fr.add(lab1);
fr.add(lab2);
fr.add(lab3);
fr.setSize(300, 300);
fr.setLayout(null);fr.setVisible(true);
}
}
Output:
Button
• The button class is used to create a labeled button that has platform
independent implementation. The application result in some action when the
button is pushed.
• A push button or a button can be created by using the
import java.awt.";
public class ButtonDemo1
{
public static void main(String[] args)
{
Frame f1 = new Frame("Button Demo");
Button b1 = new Button("Press Here");
b1.setBounds(50, 100, 80, 50);
f1.add(b1);
f1.setSize(200, 200);
f1.setLayout(null);
f1.setVisible(true);
}
}
Text Field
A text field or text box is a single line text entry control which allows the
user to enter a single line of text. It inherits TextComponent class.
A text field can be created using the TextField class along with its
following constructors:
TextField ()
TextField (int numChars)
TextField (String str)
TextField (String str, int numChars)
//Program that we are creating two textfields to display single line text
string. This text is editable in nature. See the below example
import java.awt.*;
public class TextFieldDemo
{
public static void main(String args[])
{
Frame fr = new Frame("TextField Demo");
TextField text1, text2;
text1 = new TextField("Enter Your Name...");
text1.setBounds(60, 100, 150, 40);
text2 =new TextField("Enter Your Age...");
text2.setBounds(60, 150, 150, 40);
fr.add(text1);fr.add(text2);
fr.setSize(250, 250);
fr.setLayout(null);
fr.setVisible(true);
}
}
Text Area
• A TextArea class is used for displaying multiple line text. It is a multiline
region that displays text. It allows the editing of multiple line text. It inherits
TextComponent class.
• example of Creating TextArea:
TextArea ta = new TextArea("Type Here", 5, 50, 3);
import java.awt.*;
public class TextAreaDemo
{
TextAreaDemo()
{
Frame fr= new Frame();
TextArea ta = new TextArea("Type Here");ta.setBounds
(30, 40, 100, 100);
fr.add(ta);
fr.setSize(250, 250);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
TextAreaDemo td=new TextAreaDemo();
}
}
Check Box
• The Checkbox class is used to create a checkbox. It is used to turn an option
on (true) or off (false). When the checkbox is checked then its state is "on"
(true) else it is "off" (false).
• It is used when we want to select only one option Le true or false.)
• Example of Creating Checkbox:
Checkbox cb= new Checkbox (Label);
//Program we are creating checkbox that are used to get user input.
If checkbox is checked it returns true else returns false.
import java.awt.*;
public class CheckboxDemo
{
CheckboxDemo ()
{
Frame checkB_f = new Frame ("Checkbox Demo");
Checkbox ckbox1 = new Checkbox ("Yes", true);
ckbox1.setBounds(100, 180, 60, 60);
Checkbox ckbox2 = new Checkbox("No");
ckbox2.setBounds (100, 150, 60, 60);
checkB_f.add(ckbox1);
checkB_f.add(ckbox2);
checkB_f.setSize (300, 300);
checkB_f.setLayout (null);
checkB_f.setVisible (true);
}
public static void main(String args[])
{
CheckboxDemo cd= new CheckboxDemo();
}
}
Radio Button
• A CheckboxGroup Class is used to group a set of Checkboxes. When
Checkboxes are grouped then only one box can be checked at a time. 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.
• Example of Creating Radio Button:
CheckboxGroup cbg= new CheckboxGroup ();
Checkbox rb = new Checkbox (Label, cbg, boolean);
import java.awt.*;
public class CheckboxGroupDemo
{
CheckboxGroupDemo ()
{
Frame fr= new Frame("CheckboxGroup Demo");
CheckboxGroup cbg= new CheckboxGroup();
Checkbox ckBox1 = new Checkbox("Java", cbg, true);
ckBox1.setBounds (100, 100, 50, 50);
Checkbox ckBox2 = new Checkbox("C", cbg,
false);ckBox2.setBounds (100, 150, 50, 50);
fr.add(ckBox1);
fr.add(ckBox2);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
CheckboxGroupDemo cg=new CheckboxGroupDemo();
}
}
Output
Combo Box
• A drop down box or a combo box contains a list of items (strings). When a
user clicks on a drop down box, it pops up a list of items from which user can
select a single item. When a user selects a particular item from the drop-down
then it is shown on the top of the menu.
• Example of Creating Choice:
Choice ch = new Choice();
import java.awt.*;
public class ChoiceDemo
{
ChoiceDemo()
{
Frame fr = new Frame();
Choice ch= new Choice();
ch.setBounds (80, 80, 100, 100);
ch.add("BCA");
ch.add("BCom");
ch.add("BBA");ch.add("BA");
ch.add("BHM");
ch.add("BSc");
fr.add(ch);
fr.setSize(300, 100);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
ChoiceDemo cd=new ChoiceDemo();
}
}
Lists
• A List Class is used to represent a list of items together. One or more than one
item can be selected from the list. More than one items in the list box are
visible to the user.
• Example of Creating List:
List l=new List(int, Boolean);
import java.awt.*;
public class ListDemo;
{
ListDemo()
{
Frame fr new Frame("List Demo");
List 1st =new List (6, true);
1st.setBounds(80, 80, 100, 100);
1st.add("C");
1st.add("C++");
1st.add("Java");
1st.add("Python");
1st.add("C#");
1st.add("PHP");
fr.add(1st);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
ListDemo ld=new ListDemo();
}
}
Scroll Bars
• The Scrollbar is a GUI component that allows us to see an invisible number of
rows and columns. The object of the Scrollbar class can add a horizontal
scrollbar and a vertical Scrollbar.
• A Scrollbar can be added to a top-level container like Frame or a component
like Panel. It is used to create a horizontal and vertical Scrollbar.
• Example of Creating Scrollbar:
Scrollbar sb = new Scrollbar();
import java.awt.*;
public class ScrollbarExample
{
ScrollbarExample()
{
Frame f = new Frame("Scrollbar Example");
Scrollbar s= new Scrollbar();
s.setBounds(100, 100, 50, 100);
f.add(s);
f.setSize(300, 300);
f.setLayout(null);f.setVisible(true);
}
public static void main(String args
{
ScrollbarExample se= new ScrollbarExample();
}
}
Menus
• The MenuItem class adds a simple labeled menu item on menu. The items
used in a menu must belong to the MenuItem or any of its subclass. The Menu
class is a pull down menu. Component which is displayed on the menu bar. It
inherits the MenuItem class.
• The following statements create a menu bar and add it to the top of the frame.
Menubar menuBar = new MenuBar();
setMenubar (menuBar);
These statements are part of the class that extends Frame.
import java.awt.*;
public class MenuDemo
{
MenuDemo()
{
Frame fr= new Frame("Menu Demo");
MenuBar mb= new MenuBar();
Menu fileMenu = new Menu("File");
Menu editMenu = new Menu("Edit");
Menu viewMenu = new Menu(“view”);
mb.add(fileMenu);
mb.add(editMenu);
mb.add(viewMenu);
MenuItem a1= new MenuItem("New");
MenuItem a2 = new MenuItem("Open");
MenuItem a3 = new MenuItem("Save");
MenuItem b1= new MenuItem("Copy");
MenuItem b2 = new MenuItem("Find");
MenuItem c1 = new MenuItem("Show");
fileMenu.add(a1);
fileMenu.add(a2);
fileMenu.add(a3);
editMenu.add(b1);
editMenu.add(b2);
viewMenu.add(c1);fr.setMenuBar (mb);
fr.setSize(300, 300);
fr.setLayout(null);
fr.setVisible(true);
}
public static void main(String args[])
{
MenuDemo md= new MenuDemo();
}
}
Dialog Box
• In Java, AWT contains a Dialog. It is a type of window which is having a border
and a title. But it does not have any maximize and minimize button.
• There are two kinds of Dialog Window.
Modal Dialog window: When a modal dialog window is active, all the user
inputs are directed to it and all the other parts of application are
inaccessible until this Modal dialog is closed.
Modeless Dialog window: When a modeless dialog window is active, the
other parts of application are still accessible as normal and inputs can be
directed to them, without needing to close this modeless dialog window.
//Program in this example, we are creating a dialogue box. The dialogue
box is used to provide information to the user.
import java.awt.*;
import java.awt.event.*;
public class DialogDemo extends WindowAdapter implements
ActionListener
{
Frame frame;
Label label1;
TextField field1;
Button button1, button2, button3;
Dialog d1, d2, d3;
DialogDemo()
{
frame = new Frame("Frame");
button1 = new Button("Open Modal Dialog");
label1 =new Label("Click on the button to open a Modal
Dialog");
frame.add(label1);
frame.add(button1);
button1.addActionListener(this);
frame.pack();
frame.setLayout(new FlowLayout());
frame.setSize(350,350);
frame.setVisible(true);
}
public void actionPerformed (ActionEvent ae)
{
if (ae.getActionCommand().equals("Open Modal Dialog"))
{
d1 = new Dialog (frame, "Modal Dialog", true);
Label label = new Label("You must close this
dialog window to use Frame window", Label.CENTER);
d1.add(label);
d1.addWindowListener(this);
d1.pack();
d1.setLocationRelativeTo(frame);
d1.setLocation(new Point (100, 100));
d1.setSize(400, 200);
d1.setVisible(true);
}
public void windowClosing (WindowEvent we)
{
d1.setVisible(false);
}
public static void main(String args[])
{
DialogDemo d= new DialogDemo();
}
}
APPLET PROGRAMMING
APPLET
It is a small that is embedded with html program, which is accessed
and transported over the internet, automatically installed into client
machines and run as apart of webpage.
Syntax:
public void init ()
{
………………
………………
}
2. start() method
After init() it should be declared start () method because this method
is automatically called to begin the execution of the applet like any
calculation and processing of the data should be done in this method.
Syntax:
public void start()
{
………………
………………
}
3. stop() method
This method is called by the browser when an applet is to be stopped and
also implement the method to stop any operations which started in stop().
Syntax:
public void stop ()
{
………………
………………
}
4. destroy() method
This method is called when an applet is being terminated from memory. The
stop() method will always call before destroy(). It is completely dead
whatever it is started of the applet and takes care of garbage and memory
allocation.
Syntax:
public void destroy()
{
………………
………………
}
5. paint() method
It is not a part of applet life cycle but it is used to display the output
operations on the screen and also is the graphics tools such as buttons,
textboxes, text shapes and images etc.
Syntax:
public void paint(Graphics g)
{
………………
………………
}
import java.applet.Applet;
import java.awt.Graphics;
public class Myapplet extends Applet
{
public void paint(Graphics g)
{
g. drawString("Welcome to Applet programming",20,20);
}
}
<html>
<head>
<title>Applet programming</title>
<body>
<applet code="Myapplet.class" width=200 height=200>
</applet>
</body
</head>
</html>
Applet Tag
Applet is an html tag. This tag is helpful for the applet programs embedded with
html programming.
Syntax:
<applet code =”Filename.class ALT =” alternate text” WIDTH =”
pixels” HEIGHT =”pixels” ALIGN =”alignment” VSPACE =”pixels”
HSPACE =”pixels”>
Example for Applet Tag
<html>
<head>
<title>Applet programming</title>
<body>
<applet code="Myfont.class" width=200 height=200>
</applet>
</body
</head>
</html>
Update() method
This method is called when applet has requested that a portion of its window
the redrawn and after updating call inside the paint of method.
Example:
public void update()
{
//statements
}
public void paint(Graphics g)
{
Update(g);
}
repaint() method
An Applet writes to its window only when its update() or paint()
method.
Whenever our applet needs to applet the information displayed in its window,
it simply calls repaint().
Advantages of Applets
• Applets are cross platform and run on windows Mac OS, Linux, operating
system.
• Applets can work all the version of java plug-in.
• Applets run in a Sandbox, So the user does not need the trust the code.
• Applet are supported by most web browsers.
• Quick loading in the web browsers.
Disadvantages
• Java plug-in is required compulsory.
• Difficult to design.
• Java virtual machine is required compulsory.
Introduction to swing
What is swing in java?
• Java Swing is part of java Foundation Classes. Swing is the graphical user
interface toolkit that is used for developing windows based java applications
or programs.
• Java Swing is built on top of an abstract windowing toolkit API purely written
in java programming language.
• Java Swing provides lightweight and platform- independent components,
making it suitable and efficient in designing and developing desktop based
GUI applications.
• To use the Swing in java, javax.swing package needs to be used or import. It
is also known as java Swing.
Features of java Swing
1. Platform independent
It is platform-independent; the swing components that are used to build the
program are not platform-specific it can be used on any platform and
anywhere.
2. Lightweight
Swing components are lightweight as theyare written entirely in java and do
not depend on native peers (platform specific code resources).
4. MVC
They mainly follow the concept of MVC that is the Model View Controller.
With the help of this, we can do the changes in one component without
impacting or touching other components.
5. Rich Controls
Swing provides a rich set of advanced controls like Tree, TabbedPane, Slider,
Color picker, and table controls.
AWT VS SWING
AWT SWING
AWT components are heavy weight Swing components are light weight
components components
AWT doesn’t support pluggable look Swing supports pluggable look and
and feel feel
AWT programs are not portable Swing programs are portable
AWT is old frame work for creating Swing is new framework for creating
GUIs GUIs
AWT components require java.awt Swing components require
package java.swing package
AWT supports limited number of Swing provides advanced GUI
GUI controls controls like j table, JTabbedPane etc
More code is needed to implement Less code is needed to implement
AWT controls functionally swing controls functionally
AWT doesn’t follow MVC Swing follows MVC
COMPONENTS
In general, Swing components are derived from the JComponent
class.JComponent provides the functionality that is common to all
components. For example, JComponent supports the pluggable look and feel.
JComponent inherits the AWT classes Container and Component. Thus, a Swing
component is built on and compatible with an AWT component. All of Swing's
components are represented by classes defined within the package
javax.swing. Notice that all component classes begin with the letter ‘J’. For
example, the class for a label is JLabel; the class for a push button is JButton;
and the class for a scroll bar is JScrollBar.
Containers
Swing defines two types of containers. The first are top-level containers: JFrame,
JApple, JWindow, and JDialog.These containers do not inherit Component. They
do, however, inherit the AWT classes Component and Container. Unlike Swing's
other components, which are lightweight, the top level containers are
heavyweight. This makes the top-level containers a special case in the Swing
component library.
Swing Examples:
JFrame
Frame frame new JFrame("Frame Example");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame setSize(400, 400);
frame.setVisible(true);
JLabel
JFrame f = new JFrame("Java Swing Label"); JLabel
la1,1a2;lal= new JLabel("Java Programming");
La1.setBounds(70, 70, 120, 50);
La2=new JLabel("Java Swing");
la2.setBounds(70,120, 120, 50);
f.add(lal);
f.add(la2);
f.setSize(700, 700);
f.setLayout(null);f.setvisible(true);
JButton
JFrame f=new JFrame("Creating Java Button");
JButton bt=new JButton("Sign in");
bt.setBounds (70,120,115,50);
f.add(bt);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
JTextField
JFrame f= new JFrame("Java Swing TextField");
JTextField tf1,tf2;
tfl=new JTextField("Java Programing");
tf1.setBounds (50, 100, 200,30);
tf2=new JTextField("Java Swing GUI");
tf2.setBounds(50 150, 200, 30);
f.add(tf1);
f.add(tf2);
f.setSize(700,700);
f.setLayout(null);
f.setVisible(true);
JTextArea
JFrame f= new JFrame(); JTextArea ta=new JTextArea("Java");
ta.setBounds(10,30, 200,200);
f.add(ta);
f.setSize(300, 300);
f.setLayout(null);
f.setVisible(true);
JCheckBox
JFrame f= new JFrame(“Java Swing CheckBox");
JCheckBox cb1 = new JCheckBox("C");
cb1.setBounds(100, 100, 50,50);
JCheckBox cb2 = new JCheckBox("Java", true);
cb2.setBounds(120,170, 70,70);
f.add(cb1);
f.add(cb2);
f.setSize(500, 500);
f.setLayout(null);
f.setVisible(true);
JRadioButton
Frame f=new JFrame("RadiButton Example");
JRadioButton rb1=new JRadioButton("1) Male");
JRadioButton rb2=new JRadioButton("2) Female");
rb1.setBounds(80,50,90,30);
rb2.setBounds (80,188,90,30);
ButtonGroup btg-new ButtonGroup();
btg.add(rb1);
btg.add(rb2);
f.add(rb1);
f.add(rb2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
EXCEPTION HANDLING
EXCEPTION
An exception is an error that occurs at run time.
Types of error in Java
1. Compile error
2. Runtime error.1.Compile error
1. Compile error
The compile error is nothing but syntax error or any general syntax mistake,
program fails during compile time. For example, semicolon missing, usage of
duplicate variables and so on.
Example:
Class test
{
Public static void main ()
{
System.out.println ("WELOME");
}
}
2. Runtime error
Runtime error is an error that occurs during at runtime.
Example: Division by Zero.
//Programming Example
Class Test
{
Public static void main (String args [])
{
Int I, j, k;
I=100;
J=0;
K=I/j;
System.out.println ("The value of k=" +k);
}
}
Definition of Exception Handling
Exception means run time error this error can handle by particular type of an
error and should define the error in a different fission of runtime error message
created by java.long package. This process is known as exception handling.
Try: This method is used to execute the block of statements for throwing an
exception using the keyword try.
Throw: Throwing the exception type from catch block to try block.
----------------
----------------
----------------
Catch (Exception typeN en)
{
/*typeN exception*/
}
Finally Keyword
The final keyword is used to create the block of code that follows a try block.
General Syntax:
Try
{
/*Exception statements*/
}
----------------
----------------
----------------
Catch (Exception typeN en)
{
/*typeN exception*/
}
Finally ()
{
/*final statements*/
}
Import java.io. *;
Public class fileReadBytes
{
Public static void main (String args [])
{
fileInputStream fos=null;
try
{
fos = new FileInputStream(“File1.txt”);
int size=fos. available ();
byte ba [] =new byte[size];fos. read(ba);
String data=new String(ba);
System.out.println(“the file contents are:” =+
data);
}
Catch (FileNotFoundException e)
{
System.out.println(“FileNotFoundExceptionoccurred”);
}
Catch (EOFException e)
{
System.out.println(“EOFException occurred”);
}
Catch (IOException e)
{
System.out.println(“IOException occurred”);
}
Finally
{
Try
{
fos. Close ();
}
Catch (Exception e)
{
System.out.println(“Exception while closing
file stream”);
}
}
}
}
The Following program illustrates once it gets an exception in try block, it will
not execute the rest of the code in the try block. It jumps to the catch block and
finally block.
class Demo
{
public static void main (String args[])
{
Demo t=new Demo ();
try
{
System.out.println(“one”);
t. method1();
System.out.println(“Two”);
}
catch (Arithmetic Exception e)
{
System.out.println(“Three”);
}
Finally
{
System.out.println(“Four”);
}
}
Void method1()
{
int a=o;
int b=100/a;
}
}
I/O STREAMS
a) Input Stream
Input stream is an abstract class that provides the frame work from which all
other input streams are derived. In the below diagram, all the input streams
like FileInputStream , PipedInputStream are derived from InputStream class.
We cannot create an instance of input stream class as it is abstract class.
Whenever we want to read data in byte format then we use the Input Stream
classes.
The InputStream class contains lots of methods for reading bytes, closing
streams, skipping part of data in the stream, finding the number of bytes
present in the input data, etc..,
The important methods of Input stream classes are shown below:-
METHODS DESCRIPTION
Int available() Returns the number of bytes of input currently
available for reading.
Void close() Close the input source. Further read attempts
will generate an IO Exception.
Void mark(int numBytes) Places a mark at a current point in the input
stream that will remail valid until numBytes
bytes are read.
Boolean markSupported() Return true if mark()/reset() are supported by
the invoking stream.
Int read() Return an integer representation of the next
available byte of input 1 is returned when the end
of the file is encountered.
Int read(byte buffer[]) Attempts to read up to buffer length bytes into
buffer and returns the actual number of bytes
that were successfully read. -1 is returned when
the end of the file is encountered.
Int read(byte buffer[],int Attempts to read up to numBytes bytes into
offset,int numBytes) buffer starting at buffer(offset),reading the
number of
bytes successfully read, -1 is returned when the
end of the files is encountered.
Void reset() Resets the input pointer to the previously set
mark.
Long skip(long Ignores (that is, skips) numBytes bytes of
numBytes) input,returning the number of bytes actually
ignored.
b) Output Stream
OutputStream is an abstract class that provides the framework from which all
other output streams are derived. In the below diagram,all the output streams
like FileOutputStream, PipedOutputStream are derived from OutputStream
class.
METHODS DESCRIPTION
Void close() Closes the output stream, Further write
attempts will generate an IOException.
Void flush() Finalizes the output state so that any buffers
are cleared. That is, it flushes the output
buffers.
Void write(int b) Writes a single bit to an output stream. Note
that the parameter is an int, which allows you
to call write with expressions without having
to cast them back to byte.
Void write(byte buffer[]) Writes a complete array of bytes to an output
stream.
Void write(byte buffer[],int Writes a subrange of numBytes bytes from
offset,int numBytes) the array buffer, beginning at buffer [offset].
c) Character Stream
Reader is an abstract class that provides the framework from which all other
reader streams are derived. In the below diagram all, all the reader streams like
BufferedReader, CharArrayReader are derived from Reader class.
Writer is an abstract class that provides the frame work from which all other
writer streams are derived. In the below diagram all the writer streams like
BufferedWriter, CharArrayWriter are derived from Writer class.
Input/Output Exceptions
Exceptions in java are the way of indicating the occurrence of abnormal
condition in the program. Actually these are objects that are thrown when
program encounters any problem executing the program further.
EXCEPTION MEANING
EOF Exception Signals that an end of the file reached, when we are
trying to read the file, if the position of the file is at
the end, we may get this exception.
File Not Found Exception If we are trying to access the file, and the file does
not exist, we will get this exception.
Interrupted IO Exception It warns that an I/o operation has been interrupted.
IO Exception Some sort of I/o exception has occurred. It is very
generic exception of I/o.
When we write code related to I/O operations, we should place the
statements in try block and handle the exceptions in catch block as shown
below.
Try
{
Statements related to I/o operations
}
Catch (IO Exception e)
{
Handle the exception
}
Creating Files
The following table explains the different ways of creating and reading files.
CONSTRUCTOR EXAMPLE
A file is opened for input by creating FileInputStream fis;
a FileInputStream Object. Try
FileInputStream(String ilename) {
throws FileNotFoundException fis=new
FileInputStream(“myFile.dat”);
}
catch(IOException)
{
}
FileInputStream(File f)throws File f=new File(“myFile.dat”);
FileNotFoundException FileInputStream fis;
Try
{
Fis=new FileInputStream(f);
}
catch(IOException)
{
}
To open a file for output,create a FileOutputStream fos;
FileOutputStream object. Here are Try
its two most commonly used {
constructors. Fos=new FileOutputStream(f);
FileOutputStream(StringfileName) }
Throws FileNotFoundException Catch(IOException)
{
}
FileOutputStream(File file)throws File f=new File(“myFile.dat”);
FileNotFoundException FileOutputStream fos;
Try
{
Fos=new FileOutputStream(f);
}
Catch(IOException)
{
}
Reading/Writing Bytes
1. Write a program to read data from the console and write this data
in a file named file1.txt
import java.io.*;
public class FileWriteBytes
{
public static void main(String args[])
{
Try
{
BufferedReader br=new BufferedReader(new
InputStreamReader(System.in));
System.out.println(“Enter the Data:”);
String s1=br.readLine();
FileOutputStream fos=new
FileOutputStream(“File1.txt”,true);
Byte ba[]=s1.getbytes();
Fos.write(ba);
Fos.close();
}
Catch(IOException e)
{
System.out.println(“Exception Occurred”);
}
}
}
2. Write a program to read data from the file File1.txt and write this
data to console.
import java.io.FileInputStream;
import java.io.IOException;
public class FileReadBytes
{
public static void main(String args[])
{
try
{
FileInputStream fos=new
FileInputStream(“File1.txt”);
int size=fos.available();
byte ba[]=new byte[size];
fos.read(ba);
String data=new String(ba);
System.out.println(“The file contents are: “+data)
fos.close();
}
catch(IOException e)
{
System.out.println(“Exception occurred”);
}
}
}