Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Unit 6

Download as pdf or txt
Download as pdf or txt
You are on page 1of 10

UNIT-6

(Applets and Event Handling)

Introduction:

Java Applets are small programs that run on a web page within a web browser. They are
written in the Java programming language and are downloaded from a web server and
executed on the client-side. Applets were introduced by Sun Microsystems in the mid-1990s
as a way to add interactivity and dynamic content to web pages.

Applets are embedded in an HTML page and are downloaded and executed by a web
browser. They run in a sandboxed environment, which means they cannot access the file
system or other resources on the client machine without explicit permission from the user.
This makes applets a secure way to add interactive content to web pages.

Applets can be used to create interactive animations, games, simulations, and other types of
multimedia content. They can also be used to provide dynamic data visualization, such as
charts and graphs. Applets can interact with server-side scripts, databases, and other web
services, making them a powerful tool for developing web-based applications.

To create an applet, you need to write Java code that implements the applet's behavior. This
code is compiled into a .class file, which is then packaged into a .jar file along with any other
resources needed by the applet. The .jar file is then uploaded to a web server and embedded
in an HTML page using the <applet> tag.

Here is an example of an applet that displays the message "Hello, World!" in a web page:

import java.applet.*;
import java.awt.*;
public class HelloWorld extends Applet {
public void paint(Graphics g) {
g.drawString("Hello, World!", 20, 20);
}
}

This code defines a simple applet that overrides the paint() method to display the message
"Hello, World!" on the applet's canvas. To run this applet, you need to compile the code into
a .class file, package it into a .jar file, and embed it in an HTML page using the <applet> tag.

Working with Graphics in JAVA Applet:


Working with graphics in a Java applet involves using the Graphics class, which is a part of
the AWT (Abstract Window Toolkit) package. The Graphics class provides methods for
drawing and manipulating shapes, text, and images on a canvas.

Here is an example of an applet that uses the Graphics class to draw a simple rectangle:
import java.applet.*;
import java.awt.*;
public class MyRectangle extends Applet {
public void paint(Graphics g) {
g.drawRect(50, 50, 100, 50);
}
}

This code defines an applet that overrides the paint() method to draw a rectangle using the
drawRect() method of the Graphics class. The drawRect() method takes four arguments: x, y,
width, and height, which specify the position and size of the rectangle.

Here are some other common methods of the Graphics class that you can use to draw and
manipulate shapes and text:

 drawLine(x1, y1, x2, y2): Draws a line from point (x1, y1) to point (x2, y2).
 drawOval(x, y, width, height): Draws an oval inside the rectangle specified by x, y,
width, and height.
 drawString(text, x, y): Draws the specified text at the position (x, y).
 setColor(color): Sets the color for subsequent drawing operations.
 setFont(font): Sets the font for subsequent text drawing operations.

You can also use the Graphics class to load and display images in your applet. Here is an
example of an applet that displays an image:

import java.applet.*;
import java.awt.*;
public class MyImage extends Applet {
Image img;
public void init() {
img = getImage(getDocumentBase(), "image.jpg");
}
public void paint(Graphics g) {
g.drawImage(img, 50, 50, this);
}
}

This code defines an applet that loads an image from a file called "image.jpg" using the
getImage() method of the Applet class. The image is then displayed using the drawImage()
method of the Graphics class, which takes the image, the position to draw it, and a reference
to the applet as arguments.

Working with graphics in a Java applet can be a powerful way to create dynamic and
interactive content. The Graphics class provides a wide range of methods for drawing and
manipulating shapes, text, and images, which you can use to create rich and engaging user
interfaces for your applets.

Event Handling Mechanisms:


Event handling in Java applets involves responding to user actions such as mouse clicks,
button presses, and key presses. The Java AWT (Abstract Window Toolkit) provides several
classes and interfaces for handling events in applets.

To handle events in an applet, you typically define a listener object that implements the
appropriate interface for the event type you want to handle. Here are some common listener
interfaces and their corresponding event types:

 ActionListener: Handles events when a user clicks a button or menu item.


 MouseListener: Handles events when a user clicks or releases a mouse button.
 KeyListener: Handles events when a user presses or releases a key on the keyboard.

Here is an example of an applet that uses an ActionListener to respond to button clicks:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyButton extends Applet implements ActionListener {
Button btn; public void init() {
btn = new Button("Click me!");
add(btn);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
System.out.println("Button clicked!");
}
}
}

