0% found this document useful (0 votes)
23 views8 pages

Module 5 Questions and Answers

The document provides an overview of Java applets, including their lifecycle, HTML applet tag, and event handling concepts such as event delegation model, events, event listeners, and event sources. It also discusses Java Swing, its features, components, and containers, along with procedures to create a JTable and buttons in a JApplet with event handling. Sample code snippets are included to illustrate the implementation of applets and Swing components.

Uploaded by

lakshmidk019
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)
23 views8 pages

Module 5 Questions and Answers

The document provides an overview of Java applets, including their lifecycle, HTML applet tag, and event handling concepts such as event delegation model, events, event listeners, and event sources. It also discusses Java Swing, its features, components, and containers, along with procedures to create a JTable and buttons in a JApplet with event handling. Sample code snippets are included to illustrate the implementation of applets and Swing components.

Uploaded by

lakshmidk019
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

1. What are applets? What are the 2 types of applet?

Explain different stages in the life-


cycle of an applet.
 An applet is a Java program that is intended to be transported over the web and executed
using a web browser.
 An applet doesn't have a main method
Life cycle of an applet
Applets life cycle includes the following methods
i)init( ) ii)start( ) iii)paint( ) iv)stop( ) v)destroy( )
 Applets are created by extending the Applet class.
import java.awt.*;
import java.applet.*;
// <applet code="AppletSkel" width=300 height=100> </applet>
public class AppletSkel extends Applet {
public void init() {
// initialization
}
public void start() {
// start or resume execution
}
public void stop() {
// suspends execution
}
public void destroy() {
// perform shutdown activities
}
public void paint(Graphics g) {
// redisplay contents of window
}
}
 public void init(): This method is intended for whatever initialization is needed for an
applet.
 public void start(): This method is automatically called after init method. It is also called
whenever user returns to the page containing the applet after visiting other pages.
 public void paint(Graphics g): This method is called by the browser after init() and start().
Re-invoked whenever the browser redraws the screen. (Typically when part of the screen
is obscured and then re-exposed). This method is where user level drawings are placed.
 public void stop(): This method is automatically called whenever the user moves away
from the page containing applets. This method can be used to stop an animation.
 public void destroy(): This method is only called when the browser shuts down normally.

2. Briefly explain HTML applet tag. Write a java applet that sets the background color
to cyan and foreground color to red and outputs a string message “A simple applet”.
HTML Applet Tag
 The APPLET tag is used to start an applet from both an HTML document and from an
applet viewer.
 An applet viewer will execute each APPLET tag that it finds in a separate window, while
web browsers will allow many applets on a single page.
 The syntax for the standard APPLET tag is shown here. Bracketed items are optional.
< APPLET
[CODEBASE = codebaseURL]
CODE = appletFile
[ALT = alternateText]
[NAME = appletInstanceName]
WIDTH = pixels HEIGHT = pixels
[ALIGN = alignment]
[VSPACE = pixels] [HSPACE = pixels]
>
[< PARAM NAME = AttributeName VALUE = AttributeValue>]
[< PARAM NAME = AttributeName2 VALUE = AttributeValue>]
...
[HTML Displayed in the absence of Java]
</APPLET>
 CODEBASE : is an optional attribute. It specifies the directory that has to be searched
for the applet’s executable class file. If this attribute is not specified then the HTML
document’s URL directory is used as the CODEBASE.
 CODE : is a required attribute that gives the name of the file containing your applet’s
compiled .class file.
 ALT : is an optional attribute used to specify a short text message that should be displayed
if the browser recognizes the APPLET tag but can’t currently run Java applets.
 NAME : is an optional attribute used to specify a name for the applet instance.
 WIDTH and HEIGHT : are required attributes that give the size (in pixels) of the applet
display area.
 ALIGN : is an optional attribute that specifies the alignment of the applet.
 VSPACE and HSPACE : These attributes are optional. VSPACE specifies the space, in
pixels, above and below the applet. HSPACE specifies the space, in pixels, on each side of
the applet.
 PARAM NAME and VALUE : The PARAM tag allows you to specify applet-specific
arguments in an HTML page.
Program
import java.awt.*;
import java.applet.*;
// <applet code="Sample" width=300 height=50> </applet>
public class Sample extends Applet{
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
}
public void paint(Graphics g) {
String msg = " A Simple Applet";
g.drawString(msg, 10, 30);
} }

3. Explain the following terms with respect to event handling in Java:


i) Event Delegation Model
ii) Event
iii) Event Listener
iv) Event Source
Delegation Event Model
 The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms 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 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.
 This is a more efficient way to handle events than the design used by the old Java 1.0
approach. Previously, an event was propagated up the containment hierarchy until it was
handled by a component.
 This required components to receive events that they did not process, and it wasted valuable
