Java Unit IV Answers
Java Unit IV Answers
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.
In addition to displaying information in its window, an applet can also output a message to the status window of the browser or
applet viewer on which it is running. To do so, call showStatus( ) with the string that you want displayed.
import java.awt.*;
import java.applet.*;
/*
<applet code="StatusWindow" width=300 height=300>
</applet>
*/
public class StatusWindow extends Applet
{
public void init()
{ setBackground(Color.cyan);
}
// Display msg in applet window.
public void paint(Graphics g)
{
g.drawString("This is in the applet window.", 10, 20);
showStatus("This is shown in the status window.");
}
}
Output:
The applet life cycle can be defined as the process of how the object is created, started, stopped, and destroyed during the
entire execution of its application. It basically has five core methods namely init(), start(), stop(), paint() and destroy().These
methods are invoked by the browser to execute.
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
}
}
14. what is an event?give example
Event: Change in the state of an object is known as event i.e. event describes the change in state of source. Events are
generated as result of user interaction with the graphical user interface components. For example, clicking on a button, moving
the mouse, entering a character through keyboard, selecting an item from list, scrolling the page are the activities that causes
an event to happen.
Foreground Events -Those events which require the direct interaction of user. They a regenerated as consequences of a
person interacting with the graphical components in Graphical User Interface. For example, clicking on a button, moving the
mouse, entering a character through keyboard, selecting an item from list, scrolling the page etc.
Background Events - Those events that require the interaction of end user are known as background events. Operating system
interrupts, hardware
Listeners : A listener is an object that listens to the event. A listener gets notified when an event occurs. It is an interface that
handles the event. That is, the event is caught by the listener and when caught, immediately executes some method filled up
with code. Other way, the method called gives life to the user action.
The methods that receive and process events are defined in a set of interfaces, such as those found in java.awt.event. For
example, the MouseMotionListener interface defines two methods to receive notifications when the mouse is dragged or
moved. Any object may receive and process one or both of these events if it provides an implementation of this interface
The msg parameter specifies the string that will be displayed inside the button. When a push button is pressed, it generates an
ActionEvent.
get Text() method is used to recover (or retrieve) the text of a component like Text Field at the time of running.
Set Text() method is used to change the display text of a component like a label, text field, or button at run time
4 marks
An Applet Skeleton:
Four methods—init( ), start( ), stop( ), and destroy( )—aredefined by Applet. 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
}
}
Applet Initialization and Termination:
It is important to understand the order in which the various methods shown in theskeleton are called. When an applet
begins, the AWT calls the following methods, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
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( ).
Following is the list of commonly used event classes. Sr. No. Control & Description
1 AWTEvent
It is the root event class for all AWT events. This class and its
subclasses supercede the original java.awt.Event class.
2 ActionEvent
The ActionEvent is generated when button is clicked or the item
of a list is double clicked.
3 InputEvent
The InputEvent class is root event class for all component-level
input events.
4 KeyEvent
On entering the character the Key event is generated.
5 MouseEvent
This event indicates a mouse action occurred in a component.
6 TextEvent
The object of this class represents the text events.
7 WindowEvent
The object of this class represents the change in state of a
window.
8 AdjustmentEvent
The object of this class represents the adjustment event emitted
by Adjustable objects.
9 ComponentEvent
The object of this class represents the change in state of a
window.
10 ContainerEvent
The object of this class represents the change in state of a
window.
11 MouseMotionEvent
The object of this class represents the change in state of a
window.
12 PaintEvent
The object of this class represents the change
This interface defines seven methods. The windowActivated( ) and windowDeactivated( ) methods are invoked when a window
is activated or deactivated, respectively. If a window is iconified, the windowIconified( ) method is called. When a window is
deiconified, the windowDeiconified( ) method is called. When a window is opened or closed, the windowOpened( ) or
windowClosed( ) methods are called, respectively. The windowClosing( ) method is called when a window is being closed. The
general forms of these methods are
void windowActivated(WindowEvent we)
void windowClosed(WindowEvent we)
void windowClosing(WindowEvent we)
void windowDeactivated(WindowEvent we)
void windowDeiconified(WindowEvent we)
void windowIconified(WindowEvent we)
void windowOpened(WindowEvent we)
The FocusListener Interface
This interface defines two methods. When a component obtains
keyboard focus, focusGained( )is invoked.
When a component loses keyboard focus, focusLost( ) is called. Their generalforms are shown here:
void focusGained(FocusEvent fe)
void focusLost(FocusEvent fe)
The ItemListener Interface
This interface defines the itemStateChanged( ) method that is invoked when the state of an item changes. Its general form is
shown here:
void itemStateChanged(ItemEvent ie)
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)
The MouseMotionListener Interface
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 mouseis moved.
general forms are shown here:
void mouseDragged(MouseEvent me)
void mouseMoved(MouseEvent me)
The MouseWheelListener Interface
This interface defines the mouseWheelMoved( ) method that is invoked when the mouse wheel is moved. Its general form is
shown here:
void mouseWheelMoved(MouseWheelEvent mwe)
The TextListener Interface
This interface defines the textChanged( ) method that is invoked when a change occurs
in a text area or text field. Its general form is shown here:
void textChanged(TextEvent te)
6. Explain how any two mouse events are handled in Applets with suitable examples
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
setBackground(Color.YELLOW);
addMouseListener(this);
addMouseMotionListener(this);
}
C:\>javac MouseEventsDemo.java
C:\>appletviewer MouseEventsDemo.java
7. Explain how any two key events are handled in Applets with suitable example
8. Explain the purpose of Jbutton and explain any four methods associated with it
The JButton class is used to build a platform-independent labeled button. When the button is pressed, the application performs
some action. It is inherited from the AbstractButton class.
Methods Description
9.Explain the use of JTextfield and any four methods associate with it
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent. It provides functionality that is
common to Swing text components. One of its subclasses is JTextField, which allows you to edit one line of text. Some of its
constructors are shown here:
JTextField( ) JTextField(int cols)
JTextField(String s, int cols) JTextField(String s)
field.
Here, s is the string to be presented, and cols is the number of columns in the text
The following example illustrates how to create a text field. The applet begins by
getting its content pane, and then a flow layout is assigned as its layout manager. Next, a
JTextField object is created and is added to the content pane.
Example:
import javax.swing.*; import java.awt.*; import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JLabel jl, jl2; JTextField jtf; MyFrame()
{
setLayout(new FlowLayout()); jl=new JLabel("Enter your name"); jl2=new JLabel();
jtf=new JTextField("PVPSIT",15);
add(jl);
add(jtf);
add(jl2); jtf.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
jl2.setText(jtf.getText());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame(); f.setTitle("Welcome to Swings"); f.setSize(500,500); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
10.Explain the use of JList and any four methods associated with it
JList class is useful to create a list which displays a list of items and allows the user to select one or more items.
– Constructors
• JList()
• JList(Object arr[])
• JList(Vector v)
– Methods
• getSelectedIndex() – returns selected item index
• getSelectedValue() – to know which item is selected in the list
• getSelectedIndices() – returns selected items into an array
• getSelectedValues() – returns selected items names into an array
//frame
static JFrame f;
//lists
static JList b;
//main class
public static void main(String[] args)
{
//create a new frame
f = new JFrame("frame");
//create a object
solve s=new solve();
//create a panel
JPanel p =new JPanel();
//create list
b= new JList(week);
f.add(p);
//set the size of frame
f.setSize(400,400);
f.show();
}
// frame
static JFrame f;
// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");
// create checkbox
JCheckBox c1 = new JCheckBox("checkbox 1");
JCheckBox c2 = new JCheckBox("checkbox 2");
f.show();
}
}
Output :
13. Explain different methods associated with JRadioButton control with suitable
example
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of AbstractButton. Its
immediate superclass is JToggleButton, which provides support for two-state buttons. Some of its constructors are shown
here:
JRadioButton(Icon i) JRadioButton(Icon i, boolean state) JRadioButton(String s) JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
Here, i is the icon for the button. The text is specified by s. If state is true, the button is initially selected. Otherwise, it is
not.
Radio buttons must be configured into a group. Only one of the buttons in that group can be selected at any time. For
example, if a user presses a radio button that is in a group, any previously selected button in that group is automatically
deselected. The ButtonGroup class is instantiated to create a button group. Its default constructor is invoked for this
purpose. Elements are then added to the button group via the following method:
void add(AbstractButton ab)
Here, ab is a reference to the button to be added to the group.
Radio button presses generate action events that are handled by actionPerformed( ). The getActionCommand( ) method
returns the text that is associated with a radio button and uses it to set the text field.
Example:
import javax.swing.*; import java.awt.*; import java.awt.event.*;
class MyFrame extends JFrame implements ActionListener
{
JRadioButton jrb,jrb1,jrb2; JLabel jl;
MyFrame()
{
setLayout(new FlowLayout()); jl=new JLabel();
jrb=new JRadioButton("VRSEC"); jrb1=new JRadioButton("PVPSIT"); jrb2=new JRadioButton("BEC" );
add(jrb); add(jrb1); add(jrb2); add(jl);
ButtonGroup bg=new ButtonGroup(); bg.add(jrb); bg.add(jrb1); bg.add(jrb2); 12
jrb.addActionListener(this); jrb1.addActionListener(this); jrb2.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
jl.setText("You Selected :"+ae.getActionCommand());
}
}
class FrameDemo
{
public static void main(String arg[])
{
MyFrame f=new MyFrame(); f.setTitle("Welcome to Swings"); f.setSize(500,500); f.setVisible(true);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
First, create a subclass of Frame. Next, override any of the standard applet methods, such as init( ), start( ), and stop( ), to show or hide th
frame as needed. Finally, implement the windowClosing( ) method of the WindowListener interface, calling setVisible(false) when the window
closed.
Once you have defined a Frame subclass, you can create an object of that class. This causes a frame window to come into existence, but it w
not be initially visible. You make it visible by calling setVisible( ). When created, the window is given a default height and width. You can set th
size of the window explicitly by calling the setSize( ) method.
The following applet creates a subclass of Frame called SampleFrame. A window of this subclass is instantiated within the init( ) meth
of AppletFrame. Notice that SampleFrame calls Frame’s constructor. This causes a standard frame window to be created with the title passe
in title. This example overrides the applet’s start( ) and stop( ) methods so that they show and hide the child window, respectively. This causes th
window to be removed automatically when you terminate the applet, when you close the window, or, if using a browser, when you move
another page. It also causes the child window to be shown when the browser returns to the applet .
//Create a child frame window from within an applet.
import java.awt.*;
import java.awt.event.*;
import java.applet.*; /*
*/
As the name implies, a top-level container must be at the top of a containment hierarchy. A top-level container is not contained
within any other container.
Furthermore, every containment hierarchy must begin with a top-level container. The one most commonly used for applications
are JFrame and JApplet.
Unlike Swing’s other components, the top-level containers are heavyweight.
Because they inherit AWT classes Component and Container.
Whenever we create a top level container four sub-level containers are automatically created:
Glass pane (JGlass)
Root pane (JRootPane)
Layered pane (JLayeredPane)
Content pane
Glass pane: This is the first pane and is very close to the monitor’s screen. Any components to be displayed in the foreground
are attached to this glass pane. To reach this glass pane we use getGlassPane() method of JFrame class, which return
Component class object.
Root Pane: This pane is below the glass pane. Any components to be displayed in the background are displayed in this frame.
To go to the root pane, we can use getRootPane() method of JFrame class, which returns JRootPane object.
Layered pane: This pane is below the root pane. When we want to take several components as a group, we attach them in the
layered pane. We can reach this pane by calling getLayeredPane() method of JFrame class which returns JLayeredPane class
object.
Conent pane: This is bottom most of all, Individual components are attached to this pane. To reach this pane, we can call
getContentPane() method of JFrame class which returns Container class object.
2. Lightweight containers – containers do inherit JComponent. An example of a lightweight container is JPanel, which is a
general-purpose container. Lightweight containers are often used to organize and manage groups of related components.