This code defines an applet that creates a button using the Button class and adds it to the
applet's canvas. The applet also registers itself as an ActionListener for the button using the
addActionListener() method. When the button is clicked, the actionPerformed() method is
called and checks whether the event source is the button. If it is, the method prints a message
to the console.

You can use similar techniques to handle other types of events in your applets. For example,
you can implement the MouseListener interface to handle mouse clicks or the KeyListener
interface to handle key presses. The basic approach is to define a listener object that
implements the appropriate interface and registers itself with the event source using a
registration method such as addActionListener().

Adapter and Inner Classes:


Adapter classes and inner classes are two useful features in Java applets that simplify event
handling and organization of code.

Adapter Classes
Adapter classes are a set of empty implementations of an event listener interface. By using
adapter classes, you can create listener objects that only handle the events you are interested
in, without having to provide empty implementations of the other events.
Here is an example of an applet that uses an adapter class to handle mouse events:

import java.applet.*;
import java.awt.event.*;
public class MyMouse extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
System.out.println("Mouse clicked at (" + e.getX() + "," + e.getY() + ")");
}
}
}
}

This code defines an applet that creates a new MouseAdapter object and overrides its
mouseClicked() method to print the position of the mouse click to the console. The applet
registers the MouseAdapter object as a listener for mouse events using the
addMouseListener() method.

Inner Classes
Inner classes are classes defined within another class. They are useful for organizing code
and providing encapsulation. In Java applets, inner classes are commonly used to define
event listeners.

Here is an example of an applet that uses an inner class to handle button clicks:

import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class MyButton extends Applet {
Button btn; public void init() {
btn = new Button("Click me!");
add(btn);
btn.addActionListener(new ButtonListener());
}
class ButtonListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
}
}
}

This code defines an applet that creates a new inner class called ButtonListener, which
implements the ActionListener interface. The applet creates a button using the Button class
and adds it to the applet's canvas. The applet registers an instance of the ButtonListener class
as a listener for button clicks using the addActionListener() method.

Inner classes can be useful for organizing code that is closely related to a specific applet. By
defining event listeners as inner classes, you can keep the event handling code close to the
code that creates the components that generate the events.
In summary, adapter classes and inner classes are two powerful features in Java applets that
simplify event handling and organization of code. By using adapter classes, you can create
listener objects that only handle the events you are interested in, without having to provide
empty implementations of the other events. By using inner classes, you can organize event
handling code and keep it close to the code that creates the components that generate the
events.
The design and Implementation of GUIs using the AWT controls :

The AWT (Abstract Window Toolkit) is a collection of classes and interfaces that provide the
basic building blocks for creating graphical user interfaces in Java. AWT provides a range of
controls that can be used to create GUIs, including buttons, text fields, labels, menus,
checkboxes, radio buttons, and more.

Here are the basic steps involved in designing and implementing GUIs using AWT controls:

1. Create a new Java class that extends the Applet class. This class will serve as the main
container for your GUI components.
import java.applet.*;
import java.awt.*;
public class MyGUI extends Applet {
// Your GUI components will go here
}
2. Declare and initialize your GUI components. You can use a variety of AWT controls
to create your GUI, such as Button, Label, TextField, and more.
public class MyGUI extends Applet {
Button btn;
Label lbl;
TextField txt;
public void init() {
btn = new Button("Click me!");
lbl = new Label("Enter your name:");
txt = new TextField(20);
add(lbl);
add(txt);
add(btn);
}
}
3. Add your GUI components to the applet container using the add() method. This
method takes a single argument, which is the GUI component you want to add to the applet.
4. Define event handlers for your GUI components. You can define event handlers using
either inner classes or anonymous inner classes. For example, to define an event handler for a
button, you can create a new ActionListener object that defines the actionPerformed()
method.
public class MyGUI extends Applet implements ActionListener {
Button btn;
Label lbl;
TextField txt;
public void init() {
btn = new Button("Click me!");
lbl = new Label("Enter your name:");
txt = new TextField(20);
add(lbl);
add(txt);
add(btn);
btn.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == btn) {
String name = txt.getText();
System.out.println("Hello, " + name + "!");
}
}
}

In this example, we create a new ActionListener object by implementing the ActionListener


interface and overriding its actionPerformed() method. We then register the ActionListener
with the button using the addActionListener() method.

5. Compile and run your applet. Once your GUI is complete, you can compile your code
and run it using a web browser or an applet viewer.

In summary, creating GUIs using AWT controls involves creating a new Java class that
extends the Applet class, declaring and initializing your GUI components, adding them to the
applet container using the add() method, defining event handlers for your components, and
compiling and running your applet. AWT provides a rich set of controls that can be used to
create a wide range of GUIs in Java.

