0% found this document useful (0 votes)
4 views

Java Unit IV Answers

The document provides instructions on how to create and run a Java applet named SimpleApplet, including the necessary HTML code and attributes for embedding the applet. It explains the purpose of various methods in applet programming, such as paint(), repaint(), stop(), destroy(), and update(), as well as the concept of events and listeners in Java's event handling model. Additionally, it covers the applet lifecycle, the delegation event model, and lists key event classes and listener interfaces in the AWT framework.

Uploaded by

classicsiddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Java Unit IV Answers

The document provides instructions on how to create and run a Java applet named SimpleApplet, including the necessary HTML code and attributes for embedding the applet. It explains the purpose of various methods in applet programming, such as paint(), repaint(), stop(), destroy(), and update(), as well as the concept of events and listeners in Java's event handling model. Additionally, it covers the applet lifecycle, the delegation event model, and lists key event classes and listener interfaces in the AWT framework.

Uploaded by

classicsiddu
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

4.

write HTML file to run an applet program named simple


Executing the applet within a Java-compatible Web browser(demonstrates you to run SimpleApplet.java):
Compiling: javac SimpleApplet.java
Create an Html file and embeded Applet tag in html file.
Attributes in applet tag:
Code(attribute):specify name of applet class to load into browser.
Width(attribute):width of an applet.
Height(attribute):height of an applet.
SimpleApplet.html
<html>
<body>
<applet code="SimpleApplet" width=300 height=100></applet>
</body>
</html>
When you open SimpleApplet.html , SimpleApplet.class applet is loaded into browser.
Note: The Browser must be java enabled to load applet programe.

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

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.

8. what is the purpose of repaint method?


Whenever your applet needs to update the information displayed in its window, it simply calls repaint( ).The repaint( ) method
is defined by the AWT. It causes the AWT run-time system to execute a call to your applet’s update( ) method, which, in its
default implementation, calls paint( ).
The simplest version of repaint( ) is shown here:
void repaint( )
This version causes the entire window to be repainted. The following version specifies a region that will be repainted:
void repaint(int left, int top, int width, int height)
Here, the coordinates of the upper-left corner of the region are specified by left and top, and the width and height of the region
are passed in width and height. These dimensions are specified in pixels. You save time by specifying a region to repaint.
The other two versions of repaint():
void repaint(long maxDelay)
void repaint(long maxDelay, int x, int y, int width, int height)
Here, maxDelay specifies the maximum number of milliseconds that can elapse before update( ) is called.

9.Differentiate stop and destroy methods


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( ).

10. what is the purpose of update method


An update() method is called on calling the repaint method.
- The default implementation of the update() method clears the screen and calls the paint() method.
- The graphics instance is valid only within the context of the update method() returns.
- This method is called in response to repaint() request.
- The default implementation is provided by the component class which erases the background and calls the paint() method

11. Write the purpose of showstatus() method?

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.

// Using the Status Window.

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:

12. List the superclasses of Applet defined by AWT?

13.List any four methods defined by Applet?

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

15. what is the listener?

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.

15. what is the 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.

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

16.List the key features of swing GUI


A Swing GUI consists of two key items: components and containers.
However, this distinction is mostly conceptual because all containers are also components. The difference between the two is
found in their intended purpose: As the term is commonly used, 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. Thus, all Swing GUIs will have at
least one container. Because containers are components, a container can also hold other containers. This enables Swing to
define what is called a containment hierarchy, at the top of which must be a top-level container

17. what happens when the constructor Jbutton(String msg) is called?


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

The msg parameter specifies the string that will be displayed inside the button. When a push button is pressed, it generates an
ActionEvent.

18. what is the purpose of setText() and getText() methods?

 Get Text() method is given as:-

 get Text() method is used to recover (or retrieve) the text of a component like Text Field at the time of running.

 e.g : name.get Text().

 Set Text() method is given as:

Set Text() method is used to change the display text of a component like a label, text field, or button at run time

 e.g in.set Text(""+name)

4 marks

1. Write the complete Applet skeleton with example

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( ).

3.List and explain the components of delegation event model?

