[go: up one dir, main page]

0% found this document useful (0 votes)
8 views19 pages

Java Unit-4

The document provides a comprehensive overview of Java applets, including definitions, types, and key methods associated with applets such as init(), start(), stop(), and destroy(). It also discusses event handling through the Delegation Event Model, detailing event sources, listeners, and various listener interfaces like ActionListener and MouseListener. Additionally, it includes practical examples of handling mouse and key events in applets, as well as creating frame windows and utilizing Swing components like JButton and JTextField.

Uploaded by

knganesh2001
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)
8 views19 pages

Java Unit-4

The document provides a comprehensive overview of Java applets, including definitions, types, and key methods associated with applets such as init(), start(), stop(), and destroy(). It also discusses event handling through the Delegation Event Model, detailing event sources, listeners, and various listener interfaces like ActionListener and MouseListener. Additionally, it includes practical examples of handling mouse and key events in applets, as well as creating frame windows and utilizing Swing components like JButton and JTextField.

Uploaded by

knganesh2001
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/ 19

UNIT-IV

Questions carrying 2 marks

1. What is an 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 java.applet.Applet class. The Applet
class provides the standard interface between the applet and the browser environment.

2. List two types of Applets available in Java.

• Applet
• Swing JApplet

3. What is the purpose of appletviewer?

An applet viewer executes your applet in a window. This is generally the fastest and easiest
way to test your applet.

4. Write HTML file to run an applet program named Simple.

<!DOCTYPE html>

<html>

<head>

<title> Simple </title>

</head>

<body>

<applet code=”Simple.class” height=100 width=200>

</applet>

</body>

</html>

5. List any two features of Applets.

• Speed: Smaller, incremental JRE download and faster applet startup.


• Draggable applets: Applets can now be dragged out of the web browser and
run as separate applications.

6. What is the purpose of paint() method?


The method paint() gives us access to an object of type Graphics class. The paint ( ) method
is called each time when your applet’s output must be redrawn. It may be also called when the
applet begins its execution.
7. List any four methods associated with applets?
Ans: Four methods used by applets are:
1. init(): is used to initialize the Applet.
2. start(): It is used to start the Applet.
3. stop(): is used to stop the Applet.
4. destroy(): is used to destroy the Applet.

8. What is the purpose of repaint() method?

The Repaint method() is responsible for handling update to the paint cycle of the applet.
The repaint method is a final method available in the applet class, and that’s why it cannot be
overridden.

9. Differentiate stop() and destroy() methods.

Ans: stop(): The stop() method stops the execution of the applet. The stop () method is called when
the applet is stopped or minimized. When we go back to that page, the start() method is invoked again.

destroy(): The destroy() method destroys the applet after its work is done. It is invoked when the
applet window is closed. It removes the applet object from memory and is executed only once. We
cannot start the applet once it is destroyed.

10. What is the purpose of update() method ?

This method is called when your applet has requested that a potion of its window be redrawn.
Update method is used to clear the current window, performs an update, and afterwards calls paint
method.

11. List the superclasses of Applet defined by AWT.

Ans: java.lang.Object

java.awt.Component

java.awt.Container

java.awt.Panel

java.awt.applet

12. List any 4 methods defined by applet.

Ans: init()
start()

stop()

destroy()

13.What is an event? Give example.

An event in Java is an object that is created when something changes within a graphical user
interface. If a user clicks on a button, clicks on a combo box, or types characters into a text field, etc.,
then an event triggers, creating the relevant event object.

14. What is purpose of Event Listener?

A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.

15. List the key features of a swing GUI.

• Pluggable look and feel.


• Uses MVC architecture.
• Lightweight Components.
• Platform Independent.

16. What happens when the constructor JButton(String msg) is called?

When the constructor JButton(String msg) is called, the msg parameter specifies the string
that will be displayed inside the button.

17. What is the purpose of setText() and getText() methods?

Using setText( ), it is possible to change the text inside a label during program execution. The
getText( ) method gets the text for that check box and uses it to set the text inside the label.

18. List any four swing components.

• Jlist
• JButton
• JComboBox
• JCheckBox

19. Differentiate Component and Container.

A component is an independent visual control, such as a push button or slider. A container