Swing components of Java Foundation Classes :


Swing is a GUI widget toolkit for Java that provides a collection of lightweight, customizable
components for creating rich graphical user interfaces. Swing components are part of the Java
Foundation Classes (JFC) and are implemented entirely in Java, which means that they are
platform-independent and can be used on any operating system that supports Java.

Some of the key Swing components in the JFC include:

1. JFrame: A top-level container that provides a window for your application. You can
add other Swing components to a JFrame to create a GUI.
2. JPanel: A lightweight container that can be used to group other components together.
JPanels can be added to JFrames or other JPanels.
3. JButton: A component that provides a button that can be clicked by the user. You can
define event handlers for button clicks using the ActionListener interface.
4. JLabel: A component that displays a text label or an image. You can use JLabels to
provide instructions or feedback to the user.
5. JTextField: A component that allows the user to enter text. You can retrieve the text
entered by the user using the getText() method.
6. JCheckBox: A component that provides a checkbox that can be checked or unchecked
by the user. You can use JCheckBoxes to provide options to the user.
7. JRadioButton: A component that provides a radio button that can be selected by the
user. You can use JRadiobuttons to provide mutually exclusive options to the user.
8. JList: A component that provides a list of items that can be selected by the user. You
can use JLists to display a collection of items and allow the user to select one or more of
them.
9. JComboBox: A component that provides a dropdown list of items that can be selected
by the user. You can use JComboBoxes to provide a list of options to the user.
10. JTable: A component that provides a table of data that can be edited by the user. You
can use JTables to display and manipulate data in a tabular format.

Layout managers, Menus, Events and Listeners :

Layout Managers: Layout Managers are used to arrange Swing components in a


container such as JFrame or JPanel. Swing provides several built-in layout managers
that you can use to arrange components on the screen in a particular way. The layout
managers include BorderLayout, FlowLayout, GridLayout, CardLayout, and
GroupLayout. Each of these layout managers has a different approach to arranging
components, and you can choose the most appropriate one depending on your
needs.

Menus: Menus are a common way to provide access to various options and features
in a GUI. In Swing, you can create menus using the JMenuBar, JMenu, and JMenuItem
classes. JMenuBar is a container that holds one or more JMenu components, each of
which can hold one or more JMenuItem components. You can add event handlers to
the JMenuItem components to respond to user selections.

Events and Listeners: Events are generated when a user interacts with a Swing
component, such as clicking a button or selecting an item from a list. To respond to
these events, you can create an event listener that implements an appropriate
interface, such as ActionListener, MouseListener, or KeyListener. Each interface
defines one or more methods that you can implement to respond to events. You can
register an event listener with a component using the add<EventListener> method,
where <EventListener> is the name of the interface that you want to implement.

Here's an example that demonstrates how to use a layout manager, create a menu,
and handle events in Swing:

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class MyFrame extends JFrame implements ActionListener {
private JButton myButton;
private JTextField myTextField;
public MyFrame() {
super ( "My Frame" );
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout( new FlowLayout ());
myButton = new JButton ( "Click Me" );
myButton.addActionListener( this );
add(myButton);
myTextField = new JTextField ( 10 );
add(myTextField);
JMenuBar menuBar = new JMenuBar ();
JMenu fileMenu = new JMenu ( "File" );
JMenuItem exitItem = new JMenuItem ( "Exit" );
exitItem.addActionListener( this );
fileMenu.add(exitItem);
menuBar.add(fileMenu);
setJMenuBar(menuBar);
pack();
setVisible( true );
}
public void actionPerformed(ActionEvent e) {
if (e.getSource() == myButton) {
myTextField.setText( "Button clicked" );
}
else if (e.getActionCommand().equals( "Exit" )) {
System.exit( 0 );
}
}
public static void main(String[] args) {
MyFrame frame = new MyFrame ();
}
}

In this example, we create a JFrame with a FlowLayout manager and add a JButton
and a JTextField to it. We also create a menu using JMenuBar, JMenu, and
JMenuItem, and add an ActionListener to the JMenuItem to handle the "Exit"
command. Finally, we implement the ActionListener interface in the MyFrame class
and define the actionPerformed method to respond to button clicks and menu
selections.

Graphic objects for drawing figures :


Swing provides several classes for drawing shapes and graphics in a Java application. Here
are some of the most commonly used graphic objects for drawing figures in Java Swing:

