0% found this document useful (0 votes)
16 views72 pages

Oops U5

This document provides an overview of event-driven programming in Java, focusing on graphics programming using the Abstract Window Toolkit (AWT) and applets. It covers the class hierarchy of AWT components, methods for drawing shapes, and the lifecycle of applets, as well as event handling and the use of Java Swing for building GUI applications. Key concepts include graphics methods, color management, font usage, and image handling within Java applets.
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)
16 views72 pages

Oops U5

This document provides an overview of event-driven programming in Java, focusing on graphics programming using the Abstract Window Toolkit (AWT) and applets. It covers the class hierarchy of AWT components, methods for drawing shapes, and the lifecycle of applets, as well as event handling and the use of Java Swing for building GUI applications. Key concepts include graphics methods, color management, font usage, and image handling within Java applets.
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/ 72

UNIT-V

EVENT DRIVEN PROGRAMMING


Graphics programming
• Graphics is one of the most important features of Java.
• Java applets can be written to draw lines, arcs, figures, images and text
in different fonts and styles.
• Different colors can also be incorporated in display.
Java AWT
• The Abstract Window Toolkit (AWT) is Java’s original platform-
independent windowing, graphics, and user-interface widget toolkit.
• The AWT classes are contained in the java.awt package.
• It contains all of the classes for creating user interfaces and for
painting graphics and images.
Java AWT Class Hierarchy
Java AWT Components
Java AWT Components
Java AWT Class Hierarchy
Component
• A component is an object having a graphical representation that can be
displayed on the screen and that can interact with the user.
Container
• The Container class is the subclass of Component. The container object is
a component that can contain other AWT components. It is responsible
for laying out any components that it contains.
Window
• The class Window is a top level window with no border and no menubar.
Java AWT Class Hierarchy
Panel
• The class Panel is the simplest container class. It provides space in which
an application can attach any other component, including other panels.
Frame
• A Frame is a top-level window with a title and a border.
Dialog
• A Dialog is a top-level window with a title and a border that is typically
used to take some form of input from the user.
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.
Methods of Applet
• public void init(): It is used to initialized the Applet. It is invoked
only once.
• public void start(): It is invoked after the init() method or browser is
maximized. It is used to start the Applet.
• public void stop(): It is used to stop the Applet. It is invoked when
Applet is stop or browser is minimized.
• public void destroy(): It is used to destroy the Applet. It is invoked
only once.
Applet Demo
import java.applet.*; >javac First.java
import java.awt.*; >appletviewer First.java
public class First extends Applet
{
public void paint(Graphics g)
{
g.drawString("welcome to applet",150,150);
}
}
/*<applet code=“First.class" width="300" height="300">
</applet>
*/
Applet Demo
The java.awt.Component class provides 1 life cycle method of applet.

• public void paint(Graphics g): is used to paint the Applet. It provides


