Module V Quest&Sol
Module V Quest&Sol
What are applets? Explain the different stages in the life cycle of an applet.
What is an applet? With a skeletal code explain the methods that constitute the life cycle of an applet.
What are applets? Demonstrate how to pass parameters for name, font size and type conversion in applet.
A Java applet is a special kind of Java program that a browser enabled with Java technology can download from the internet and run.
An applet is typically embedded inside a web page and runs in the context of a browser. An applet must be a subclass of
the [Link] class. The Applet class provides the standard interface between the applet and the browser environment. An applet
doesn't have a main method. Instead, there are several special methods that serve specific purposes. appletviewer is a program that can
run applets.
An applet is a window-based program. Its architecture is different from the console-based programs. The key concepts of applet
architecture are:
• First, applets are event driven. An applet waits until an event occurs. The run-time system notifies the applet about an event by
calling an event handler that has been provided by the applet. Once this happens, the applet must take appropriate action and then
quickly return. The applet must perform specific actions in response to events and then return control to the run-time system. In
those situations in which your applet needs to perform a repetitive task on its own, you must start an additional thread of execution.
• Second, the user initiates interaction with an applet, not the other way around. In a non-windowed program, when the program
needs input, it will prompt the user and then call some input method. In an applet, the user interacts with the applet as and when
required. For example, when the user clicks the mouse inside the applet’s window, a mouse-clicked event is generated. Applets can
contain various controls, such as push buttons and check boxes. When the user interacts with one of these controls, an event is
generated.
Life Cycle of an Applet consist of following stages: It can initialize itself. It can start running. It can stop running. It can perform
a final cleanup, in preparation for being unloaded.
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.
// An Applet skeleton.
import [Link].*;
import [Link].*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
// Called first.
public void init() { // initialization }
/* Called second, after init. Also called whenever the applet is restarted. */
public void start() { // start or resume execution }
// Called when the applet is stopped.
public void stop() { // suspends execution }
/* Called when applet is terminated. This is the last method executed. */
public void destroy() { // perform shutdown activities }
// Called when an applet's window must be restored.
public void paint(Graphics g) { // redisplay contents of window }
}
6. Demonstrate how to pass parameters for name, font size and type conversion in applet. OR
Explain the applet architecture and demonstrate how to pass parameters for font size, font name, and type conversion in
applets.
(For Applet architecture refer question 3 above)
An APPLET tag in HTML allows you to pass parameters to your applet. To retrieve a parameter, getParameter( ) method is used. It
returns the value of the specified parameter in the form of a String object. Thus, for numeric and boolean values, you will need to
convert their string representations into their internal formats. Here is an example that demonstrates passing parameters:
// Use Parameters
import [Link].*;
import [Link].*;
/*
<applet code="ParamDemo" width=300 height=80>
<param name=fontName value=Courier>
<param name=fontSize value=14>
<param name=leading value=2>
<param name=accountEnabled value=true>
</applet>
*/
public class ParamDemo extends Applet{
String fontName;
int fontSize;
float leading;
boolean active;
// Initialize the string to be displayed.
public void start() {
String param;
fontName = getParameter("fontName");
if(fontName == null)
fontName = "Not Found";
param = getParameter("fontSize");
try {
if(param != null) // if not found
fontSize = [Link](param);
else
fontSize = 0;
} catch(NumberFormatException e) {
fontSize = -1;
}
param = getParameter("leading");
try {
if(param != null) // if not found
leading = [Link](param).floatValue();
else
leading = 0;
} catch(NumberFormatException e) {
leading = -1;
}
param = getParameter("accountEnabled");
if(param != null)
active = [Link](param).booleanValue();
}
// Display parameters.
public void paint(Graphics g) {
[Link]("Font name: " + fontName, 0, 10);
[Link]("Font size: " + fontSize, 0, 26);
[Link]("Leading: " + leading, 0, 42);
[Link]("Account Active: " + active, 0, 58);
}
}
7. What are the two types of applet? Explain the skeleton of an applet. Enlist applet tags.
Refer Question 2 for 2 types of applets.
Refer Question 5 for skeleton of an applet.
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 APPLET
tag is shown here.
< 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>]
. . .
</APPLET>
9. Write a. Java Applet that sets the background color to cyan and foreground color to red and outputs a string message "A
simple Applet”.
// An applet that sets the foreground and background colors and outputs a string.
import [Link].*;
import [Link].*;
/*
<applet code="A Simple Applet" width=300 height=50>
</applet>
*/
public class Sample extends Applet{
String msg;
// set the foreground and background colors.
public void init() {
setBackground([Link]);
setForeground([Link]);
msg = "A Simple Applet";
}
10. Write an applet program to display the message “VTU BELGAUM”. Set the background color to cyan and foreground
color to red.
Same as Question 9 solution, except one change i.e. modify the msg in method init():
msg = "VTU BELGAUM";
11. Write a JAVA applet that continuously plays an audio clip named “[Link]” loaded from applet’s parent directory.
Provide the necessary HTML file to run this applet.
import [Link].*;
import [Link].*;
import [Link].*;
}
// Display code and document bases.
public void paint(Graphics g) {
showStatus("Anthem Demo");
}
}
12. Write a program using an applet which will print "key pressed" on the status window when you press the key, "key
released" on the status window when you release the key and when you type the characters it should print "Hello" at co-
ordinates (50, 50) on Applet.
// Display keystrokes.
public void paint(Graphics g) {
[Link](msg, X, Y);
}
}
13. Develop an applet to create a label, a text field and 4 check boxes with the caption "red", "green", "blue" and "yellow".
import [Link].*;
import [Link].*;
import [Link].*;
public class JCheckBoxDemo extends JApplet
JLabel jlab;
public void init() {
try {
[Link]( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
cb = new JCheckBox("Green");
add(cb);
cb = new JCheckBox("Blue");
add(cb);
cb = new JCheckBox("Yellow");
add(cb);
}
}
14. What are swings? Provide any two typical applications of swings. OR
What is swing? List the main swing features. OR
What is swing? Explain important features of swing. OR
How AWT is different from Swings? What are the two key features of it? Explain. OR
What are the deficiencies of AWT that are overcome by swings? Explain the key features of swings. OR
Differentiate between AWT and swings.
What is Swing?
Java Swing is a Set of classes that provides powerful and flexible GUI components. Swing is built on the AWT. It eliminates a
number of limitations and deficiencies inherent in AWT. Swings are:
• Lightweight- Not built on native window-system windows.
• Provide much bigger set of built-in controls. Trees, image buttons, tabbed panes, sliders, toolbars, etc.
• More customizable. Can change border, text alignment, or add image to almost any control. Can customize how minor
features are drawn.
• Provide "Pluggable" look and feel. Can change look and feel at runtime, or design own look and feel.
Swing is developed to overcome the deficiencies present in Java’s original GUI system AWT. AWT translates various
components into their corresponding platform specific equivalents. Since AWT components use native code resources they are
referred to as heavyweights and possess following deficiencies:
• Because of variations between operating systems a component might look, or even act differently on different platforms.
• Look and feel of each component is fixed (defined by the underlying platform) and cannot be changed easily.
• Use of heavy weight components caused some frustrating restrictions. Heavyweight component is always rectangular and
opaque
How AWT is different from Swings? Or Differentiate between AWT and swings.
AWT Swing
AWT components are Heavyweight component. Swings are called light weight component because swing
components sits on the top of AWT components and do the
work.
AWT components require [Link] package Swing components require [Link] package
AWT components are platform dependent Swing components are made in purely java and they are
platform independent
AWT is a thin layer of code on top of the OS Swing is much larger. Swing also has very much richer
functionality
Swing Components: A Swing component is an independent visual control, such as push button, lable or list. In general Swing
components are derived from JComponent class.
• JComponent supports the pluggable look and feel.
• Swing components are represented by classes defined within the package [Link]
• Examples of Swing component classes
- JApplet, JButton, JCheckBox, JColorChooser, JComboBox,
- JComponent, JDialog, JFrame, JLable, JList, JMenu, JPanel, JRadioButton,
- JScrollBar, JTable, JTree, JWindow etc
Swing Containers: A Swing container is a special kind of component that holds other components. In order for a component to
be displayed it must be held within a container. Since containers are components, a container can also hold other containers.
Swing defines two types of containers
1. Top level containers
• Example: JFrame, JApplet, JWindow, JDialog
• They do not inherit from JComponent, instead they inherit from AWTs Component and Container classes
• They are heavyweight containers
• They appear at the top of the containment hierarchy
• Every containment hierarchy must begin with a top level component
- The most commonly used for the applications is JFrame
- The one used for applets is JApplet
2. Light Weight containers
• Inherit from JComponent
• Example JPanel
• Often used to organize and manage group of related components
• Light weight containers can be contained within another container
Swing defines four types of buttons. All are subclasses of the AbstractButton class.
1. JButton
2. JToggleButton
3. JCheckBox
4. JRadioButton
JButton:
• The JButton class provides the functionality of a push button.
• JButton allows an icon, a string, or both to be associated with the push button. Three of its constructors are:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
• When the button is pressed, an ActionEvent is generated. This ActionEvent object passed to the actionPerformed( )
method of the registered ActionListener.
JToggleButton:
JCheckBox:
• The JCheckBox class provides the functionality of a check box. Its immediate superclass is JToggleButton.
• JCheckBox defines several constructors. One is
JCheckBox(String str)
It creates a check box that has the text specified by str as a label.
• Other constructors let you specify the initial selection state of the button and specify an icon.
• When the user selects or deselects a check box, an ItemEvent is generated. ItemEvent is passed to the
itemStateChanged() method defined by ItemListener.
JRadioButton:
• Radio buttons are a group of mutually exclusive buttons, in which only one button can be selected at any one time.
• JRadioButton class extends JToggleButton.
• JRadioButton provides several constructors. The one is shown here:
JRadioButton(String str)
• A button group is created by the ButtonGroup class. Elements are then added to the button group using method:
void add(AbstractButton ab)
• AJRadioButton generates action events, item events, and change events each time the button selection changes.
• In following example three radio buttons are created and then added to a button group. Pressing a radio button generates
an action event, which is handled by actionPerformed().
17. Create a swing application having two buttons named alpha and beta. When either of buttons pressed, it should display
“alpha pressed” and “beta pressed” respectively.
import [Link].*;
import [Link].*;
import [Link].*;
class EventDemo {
JLabel jlab;
EventDemo() {
// Create a new JFrame container.
JFrame jfrm = new JFrame("An Event Example");
18. Create swing applet that has two buttons named alpha and beta. When either of the buttons pressed, it should display
"alpha vas pressed" and "beta was pressed", respectively.
import [Link].*;
import [Link].*;
import [Link].*;
19. Write a swing applet program to demonstrate with two JButtons named India and Srilanka. When either buttons pressed,
it should display respective label with its icon. Refer the image icons “[Link]” and “[Link]”. Set the initial label is
“press the button”.
// A simple Swing-based applet
import [Link].*;
import [Link].*;
import [Link].*;
/*
This HTML can be used to launch the applet:
JLabel jlab;
20. List the different types of swing buttons. Write a program to create four types of buttons on JApplet. Use suitable events
to show actions on the buttons and use JLabel to display the action invoked. OR
List four types of buttons in swings with their use. Write a program to create four different types of buttons on JApplet.
Use suitable events to show actions on the buttons and use JLabel to display the action invoked.
import [Link].*;
import [Link].*;
import [Link].*;
public class ButtonDemo extends JApplet implements ActionListener {
JLabel jlab;
public void init() {
try {
[Link]( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
21. Explain the following, with an example for each: i) JTextFieId class ii) JButton class iii) JComboBox class.
JTextField:
The class JTextField is a component which allows the editing of a single line of text.
• It is the simplest and most widely used Swing text component.
• Constructors
- JTextField(int cols) : Constructs a new empty TextField with the specified number of columns.
- JTextField(String str, int cols) : Constructs a new TextField initialized with the specified text and columns.
- JTextField(String str) : Constructs a new TextField initialized with the specified str
• To obtain the text currently in the text field, call getText( )
• JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the user presses
ENTER.
JTextField example creates a JTextField and adds it to the content pane. When the user presses ENTER, an action event is
generated. This is handled by displaying the text in the status window.
// Demonstrate JTextField.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet {
JTextField jtf;
public void init() {
try {
[Link]( new Runnable() {
public void run() {makeGUI();}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Change to flow layout.
setLayout(new FlowLayout());
// Add text field to content pane.
jtf = new JTextField(15);
add(jtf);
[Link](new ActionListener() {
public void actionPerformed(ActionEvent ae) {
// Show text when user presses ENTER.
showStatus([Link]());
}
});
}
}
import [Link].*;
import [Link].*;
import [Link].*;
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "India", "Bhutan", "Nepal", "Thailand", "Malaysia", "Indonesia",
"Philippines", "Myanmar", "Kuwait", "UAE", "USA", "UK", "Brazil", "Peru", "Egypt", "Germany",
"France", "Germany", "Italy", "Japan" };
// Handle selections.
[Link](new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) [Link]();
[Link](new ImageIcon(s + ".gif"));
}
});
23. Explain with syntax the following: i) JLabel ii) JTextField iii) JButton iv) JCheckBox.
i) JLable: JLabel is Swing’s easiest-to-use component. It creates a label. JLabel can be used to display text and/or an icon.
It is a passive component in that it does not respond to user input. JLabel defines several constructors. Here are three of
them:
JLabel(Icon icon)
JLabel(String str)
JLabel(String str, Icon icon, int align)
Here, str and icon are the text and icon used for the label. The align argument specifies the horizontal alignment of the text
and/or icon within the dimensions of the label.
ii) JTextField: JTextField is the simplest Swing text component. JTextField allows you to edit one line of text. Three of
JTextField’s constructors are shown here:
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)
Here, str is the string to be initially presented, and cols is the number of columns in the text field. If no string is specified,
the text field is initially empty. If the number of columns is not specified, the text field is sized to fit the specified string.
JTextField generates events in response to user interaction. For example, an ActionEvent is fired when the user presses
ENTER. To obtain the text currently in the text field, call getText().
iii) JButton: The JButton class provides the functionality of a push button. JButton allows an icon, a string, or both to be
associated with the push button. Three of its constructors are shown here:
JButton(Icon icon)
JButton(String str)
JButton(String str, Icon icon)
Here, str and icon are the string and icon used for the button. When the button is pressed, an ActionEvent is generated.
Using the ActionEvent object passed to the actionPerformed( ) method of the registered ActionListener, you can obtain
the action command string associated with the button. You can obtain the action command by calling
getActionCommand( ) on the event object.
iv) JCheckBox: Check Boxes The JCheckBox class provides the functionality of a check box. Its immediate superclass is
JToggleButton, which provides support for two-state buttons, as just described. JCheckBox defines several constructors.
For example JCheckBox(String str)
It creates a check box that has the text specified by str as a label. Other constructors let you specify the initial selection
state of the button and specify an icon. When the user selects or deselects a check box, an ItemEvent is generated. You
can obtain a reference to the JCheckBox that generated the event by calling getItem() on the ItemEvent passed to the
itemStateChanged() method defined by ItemListener. The easiest way to determine the selected state of a check box is
to call isSelected( ) on the JCheckBox instance.
24. Explain the JScrollPane with an example.
import [Link].*;
import [Link].*;
public class JScrollPaneDemo extends JApplet {
public void init() {
try {
[Link]( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
` // Add 400 buttons to a panel.
JPanel jp = new JPanel();
[Link](new GridLayout(20, 20));
int b = 0;
for(int i = 0; i < 20; i++) {
for(int j = 0; j < 20; j++) {
[Link](new JButton("Button " + b));
++b;
}
}
// Create the scroll pane.
JScrollPane jsp = new JScrollPane(jp);
// Add the scroll pane to the content pane. Because the default border layout
// is used, the scroll pane will be added to the center.
add(jsp, [Link]);
}
}
JComboBox:
• Swing provides a combo box (a combination of a text field and a drop-down list) through the JComboBox class.
• A combo box normally displays one entry, but it will also display a drop-down list that allows a user to select a different entry.
• The following JComboBox constructor initializes the combo box using items array
JComboBox(Object[ ] items)
• JComboBox generates an action event when the user selects an item from the list. JComboBox also generates an item event
when the state of selection changes, which occurs when an item is selected or deselected.
• One way to obtain the item selected in the list is to call getSelectedItem( ) on the combobox.
The following example demonstrates the combo box. The combo box contains entries for “France,” “Germany,” “Italy,” and
“Japan.” When a country is selected, an icon-based label is updated to display the flag for that country.
import [Link].*;
import [Link].*;
import [Link].*;
public class JComboBoxDemo extends JApplet {
JLabel jlab;
ImageIcon france, germany, italy, japan;
JComboBox jcb;
String flags[] = { "France", "Germany", "Italy", "Japan" };
// Handle selections.
[Link](new ActionListener() {
public void actionPerformed(ActionEvent ae) {
String s = (String) [Link]();
[Link](new ImageIcon(s + ".gif"));
}
});
26. Write the steps to create JTable. Write a program to create a table with column headings “fname, lname, age” and insert
at least 5 records in the table and display. OR
Write the steps to create JTabIe. Write a program to create a table with the column headings "Fname, Lname, Age' and
insert at least five records in the table and display. OR
Write the steps to create 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:
Program to create a table with the column headings "Fname, Lname, Age' and insert at least five records in the table and
display.
import [Link].*;
import [Link].*;
public class JTableDemo extends JApplet {
public void init() {
try {
[Link]( new Runnable() {
public void run() {
makeGUI();
}
} );
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Initialize column headings.
String[] colHeads = { "Fname", "Lname", "Age" };
// Initialize data.
Object[][] data = {
{ "Zahid", "Ansari", "50" },
{ "Abdullah", "Ansari", "19" },
{ "Musab", "Ansari", "17" },
{ "Muaaz", "Ansari", "16" },
{ "Abdurrahman", "Ansari", "10" }
};
// Create the table.
JTable table = new JTable(data, colHeads);
27. Write a program to create a table with the column headings Name, USN, Age, Address and insert at least five records in
the table and display.
(Refer Question 26 above and change the colHeads to Name, USN, Age, Address and add 5 data items )
String[] colHeads = { "Name", “USN”, "Age", "Address" };
Object[][] data = {
{ "Ahmed", "123456", "20", “Deralakatte” },
.
.
.
.
};
28. Explain the different types of panes of swing containers.