time. The delegation event model eliminates this overhead.
 Event
 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.
 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.
public void addTypeListener(TypeListener el)
Here, Type is the name of the event and el is a reference to the event listener.
o For example,
The method that registers a keyboard event listener is called
addKeyListener().
The method that registers a mouse motion listener is called
addMouseMotionListener( ).
 Event Listeners
 A listener is an object that is notified when an event occurs.
 Event has two major requirements.
 It must have been registered with one or more sources to receive notifications
about specific types of events.
 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.
4. What is a swing? Discuss about swing features. Explain the components and
containers in the swings.
Java Swing is a Set of classes that provides powerful and flexible GUI components. Swing is
built on the AWT.
Two Key Swing Features
1. Swing Components Are Lightweight
Swing components are lightweight. This means that they are written entirely in Java and
do not map directly to platform-specific peers. Because lightweight components are
rendered using graphics primitives, they can be transparent, which enables
nonrectangular shapes.
Thus, lightweight components are more efficient and more flexible. Furthermore,
because lightweight components do not translate into native peers, the look and feel of each
component is determined by Swing, not by the underlying operating system. This means
that each component will work in a consistent manner across all platforms.
2. Swing Supports a Pluggable Look and Feel
Swing supports a pluggable look and feel (PLAF). Because each Swing component is
rendered by Java code rather than by native peers, the look and feel of a component is under
the control of Swing. This fact means that it is possible to separate the look and feel of a
component from the logic of the component, and this is what Swing does.
PLAF advantages are as follows: (i) It is possible to define a look and feel that is consistent
across all platforms. (ii)it is possible to create a look and feel that acts like a specific
platform. (iii)it is possible to design accustom look and feel (iv)The look and feel can be
changed dynamically at run time.
Component
A component is an independent visual control and Java Swing Framework contains a large set
of these components which provide rich functionalities and allow high level of customization.
They all are derived from JComponent class.
All these components are lightweight components. This class provides some common
functionality like pluggable look and feel, support for accessibility, drag and drop, layout, etc.
Containers
A container holds a group of components. It provides a space where a component can be
managed and displayed.
Containers are of two types:
1. Top level Containers
 It inherits Component and Container of AWT.
 It cannot be contained within other containers.
 Example: JFrame, JDialog, JApplet
2. Lightweight Containers
 It inherits JComponent class.
 It can be used to organize related components together.
 Example: JPanel

5. Explain the procedure to create a JTable in a Java Swing application. Develop a


program to create a JTable.
 JTable is a component that displays rows and columns of data.
 At the top of each column is a heading. In addition to describing the data in a column, the
heading also provides the mechanism by which the user can change the size of a column or
change the location of a column within the table.
 The steps required to set up a simple JTable that can be used to display data are described
below:
1. Create an instance of JTable.
A commonly used constructor for JTable: JTable(Object data[ ][ ], Object colHeads[ ])
data is a two-dimensional array of the information to be presented, and
colHeads is a one-dimensional array with the column headings.
2. Create a JScrollPane object, specifying the table as the object to scroll.
3. Add the table to the scroll pane.
4. Add the scroll pane to the content pane.
Program
import java.awt.*;
import javax.swing.*;
public class JTableDemo extends JApplet {
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Fname", "Lname", "Age" };
// Initialize data.
Object[][] data = {
{ "Manjunath", "M P", "39" },
{ "Vinay", "V N", "19" },
{ "Anil", "K B", "17" },
{ "Sachin", "N M", "16" },
{ "Siddu", "A S", "10" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
// Add the table to a scroll pane.
JScrollPane jsp = new JScrollPane(table);
// Add the scroll pane to the content pane.
add(jsp);
}
}

6. Develop a program to create four different types of buttons on a JApplet. Implement


appropriate event handling to respond to actions on the buttons, and use a JLabel to
display the action invoked.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class ButtonDemo extends JApplet implements ActionListener {
JLabel jlab;
public void init() {
try {
SwingUtilities.invokeAndWait( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
System.out.println("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add buttons to content pane.
JButton jb = new JButton(“Button”);
jb.addActionListener(this);
add(jb);
// Create and add a toggle button.
JToggleButton cb = new JToggleButton("ToggleButton");
cb.addActionListener(this);
add(cb);
// Create and add a check box.
JCheckBox cb = new JCheckBox ("CheckBox ");
cb.addActionListener(this);
add(cb);
// Create and add a radio button.
JRadioButton rb = new JRadioButton ("JRadioButton ");
rb.addActionListener(this);
add(rb);
// Create and add the label to content pane.
jlab = new JLabel("Press/Select a Button");
add(jlab);
}
// Handle button events.
public void actionPerformed(ActionEvent ae) {
jlab.setText("You selected " + ae.getActionCommand());
}
}

You might also like