1. Graphics class: The Graphics class is the main class for drawing shapes in Swing. It
provides methods for drawing lines, shapes, text, and images on a component. You can obtain
a Graphics object for a component using the getGraphics() method.
2. Color class: The Color class represents a color in the RGB (red, green, blue) color
space. You can set the color of a shape using the setColor() method of the Graphics class.
3. Font class: The Font class represents a font used for drawing text. You can set the font
of a text using the setFont() method of the Graphics class.
4. Graphics2D class: The Graphics2D class is a subclass of the Graphics class that
provides additional methods for advanced 2D graphics operations. You can cast a Graphics
object to Graphics2D to use these methods.
5. Shape class: The Shape class is an abstract class that represents a geometric shape,
such as a rectangle, ellipse, or polygon. You can create a Shape object using the methods of
the Path2D class, such as moveTo(), lineTo(), and curveTo().
6. BasicStroke class: The BasicStroke class defines the width and style of a line. You
can set the stroke of a line using the setStroke() method of the Graphics2D class.
7. GradientPaint class: The GradientPaint class represents a gradient color that changes
gradually from one color to another. You can use the setPaint() method of the Graphics2D
class to set the color of a shape to a gradient paint.

Here's an example that demonstrates how to use some of these graphic objects to draw a
rectangle and a line in Swing:

import javax.swing.*;
import java.awt.*;
public class MyFrame extends JFrame {
public MyFrame() {
super("My Frame");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 300);
setVisible(true);
}
public void paint(Graphics g) {
super.paint(g);
Graphics2D g2d = (Graphics2D) g;
g2d.setColor(Color.RED);
g2d.fillRect(50, 50, 100, 100);
g2d.setColor(Color.BLUE);
g2d.setStroke(new BasicStroke(5));
g2d.drawLine(50, 50, 150, 150);
}
public static void main(String[] args) {
MyFrame frame = new MyFrame();
}
}

In this example, we override the paint() method of the JFrame class to draw a red rectangle
using the fillRect() method of the Graphics2D class, and a blue line using the drawLine()
method. We also set the stroke of the line using the setStroke() method and cast the Graphics
object to Graphics2D to use this method. Finally, we set the color of the shapes using the
setColor() method of the Graphics2D class.
JAVA Swing:
Java Swing is a graphical user interface (GUI) toolkit that allows developers
to create cross-platform desktop applications in Java. It is built on top of
the Abstract Window Toolkit (AWT) and provides a rich set of graphical
components, such as buttons, labels, text fields, tables, trees, and more.

Swing components are lightweight, meaning that they don't rely on the
operating system's native widgets and can be rendered consistently on any
platform. This makes Swing ideal for developing applications that need to
look and feel the same across different operating systems.

Swing provides a powerful event-driven programming model that allows


developers to respond to user actions, such as button clicks and key
presses, with custom code. It also provides layout managers that
automatically position and size components in a container, making it easy
to create complex user interfaces.

Swing provides a rich set of features, such as drag and drop, data binding,
and accessibility support, that make it easy to develop professional-looking
applications. It also provides support for internationalization and
localization, allowing applications to be translated into multiple languages.

Swing has been widely used for developing desktop applications in Java,
including integrated development environments (IDEs), media players,
database clients, and more. It continues to be actively developed and
maintained as part of the Java Foundation Classes (JFC) and is included in
the standard Java Development Kit (JDK).
Overview of servlets:

Servlets are Java-based components that provide a server-side solution for handling HTTP
requests and generating dynamic web content. Servlets are used to extend the functionality of
web servers by providing a way to generate dynamic content in response to client requests.

Servlets are executed on the server-side and are used to handle requests and generate
responses. They can be used for a variety of purposes such as handling HTML form data,
generating dynamic content, generating PDF documents, and more.

Servlets are typically used in web applications and can be used in conjunction with other web
technologies such as JavaServer Pages (JSP) and JavaServer Faces (JSF). Servlets are
commonly used in server-side web application frameworks such as Spring, Struts, and
JavaServer Faces.

Servlets are deployed in a web container such as Apache Tomcat, Jetty, or JBoss. When a
client sends a request to the web server, the web container receives the request and dispatches
it to the appropriate servlet. The servlet generates the response and sends it back to the client.

Servlets are part of the Java Enterprise Edition (Java EE) platform and are included in the
Java Standard Edition (Java SE) as well. Servlets provide a powerful and flexible way to
create server-side web applications using Java. They are widely used in enterprise web
applications and provide a robust and scalable solution for handling HTTP requests and
generating dynamic web content.

You might also like