holds a group of components. Thus, a container is a special type of component that is designed to
hold other components. Furthermore, in order for a component to be displayed, it must be held
within a container.
Questions carrying 4 or more marks

1. Write the complete Applet skeleton with example.

All but the most trivial applets override a set of methods that provides the basic mechanism by
which the browser or applet viewer interfaces to the applet and controls its execution. Four of these
methods, init( ), start( ), stop( ), and destroy( ), apply to all applets and are defined by Applet.
Default implementations for all of these methods are provided. Applets do not need to override
those methods they do not use. However, only very simple applets will not need to define all of
them. Another, paint( ), is defined by the AWT Component class. All applets must import java.applet.
Applets must also import java.awt.

These five methods can be assembled into the skeleton shown here:

// An Applet skeleton.

import java.awt.*;

import java.applet.*;

/*

<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

}}

2. List and explain any 6 methods defined by Applet .

• init( ): init( ) method is called once—the first time an applet is loaded. The init( )
method is the first method to be called. This is where you should initialize variables.
• start(): The start( ) method is called after init( ). It is also called to restart an applet
after it has been stopped(i.e start() method is called every time, the applet resumes
execution).
• Paint(): The paint( ) method is called each time your applet’s output must be
redrawn. This situation can occur for several reasons.
For example, the window in which the applet is running may be overwritten by another
window and then uncovered. Or the applet window may be minimized and then restored.
paint( ) is also called when the applet begins execution. Whatever the cause, whenever the
applet must redraw its output, paint( ) is called. The paint( ) method has one parameter of
type Graphics.
• stop( ): The stop() method is called when the applet is stopped(i.e for example
,when the applet is minimized the stop method is called).
• destroy( ): The destroy( ) method is called when the environment determines that your
applet needs to be removed completely from memory(i.e destroy() method is called when
the applet is about to terminate).The stop( ) method is always called before destroy( ).
• String getAppletInfo( ): Returns a string that describes the applet.

3. List and explain the components of Delegation Event Model.

• Events:

The Events are the objects that define state change in a source. An event can be generated as a
reaction of a user while interacting with GUI elements. Some of the event generation activities are
moving the mouse pointer, clicking on a button, pressing the keyboard key, selecting an item from the
list, and so on. We can also consider many other user operations as events.
The Events may also occur that may be not related to user interaction, such as a timer expires, counter
exceeded, system failures, or a task is completed, etc. We can define events for any of the applied
actions.

• Event Sources:

Event sources are objects that cause the events to occur due to some change in the property
of the component. Because there can be various types a component can trigger, each must
be registered to a listener to provide a suitable response.

• Event Listener:

An event listener is an object that is invoked when an event triggers. The listeners require
two things; first, it must be registered with a source; however, it can be registered with
several resources to receive notification about the events. Second, it must implement the
methods to receive and process the received notifications.

The methods that deal with the events are defined in a set of interfaces. These
interfaces can be found in the java.awt.event package.

For example, the MouseMotionListener interface provides two methods when the mouse is
dragged and moved. Any object can receive and process these events if it implements the
MouseMotionListener interface.

4. List and explain any three Event Listener Interfaces.

• The ActionListener Interface:

This interface defines the actionPerformed( ) method that is invoked when an action event occurs.
Its general form is shown here:

void actionPerformed(ActionEvent ae)

• The KeyListener Interface:

This interface defines three methods. The keyPressed( ) and keyReleased( ) methods are
invoked when a key is pressed and released, respectively. The keyTyped( ) method is invoked when a
character has been entered.

For example, if a user presses and releases the A key, three events are generated in
sequence: key pressed, typed, and released. If a user presses and releases the HOME key, two key
events are generated in sequence: key pressed and released.

The general forms of these methods are shown here:

void keyPressed(KeyEvent ke)

void keyReleased(KeyEvent ke)

void keyTyped(KeyEvent ke)


• The MouseListener Interface:

This interface defines five methods. If the mouse is pressed and released at the same point,
mouseClicked( ) is invoked. When the mouse enters a component, the mouseEntered( ) method is
called. When it leaves, mouseExited( ) is called. The mousePressed( ) and mouseReleased( ) methods
are invoked when the mouse is pressed and released, respectively.

The general forms of these methods are shown here:

void mouseClicked(MouseEvent me)

void mouseEntered(MouseEvent me)

void mouseExited(MouseEvent me)

void mousePressed(MouseEvent me)

void mouseReleased(MouseEvent me)

5. Explain how any two Mouse events are handled in Applets with suitable example.

i. The MouseListener Interface

The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. It has five methods. If a mouse is pressed & released at the same point mouseClicked( )
is invoked. When the mouse enters a component, the mouseEntered( ) method is called. When it
leaves, mouseExited( ) is called. The mousePressed( ) & mouseReleased( ) methods are invoked when
the mouse is pressed & released.

Methods of MouseListener interface:

1. mouseClicked(MouseEvent e);
2. mouseEntered(MouseEvent e);
3. mouseExited(MouseEvent e);
4. mousePressed(MouseEvent e);
5. mouseReleased(MouseEvent e);

ii. The MouseMotionListener Interface

The interface MouseMotionListener is used for receiving mouse motion events on a component.
This interface defines two methods. The mouseDragged( ) method is called multiple times as the
mouse is dragged. The mouseMoved( ) method is called multiple times as the mouse is moved. Their
general forms are;

1. mouseDragged(MouseEvent e)

2. mouseMoved(MouseEvent e)
Program example:

import java.awt.*;

import java.awt event.*;

import java.applet.*;

/*

<applet code="Move" width=600 height=500> </applet>

*/