Graphics class object that can be used for drawing oval, rectangle, arc
etc.
Write a Java program that implements a multi-threaded application
that has four threads. First thread generates a random integer and if
the value is divisible by 4, second thread computes the square of the
number and prints. If the value is divisible by 3, the third thread will
print the value of cube of the number. If the value is divisible by both,
the fourth thread will print the value it is.
Graphics methods
Method Description
abstract void drawLine(int x1, int y1, Draws a line, using the current color,
int x2, int y2) between the points (x1, y1) and (x2, y2)
import java.applet.Applet;
import java.awt.*;
public class LineDemo extends Applet
{
public void paint(Graphics g)
{
g.drawLine(120,120,200,300);
}
}
/*<applet code="LineDemo.class" width="300"
height="300"></applet>
*/
Graphics methods
Method Description
void drawRect(int x, int y, int width, draws a rectangle with the specified
int height) width and height
import java.applet.Applet;
import java.awt.*;
public class RectDemo extends Applet
{
public void paint(Graphics g)
{
g.drawRect(100,60,160,50);
}
}
/*<applet code="RectDemo.class" width="300"
height="300">
</applet>*/
Graphics methods
Method Description
abstract void drawRoundRect(int x, int y, int Draws an outlined round-
width, int height, int arcWidth, int arcHeight) cornered rectangle.
import java.applet.Applet;
import java.awt.*;
public class RRectDemo extends Applet
{
public void paint(Graphics g)
{
g.drawRoundRect(190, 10, 60, 50, 15, 15);
}
}
/*<applet code="RRectDemo.class" width="300"
height="300"></applet>*/
Graphics methods
Method Description
abstract void fillRect(int x, int y, int fill rectangle with the default color and
width, int height) specified width and height.
import java.applet.Applet;
import java.awt.*;
public class FRectDemo extends Applet
{
public void paint(Graphics g)
{
g.fillRect(170,100,60,50);
}
}
/*
<applet code="FRectDemo.class" width="300"
height="300"></applet>*/
Graphics methods
Method Description
abstract void drawPolygon(int[] Draws a closed polygon defined by
xPoints, int[] yPoints, int nPoints) arrays of x and y coordinates.
import java.applet.Applet;
import java.awt.*;
public class PolyDemo extends Applet
{
public void paint(Graphics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
g.drawPolygon(xpoints, ypoints, 5);
}
}
/*<applet code="PolyDemo.class" width="300"
height="300"></applet>*/
Graphics methods
Method Description
abstract void fillPolygon(int[] xPoints, Fills a closed polygon defined by
int[] yPoints, int nPoints) arrays of x and y coordinates.
import java.applet.Applet;
import java.awt.*;
public class PolyDemo extends Applet
{
public void paint(Graphics g)
{
int xpoints[] = {30, 200, 30, 200, 30};
int ypoints[] = {30, 30, 200, 200, 30};
g.fillPolygon(xpoints, ypoints, 5);
}
}
/*<applet code=“PolyDemo.class" width="300"
height="300"></applet>*/
Graphics methods
Method Description
abstract void drawOval(int x, int y, int draw oval with the specified width and
width, int height) height.
import java.applet.Applet;
import java.awt.*;
public class OvalDemo extends Applet
{
public void paint(Graphics g)
{
g.drawOval(70,200,50,50);
}
}
/*
<applet code="OvalDemo.class" width="300"
height="300"></applet>
*/
Graphics methods
Method Description
abstract void fillOval(int x, int y, int fill oval with the default color and
width, int height) specified width and height.
import java.applet.Applet;
import java.awt.*;
public class OvalDemo extends Applet
{
public void paint(Graphics g)
{
g.fillOval(70,200,50,50);
}
}
/*
<applet code="OvalDemo.class" width="300"
height="300">
</applet>*/
Graphics methods
Method Description
abstract void drawArc(int x, int y, int width, draw a circular or elliptical arc.
int height, int startAngle, int arc Angle)
import java.applet.Applet;
import java.awt.*;
public class ArcDemo extends Applet
{
public void paint(Graphics g)
{
g.drawArc(90,150,70,70,0,75);
}
}
/*
<applet code="ArcDemo.class" width="300"
height="300"></applet>
*/
Graphics methods
Method Description
abstract void fillArc(int x, int y, int width, fill a circular or elliptical arc.
int height, int startAngle, int arcAngle)
import java.applet.Applet;
import java.awt.*;
public class ArcDemo extends Applet
{
public void paint(Graphics g)
{
g.fillArc(90,150,70,70,0,75);
}
}
/*
<applet code="ArcDemo.class" width="300"
height="300"></applet>
*/
Graphics methods
Method Description
abstract boolean drawImage(Image img, int draw the specified image.
x, int y, ImageObserver observer)