The 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 an event is 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 original 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.
Events
In the delegation model, an event is an object that describes a state change in a source.
Among other causes, an event 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.
Events may also occur that are not directly caused by interactions with a user interface.
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. Here is the general form:
public void addTypeListener (TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener. For example, the method that registers a
keyboard event listener is called addKeyListener( ). The method that registers a mouse motion listener is called
addMouseMotionListener( ).
When an event occurs, all registered listeners are notified and receive a copy of the event object. This is known as
multicasting the event. In all cases, notifications are sent only to listeners that register to receive them.
Some sources may allow only one listener to register. The general form of such a method is this:
public void addTypeListener(TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener.
When such an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest in a specific type of event. The general
form of such a method is this:
public void removeTypeListener(TypeListener el )
Here, Type is the name of the event, and el is a reference to the event listener. For example, to remove a keyboard
listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that generates events. For example, the Component
class provides methods to add and remove keyboard and mouse event listeners.
Event Listeners
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.
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.

4. List and explain any 6 event classes in java.awt.event

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

5.List and explain different event listener interfaces


Following table lists several commonly used listener interfaces and provide a brief description of the methods that they
define.

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 ContainerListener Interface
This interface contains two methods. When a component is added to a container, componentAdded( ) is invoked. When a
component is removed from a container, componentRemoved( ) is invoked. Their general forms are shown here:
void componentAdded(ContainerEvent ce)
void componentRemoved(ContainerEvent ce)
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 WindowListener Interface

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.*;

/* <APPLET CODE="MouseEventsDemo.class" WIDTH="300" HEIGHT="300">


</APPLET>
*/

public class MouseEventsDemo extends Applet implements MouseListener, MouseMotionListener {

String message = "";

public void init() {

setBackground(Color.YELLOW);
addMouseListener(this);
addMouseMotionListener(this);
}

public void paint(Graphics g) {


g.drawString(message, 50, 50);
}

public void mouseEntered(MouseEvent me) {


setBackground(Color.PINK);
message = "Mouse Entered: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseExited(MouseEvent me) {


setBackground(Color.RED);
message = "Mouse Exited: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseClicked(MouseEvent me) {


setBackground(Color.CYAN);
message = "Mouse Clicked: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mousePressed(MouseEvent me) {


setBackground(Color.MAGENTA);
message = "Mouse Pressed: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseReleased(MouseEvent me) {


setBackground(Color.GREEN);
message = "Mouse Released: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseMoved(MouseEvent me) {


setBackground(Color.ORANGE);
message = "Mouse Moved: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}

public void mouseDragged(MouseEvent me) {


setBackground(Color.GRAY);
message = "Mouse Dragged: (" + me.getX() + ", " + me.getY() + ")";
repaint();
}
}
OUTPUT

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 of AbstractButton Class

Methods Description

void setText(String s) Set specified text on the button

String getText() Return the text of the button.

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

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

Icon getIcon() It get the Icon of the button.

void setMnemonic(int a) Set the mnemonic on the button.

void addActionListener(ActionListener a) Add the action listener to this object.


Also read about swing component in java
How to Create JButton in Java
import javax.swing.*;
public class Jbutton_Class{
public static void main(String[] args) {
JFrame f=new JFrame("JButton ");
JButton b=new JButton("Click Here");
b.setBounds(85,110,105,50);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
Output

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

java Program to create a simple JList


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame
{

//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 a new label


JLabel l= new JLabel("select the day of the week");

//String array to store weekdays


String week[]= { "Monday","Tuesday","Wednesday",
"Thursday","Friday","Saturday","Sunday"};

//create list
b= new JList(week);

//set a selected index


b.setSelectedIndex(2);

//add list to panel


p.add(b);

f.add(p);
//set the size of frame
f.setSize(400,400);

f.show();
}

11.Illustrate the use of Label with suitable example


ImageIcon icon = createImageIcon("images/middle.gif");
...
label1 = new JLabel("Image and Text",
icon,
JLabel.CENTER);
//Set the position of the text, relative to the icon:
label1.setVerticalTextPosition(JLabel.BOTTOM);
label1.setHorizontalTextPosition(JLabel.CENTER);

label2 = new JLabel("Text-Only Label");


label3 = new JLabel(icon);

12.List and explain different methods associated with JcheckBox


1. setIcon(Icon i) : sets the icon of the checkbox to the given icon
2. setText(String s) :sets the text of the checkbox to the given text
3. setSelected(boolean b) : sets the checkbox to selected if boolean value passed is true or vice versa
4. getIcon() : returns the image of the checkbox
5. getText() : returns the text of the checkbox
6. updateUI() : resets the UI property with a value from the current look and feel.
7. getUI() : returns the look and feel object that renders this component.
8. paramString() : returns a string representation of this JCheckBox.
9. getUIClassID() : returns the name of the Look and feel class that renders this component.
10. getAccessibleContext() : gets the AccessibleContext associated with this JCheckBox.
11. isBorderPaintedFlat() : gets the value of the borderPaintedFlat property.
12. setBorderPaintedFlat(boolean b) : sets the borderPaintedFlat property,
The following programs will illustrate the use of JCheckBox
1. Program to create a simple checkbox using JCheckBox

// java Program to create a simple checkbox using JCheckBox


import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
class solve extends JFrame {

// frame
static JFrame f;

// main class
public static void main(String[] args)
{
// create a new frame
f = new JFrame("frame");

// set layout of frame


f.setLayout(new FlowLayout());

// create checkbox
JCheckBox c1 = new JCheckBox("checkbox 1");
JCheckBox c2 = new JCheckBox("checkbox 2");

// create a new panel


JPanel p = new JPanel();

// add checkbox to panel


p.add(c1);
p.add(c2);

// add panel to frame


f.add(p);

// set the size of frame


f.setSize(300, 300);

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);
}
}

14. Explain with example creating a Frame window in Applet

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.*; /*

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

*/

15. write a note on swing components and containers


A Swing GUI consists of two key items: components and containers.
However, this distinction is mostly conceptual because all containers are also components. The difference between the two is
found in their intended purpose: As the term is commonly used, 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. Thus, all Swing GUIs will have at
least one container. Because containers are components, a container can also hold other containers. This enables Swing to
define what is called a containment hierarchy, at the top of which must be a top-level container.
Components:
In general, Swing components are derived from the JComponent class. 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. All of Swing’s components are represented by classes defined within the package javax.swing. The
following figure shows hierarchy of classes of javax.swing.
Containers:
Swing defines two types of containers.
1. Top-level containers/ Root containers: JFrame, JApplet,JWindow, and JDialog.

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.

You might also like