public class Mouse extends Applet implements MouseListener

int x = 0 , y = 10 ;

String message = “ Mouse Events”;

Public void Init( ) {

addMouseListener (this) ;

setBackground (color.BLACK); }

Public void MouseEntered (MouseEvent me) {

setBackground (color.WHITE); }

Public void MouseClicked (MouseEvent me) {

setBackground (color.RED); }

6. Explain how any two keys events are handled in applets with suitable example.

Ans: key events in java ;

KeyEvent : is triggered whenever a key is pressed on the keyboard.

WindowEvent : is triggered whenever a window-related operation is performed, such as


closing or activating a window.

TextEvent : is triggered when a text field is modified.

Program Example:

import java.awt.*;

import java.awt.event.*;
import java.applet.*;

/*

<applet code="SimpleKey" width=300 height=100> </applet>

*/

public class SimpleKey extends Applet

implements KeyListener {

String msg = "";

int X = 10, Y = 20;

// output coordinates

public void init() {

addKeyListener(this);

public void keyPressed(KeyEvent ke) {

showStatus("Key Down");

public void keyReleased(KeyEvent ke) {

showStatus("Key Up");

7. Write example explain creating frame window in applet.

Creating a new frame window from within an applet is actually quite easy.
The following steps may be used to do it,
• Create a subclass of Frame
• Override any of the standard window methods,such as init(),start(),stop(),and paint().
• Implement the windowClosing() method of the windowlistener interface,calling
setVisible(false)when the window is closed
• Once you have defined a Frame subclass,you can create an object of that class.But it will note
be initially visible
• When created,the window is given a default height and width
• You can set the size of the window explicitly by calling the setSize() method

Program Example :
import java.awt.*;
import java.awt.event.*;

import java.applet.*;

/*

<applet code="AppletFrame" width=300 height=50> </applet>

*/

// Create frame window.

public class AppletFrame extends Applet

Frame f;

public void init() {

f = new SampleFrame("A Frame Window");

f.setSize(250, 250);

f.setVisible(true);

public void start() { f.setVisible(true);

public void stop() { f.setVisible(false);

public void paint(Graphics g) {

g.drawString("This is in applet window", 10, 20);

8. Explain the purpose of JButton and Explain any four methods associated with it.

Ans: The JButton class is used to create a labeled button that has platform independent
implementation. JButton class provides the functionality of a push button. JButton allows an icon, a
string, or both to be associated with the push button. It inherits AbstractButton class.
Methods Description

void setText(String s) It is used to set specified text on button

String getText() It is used to return the text of the button.

void setEnabled(boolean b) It is used to enable or disable the button.

void setIcon(Icon b) It is used to set the specified Icon on the button.

Icon getIcon() It is used to get the Icon of the button.

void setMnemonic(int a) It is used to set the mnemonic on the button.

void addActionListener(ActionListener a) It is used to add the action listener to this object.

9. Explain the use of JTextField and any four methods associated with it.

JTextField is the simplest Swing text component. It is also probably its most widely used text
component. JTextField allows you to edit one line of text. It is derived from JTextComponent, which
provides the basic functionality common to Swing text components. JTextField uses the Document
interface for its model.

Three of JTextField’s constructors are shown here:

JTextField(int cols)

JTextField(String str, int cols)

JTextField(String st

Methods

Void addActionListener(ActionListener l) :It is used to add the specified action listener to receive
action events from this textfield.

Action getAction(): It returns the currently set Action for this ActionEvent source, or null if no Action
is set.

Void setFont(Font fi) : It is used to set the current font.

Void removeActionListener(ActionListener l): It is used to remove the specified action listener so


that it no longer receives action events from this textfield.

Java JTextField Example:


Import javax.swing.*;

Class TextFieldExample

Public static void main(String args[])

JFrame f= new JFrame(“TextField Example”);

JTextField t1,t2;

T1=new JTextField(“Welcome to Javatpoint.”);

T1.setBounds(50,100, 200,30);

T2=new JTextField(“AWT Tutorial”);

T2.setBounds(50,150, 200,30);

f.add(t1); f.add(t2);

f.setSize(400,400);

f.setLayout(null);

f.setVisible(true);

10. Explain the use of JList and any for methods associated with it.

In Swing, the basic list class is called JList. It supports the selection of one or more items
from a list. Although the list often consists of strings, it is possible to create a list of just about any
object that can be displayed. JList is so widely used in Java that it is highly unlikely that you have not
seen one before.

Commonly used methods:

Void addListSelectionListener(ListSelectionListener listener): It is used to add a listener to the list,


to be notified each time a change to the selection occurs.

int getSelectedIndex(): It is used to return the smallest selected cell index.

ListModel getModel(): It is used to return the data model that holds a list of items displayed by the
JList component.

void setListData(Object[] listData): It is used to create a read-only ListModel from an array of


objects.

11: Illustrate the use of ILabel with suitable example.

The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent tclass.
It is called a passive control as it does not create any event when it is accessed. To create a label, we
need to create the object of Label class.

The java.awt.Component class has following fields:

Static int LEFT: It specifies that the label should be left justified.

Static int RIGHT: It specifies that the label should be right justified.

Static int CENTER: It specifies that the label should be placed in center.

Program:

Import java.awt.*;

Public class LabelExample {

Public static void main(String args[])

// creating the object of Frame class and Label class

Frame f = new Frame (“Label example”);

Label l1, l2;

// initializing the labels

L1 = new Label (“First Label.”);

L2 = new Label (“Second Label.”);

// set the location of label

L1.setBounds(50, 100, 100, 30);

L2.setBounds(50, 150, 100, 30);

// adding labels to the frame

f.add(l1);

f.add(l2);

// setting size, layout and visibility of frame

f.setSize(400,400);
f.setLayout(null);

f.setVisible(true);

12. List and explain different methods associated with JCheckBox.

The JcheckBox class is used to create a checkbox. It is used to turn an option on(true) or
off(false). Clicking on a checkbox changes its state from “on” to ”off” or from “off” to “on”. It inherits
JtoggleButton class.

Commonly used methods:

• setIcon(Icon i) : sets the icon of the checkbox to the given icon.


• setText(String s) : sets the text of the checkbox to the given text.
• setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or vice
versa.
• getIcon() : returns the image of the checkbox.

Example:

import javax.swing.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
checkBox1.setBounds(100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
JCheckBox checkBox2 = new JCheckBox("Java", true);
checkBox2.setBounds(100,150, 50,50);
f.add(checkBox1);
f.add(checkBox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}

13. Explain the use of JCombobox and any for methods associated with it.

JComboBox is a part of Java Swing package. JComboBox inherits JComponent class .


JComboBox shows a popup menu that shows a list and the user can select a option from that specified
list .

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. Thus, changing a selection means that two item events will occur: one for the
deselected item and another for the selected item.

Methods:

• addItem(E item) : adds the item to the JComboBox.


• addItemListener( ItemListener l) : adds a ItemListener to JComboBox.
• getItemAt(int i) : returns the item at index i.
• getItemCount(): returns the number of items from the list.

14. Explain different methods associate with JRadioButton control with suitable example.

We use the JRadioButton class to create a radio button. Radio button is use to select one
option from multiple options. It is used in filling forms, online objective papers and quiz.

We add radio buttons in a ButtonGroup so that we can select only one radio button at a time. We
use “ButtonGroup” class to create a ButtonGroup and add radio button in a group.

Methods Used :

• JRadioButton() : Creates a unselected RadioButton with no text.


• JButton(String s) : Creates a JButton with a specific text.
• JLabel(String s) : Creates a JLabel with a specific text.
• ButtonGroup() : Use to create a group, in which we can add JRadioButton.
• isSelected() : it will return a Boolean value true or false, if a JRadioButton is selected it Will
return true otherwise false.

Example:
import javax.swing.*; //import swing class

public class RadioButtonExample

JFrame f;

RadioButton() //constructor

f = new JFrame(); //instance of frame

JRadioButton r1=new JRAdioButton(“Yes”);

JRadioButton r2=new JRAdioButton(“No”);

JButtonGroup Jb=new JButtonGroup();

r1.setBounds(70,50,100,30); //position

r2.setBounds(70,50,100,30);

Jb.add(r1); //adds the button to the group

Jb.add(r2);

f.add(r1);

f.add(r1);

f.setVisible(true); // display the frame

public static void main(String args[])

new RadioButton();

15. Explain with example creating a Frame window in Applet.

Creating a new frame window from within an applet is actually quite easy.
The following steps may be used to do it,
• Create a subclass of Frame
• Override any of the standard window methods,such as init(),start(),stop(),and paint().
• Implement the windowClosing() method of the windowlistener interface,calling
setVisible(false)when the window is closed
• Once you have defined a Frame subclass,you can create an object of that class.But it will note
be initially visible
• When created,the window is given a default height and width
• You can set the size of the window explicitly by calling the setSize() method

Program Example :

import java.awt.*;
import java.awt.event.*;

import java.applet.*;

/*

<applet code="AppletFrame" width=300 height=50> </applet>

*/

// Create frame window.

public class AppletFrame extends Applet

Frame f;

public void init() {

f = new SampleFrame("A Frame Window");

f.setSize(250, 250);

f.setVisible(true);

public void start() { f.setVisible(true);

public void stop() { f.setVisible(false);

public void paint(Graphics g) {

g.drawString("This is in applet window", 10, 20);

}
16. Write a note on Swing Components and Containers.
Swing components are derived from the JComponent class. (The only exceptions
to this are the four top-level containers, described in the next section.) 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. The following table shows the class names for Swing components (including those used as containers).

Eg: JList, JButton, JCheckBox etc.

A container holds a group of components. Thus, a container is a special type of component that is

designed to hold other components. Furthermore, in order for a component to be displayed, it must be held

within a container. Thus, all Swing GUIs will have at least one container.

Containers are of two types:

1. Top level Containers

• It inherits Component and Container of AWT.


• It cannot be contained within other containers.
• Heavyweight.

Example: JFrame, JDialog, JApplet

2. Lightweight Containers

• It inherits JComponent class.


• It is a general purpose container.
• It can be used to organize related components together.

Example: JPanel

17. Write and explain a simple swing application program.

// A simple Swing application.

import javax.swing.*;

class SwingDemo {

SwingDemo() {

JFrame jfrm = new JFrame("A Simple Swing Application"); // Create a new JFrame container.
jfrm.setSize(275, 100); // Give the frame an initial size.

jfrm.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Terminate the program when the


user closes the application.

JLabel jlab = new JLabel(" Swing means powerful GUIs."); // Create a text-based label.

jfrm.add(jlab); // Add the label to the content pane.

jfrm.setVisible(true); // Display the frame.

public static void main(String args[]) { // Create the frame on the event dispatching
thread.

SwingUtilities.invokeLater(new Runnable() {

public void run() {

new SwingDemo();

}}}

You might also like