abstract void drawArc(int x, int y, int width, draw a circular or elliptical arc.
int height, int startAngle, int arc Angle)
abstract void fillArc(int x, int y, int width, fill a circular or elliptical arc.
int height, int startAngle, int arcAngle)
Frame
• We can generate a window by creating an instance of Frame.
• The created frame can be made visible by calling setVisible( ).
• When created, the window is given a default height and width. The
size of the window can be changed explicitly by calling the setSize( )
method.
• A label can be added to the current frame by creating an Label
instance and calling the add() method.
Program
import java.awt.*;
public class AwtFrame
{
public static void main(String[] args)
{
Frame frm = new Frame("Java AWT Frame");
Label lbl = new Label("Welcome",Label.CENTER);
frm.add(lbl);
frm.setSize(400,400);
frm.setVisible(true);
}
}
Creating an Frame Window in an Applet
import java.applet.*; public class AFrame extends Applet
import java.awt.*; {
class SFrame extends Frame Frame f;
{ public void init()
SFrame(String title) {
{ f = new SFrame("Frame Window");
super(title); f.setSize(150, 150);
} f.setVisible(true);
public void paint(Graphics g) }
{ public void start()
g.drawString(“Frame window", 10, 40); {
} f.setVisible(true);
} }
Creating an Frame Window in an Applet
public void stop()
{
f.setVisible(false);
}
public void paint(Graphics g)
{
g.drawString(“Applet window", 15, 30);
}
}
/*
<applet code="AFrame.class" width="400" height="300">
</applet>
*/
Working with 2D shapes
• Java supports 2-dimensional shapes, text and images using methods
available in Graphics2D class.
• The Graphics2D class extends the Graphics class to provide more
sophisticated control over geometry, coordinate transformations, color
management, and text layout.
Working with 2D shapes
import java.awt.*; g2d.drawRect(75,75,300,200);
import java.applet.*; Font ex=new Font("TimesRoman",Font.PLAIN,40);
/* g2d.setFont(exFont);
<applet code="ShapesDemo" g2d.setColor(Color.black);
width=350 height=300> g2d.drawString("Graphics2D Example",120,100);
</applet>*/ g2d.setColor(Color.green);
public class SDemo extends Applet g2d.drawLine(100,100,300,200);
{ g2d.fillOval(150,150,100,200);
public void paint(Graphics g) }
{ }
Graphics2D g2d = (Graphics2D)g;
g2d.setColor(Color.blue);
Working with 2D shapes
Colors in Java
• The Color class states colors in the default RGB color space or colors
in arbitrary color spaces identified by a ColorSpace.
• Color(float r, float g, float b) – create color with specified red, green,
and blue values in the range (0.0 - 1.0)
• Color(int r, int g, int b)- create color with the specified red, green, and
blue values in the range (0 - 255).
Colors in Java
• The current graphics color can be changed using setColor() method defined in
Graphics class.
void setColor(Color newColor) // newColor indicates new drawing color
• The current color detail can be obtained using getColor() method. Its syntax
is.
Color getColor()
Colors in Java
import java.awt.*; g.setColor(Color.red);
import java.applet.*; g.drawRect(50, 100, 150, 100);
/* Color clr = new Color(200, 100, 150);
<applet code="CDemo" g.setColor(clr);
width=350 height=300> g.fillRect(220,100, 150, 100);
</applet> }
*/ }
public class CDemo extends Applet
{
public void paint(Graphics g)
{
Colors in Java
Fonts in Java
• The Font class states fonts, which
are used to render text in a visible
way.
• Font class constructor
• Font(Font font)
• Font(String name, int style, int
size)
Images in Java
• Image control is superclass for all image classes representing graphical
images.
• Image class constructor
• Image() // create an Image object
Images in Java
• getImage() method that returns the object of Image. Its syntax is as
follows.
public Image getImage(URL u, String image){}
• getDocumentBase() method returns the URL of the document in which
applet is embedded.
public URL getDocumentBase(){} Uniform Resource Locator
• URL getCodeBase() method returns the base URL.
public URL getCodeBase()
Images in Java
import java.applet.Applet;
import java.awt.*;
import java.net.URL;
/* <applet code ="IDemo.class" width=300
height=200> </applet> */
public class IDemo extends Applet
{
Image img;
public void paint(Graphics g)
{
URL url1 = getCodeBase();
img = getImage(url1,"tec.jpg");
g.drawImage(img, 60, 120, this);
}
}
Event Handling
• Any change in the state of any object is called event. For Example:
Pressing a button, entering a character in Textbox, Clicking or
dragging a mouse, etc. The three main components in event handling
are:
• Events: An event is a change in state of an object. For example,
mouseClicked, mousePressed.
• Events Source: Event source is an object that generates an event.
Example: a button, frame, textfield.
• Listeners: A listener is an object that listens to the event. For example
MouseListener handles all MouseEvent.
Event Handling
Event classes Generated when Listener Interfaces
ActionEvent button is pressed, menu-item is selected, list- Action Listener
item is double clicked
MouseEvent mouse is dragged, moved, clicked or released Mouse Listener, Mouse
and also when it enters or exit a component Motion Listener
MouseWheelEvent mouse wheel is moved Mouse Wheel Listener
KeyEvent input is received from keyboard Key Listener
ItemEvent check-box or list item is clicked Item Listener
TextEvent value of textarea or textfield is changed Text Listener
AdjustmentEvent scroll bar is manipulated Adjustment Listener
WindowEvent window is activated, deactivated, deiconified, Window Listener
iconified, opened or closed
Adapter Classes
• An adapter class provides the default
implementation of all methods in an
event listener interface.
• Adapter classes are very useful when
you want to process only few of the
events that are handled by a
particular event listener interface.
Java Swing
• Swing in Java is a lightweight GUI toolkit which has a wide variety of
widgets for building optimized window based applications.
• It is a part of the JFC( Java Foundation Classes).
• It is build on top of the AWT API and entirely written in java.
• It is platform independent unlike AWT and has lightweight
components.
Java Swing
Layout Management
• 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.
• java.awt.BorderLayout
• java.awt.FlowLayout
• java.awt.GridLayout
• java.awt.CardLayout
• java.awt.GridBagLayout
• javax.swing.BoxLayout
• javax.swing.GroupLayout
• javax.swing.ScrollPaneLayout
• javax.swing.SpringLayout
BorderLayout
• The BorderLayout is used to arrange the components in five regions:
north, south, east, west and center. It is the default layout of frame or
window. The BorderLayout provides five constants for each region:
• public static final int NORTH
• public static final int SOUTH
• public static final int EAST
• public static final int WEST
• public static final int CENTER
BorderLayout
• BorderLayout(): creates a border layout but with no gaps between the
components.
• JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
GridLayout
• The GridLayout is used to arrange the components in rectangular grid.
One component is displayed in each rectangle.
• GridLayout(): creates a grid layout with one column per component in
a row.
• 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 alongwith given horizontal
and vertical gaps.
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.
• The fields are
• public static final int LEFT
• public static final int RIGHT
• public static final int CENTER
• public static final int LEADING
• public static final int TRAILING
FlowLayout
• FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
• FlowLayout(int align): creates a flow layout with the given alignment
and a default 5 unit horizontal and vertical gap.
• FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.
BoxLayout
• The BoxLayout is used to arrange the components either vertically or
horizontally.
• The fields are
• public static final int X_AXIS
• public static final int Y_AXIS
• public static final int LINE_AXIS
• public static final int PAGE_AXIS
• BoxLayout(Container c, int axis): creates a box layout that arranges
the components with the given axis.
CardLayout
• The CardLayout class manages the components in such a manner that
only one component is visible at a time. It treats each component as a
card that is why it is known as CardLayout.
• CardLayout(): creates a card layout with zero horizontal and vertical
gap.
• CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
GridBagLayout
• The Java GridBagLayout class is used to align components vertically,
horizontally or along their baseline.
• The components may not be of same size.
• Each GridBagLayout object maintains a dynamic, rectangular grid of
cells. Each component occupies one or more cells known as its display
area.
• The GridBagLayout manages each component's minimum and
preferred sizes in order to determine component's size.
GroupLayout
• GroupLayout groups its components and places them in a Container
hierarchically. The grouping is done by instances of the Group class.
• GroupLayout(Container host) It creates a GroupLayout for the
specified Container.
SpringLayout
• A SpringLayout arranges the children of its associated container
according to a set of constraints.
• Constraints are nothing but horizontal and vertical distance between
two component edges.
SpringLayout
Field Description
BASELINE It specifies the baseline of a component.
EAST It specifies the right edge of a component's bounding
rectangle.
HEIGHT It specifies the height of a component's bounding rectangle.
HORIZONTAL_ It specifies the horizontal center of a component's bounding
CENTER rectangle.
NORTH It specifies the top edge of a component's bounding
rectangle.
SpringLayout
Field Description
SOUTH It specifies the bottom edge of a component's bounding
rectangle.
VERTICAL_CE It specifies the vertical center of a component's bounding
NTER rectangle.
WEST It specifies the left edge of a component's bounding
rectangle.
WIDTH It specifies the width of a component's bounding rectangle.
ScrollPaneLayout
• JScrollPaneLayout is responsible for nine components: a viewport,
two scrollbars, a row header, a column header, and four "corner"
components.
• ScrollPaneLayout.UIResource-It is UI resource version of
ScrollPaneLayout.
Java Swing - TextField
• A JTextField object is a text component that allows for the editing of a
single line of text.
Constructor Description
JTextField() Creates a new TextField
JTextField(String text) Creates a new TextField initialized with the
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
Java Swing - TextArea
• The object of a JTextArea class is a multi line region that displays text.
Constructor Description
JTextArea() Creates a text area that displays no text initially.
JTextArea(String s) Creates a text area that displays specified text
initially.
JTextArea(int row, int Creates a text area with the specified number of
column) rows and columns that displays no text initially.
JTextArea(String s, int Creates a text area with the specified number of
row, int column) rows and columns that displays specified text.
Java Swing - CheckBox
• The JCheckBox class is used to create a checkbox. Clicking on a
CheckBox changes its state from "on" to "off" or from "off" to "on “.
Constructor Description
JCheckBox() Creates an initially unselected check box button
with no text, no icon.
JChechBox(String s) Creates an initially unselected check box with text.
JCheckBox(String text, Creates a check box with text and specifies
boolean selected) whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.
Java Swing - RadioButton
• The JRadioButton class is used to create a radio button. It is used to
choose one option from multiple options.
Constructor Description
JRadioButton() Creates an unselected radio button with no text.
JRadioButton(String s) Creates an unselected radio button with specified
text.
JRadioButton(String s, Creates a radio button with the specified text and
boolean selected) selected status.
Java Swing - List
• The object of JList class represents a list of text items. The list of text
items can be set up so that the user can choose either one item or
multiple items.
Constructor Description
JList() Creates a JList with an empty, read-only, model.
JList(ary[] listData) Creates a JList that displays the elements in the
specified array.
JList(ListModel<ary> Creates a JList that displays elements from the
dataModel) specified, non-null, model.
• Write a Java program to draw a square using Polygon function.
• Write a Java program to draw a Circle using arc function.
Java Swing - ScrollBar
• The object of JScrollbar class is used to add horizontal and vertical
scrollbar.
Constructor Description
JScrollBar() Creates a vertical scrollbar with the initial values.
JScrollBar(int orientation) Creates a scrollbar with the specified orientation
and the initial values.
JScrollBar(int orientation, Creates a scrollbar with the specified orientation,
int value, int extent, int value, extent, minimum, and maximum.
min, int max)
Java Swing - Menus

• The JMenuBar class is used to display menubar on the window or


frame. It may have several menus.
• The object of JMenu class is a pull down menu component which is
displayed from the menu bar. It inherits the JMenuItem class.
• The object of JMenuItem class adds a simple labeled menu item. The
items used in a menu must belong to the JMenuItem or any of its
subclass.
Java Swing - Dialog
• The JDialog control represents a top level window with a border and a
title used to take some form of input from the user.
Constructor Description
JDialog() It is used to create a modeless dialog without a
title and without a specified Frame owner.
JDialog(Frame owner) It is used to create a modeless dialog with
specified Frame as its owner and an empty title.
JDialog(Frame owner, It is used to create a dialog with the specified
String title, boolean modal) title, owner Frame and modality.
Thank you
Conversion
• 1 dollar = 73.16 INR • 1 km = 1000 m • 1 Hr = 60 min
• 1 euro = 86.18 INR • 1 km = 0.6 miles • 1 min = 60 sec
• 1 yen = 0.69 INR • 1 Hr = 3600 sec
Conversion
• 1 dollar = 73.16 INR • 1 km = 1000 m • 1 Hr = 60 min
• 1 euro = 86.18 INR • 1 km = 0.6 miles • 1 min = 60 sec
• 1 yen = 0.69 INR • 1 feet = 12 inches • 1 Hr = 3600 sec
• 1 feet = 0.3048 m
Name

Password

Confirm Password

Address

Submit

You might also like