0% found this document useful (0 votes)
35 views51 pages

Unit Ii

The document discusses the AWT class hierarchy in Java. It explains that: 1) The AWT class hierarchy is headed by the Component class, with subclasses including Container, Panel, Window and Frame. 2) Container can contain other components. Panel is a subclass of container without title/menu bars. 3) Window and Frame are subclasses of container that create top-level windows, with Frame providing title/menu bars.

Uploaded by

moaz.sheikh11
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)
35 views51 pages

Unit Ii

The document discusses the AWT class hierarchy in Java. It explains that: 1) The AWT class hierarchy is headed by the Component class, with subclasses including Container, Panel, Window and Frame. 2) Container can contain other components. Panel is a subclass of container without title/menu bars. 3) Window and Frame are subclasses of container that create top-level windows, with Frame providing title/menu bars.

Uploaded by

moaz.sheikh11
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/ 51

UNIT-II

AWT Class hierarchy


Que:
1. Draw and Explain AWT Class hierarchy.
2. Explain AWT class hierarchy.
3. What is AWT class hierarchy in java?
4. Explain the hierarchy of classes in the java.awt package.
Ans:
 AWT (Abstract Window Toolkit) contains numerous classes and methods that allow us to create
and manage windows.
 AWT classes are contained in the java.awt package. It is one of Java’s largest package.
 The AWT defines windows according to a class hierarchy that adds functionality and specificity
with each level.
 The hierarchy of Java AWT classes are given below :

Component

o Component class is at the top of AWT hierarchy.


o Component is an abstract class that encapsulates all attribute of visual component.
o All user interface elements that are displayed on the screen and that interact with the
user are subclasses of Component.
o It defines over a hundred public methods that are responsible for managing events
such as mouse, keyboard input, positioning and sizing the window and repainting.
o Component object is responsible for remembering the current foreground and
background colors and the currently selected text font.
 Container
o Container is a component in AWT that contains another component like button, text
field, tables etc.
o Container is a subclass of component class.
o A container can also hold sub-containers.
 Panel
o It is a subclass of container and it is the super class of Applet.
o It is a window that does not have a title bar, menu bar or border.
o A Panel is used for displaying Multiple Windows in a Single Window.

o A Panel may have any Layout. By default, it uses FlowLayout.

o Windows for applet is derived from panel.

 Window
o Window is also a sub class of a container.
o Window class creates a top level window. A top-level window is not contained within
any other object, it sits directly on the desktop.
o We won’t create window object directly. We can use a subclass of window called
Frame.
 Frames
o Frame Class is also a sub class of window class.
o Frame Class provides a Special Type of Window which has a title bar, menu bar,
borders and resizing corners.
o It is a container that contains several different components like button, title bar,
textfield, label etc.

Commonly used Methods of Component class


Que:
1. List any four methods provided by Component in Java.

Ans:

 The methods of Component class are widely used in java swing that are given below:
Method Description
public void add(Component c) add a component on another component.
public void setSize(int width,int height) sets size of the component.
public void setLayout(LayoutManager m) sets the layout manager for the component.
public void setVisible(boolean b) sets the visibility of the component. It is by default false.

FRAME in AWT
Que:
1. Write code to create FRAME WINDOW in Applet.
2. How to create a Frame window within an applet? Give an example.
3. How to create a frame window in applet?
4. Define Frame and state two ways to create a frame.
5. Explain the process of creating a frame and adding a button to it.
Ans:

 Frame Class is also a sub class of window class.


 Frame Class provides a Special Type of window which has a title bar, menu bar, borders and
resizing corners.
 It is a container that contains several different components like button, title bar, textfield, label
etc.

Creating a Frame Window in an Applet

 Steps to create a new frame window from within an applet are shown below:

1. Create a subclass of Frame


2. Override any of the standard window methods,such as init(),start(),stop(),and paint().
3. Implement the windowClosing() method of the windowlistener interface, calling setVisible(false)
when the window is closed.
4. Once you have defined a Frame subclass, you can create an object of that class. But it will note be
initially visible.
5. When created, the window is given a default height and width.
6. You can set the size of the window explicitly by calling the setSize() method.

 Example:
 The following applet creates a subclass of Frame called SampleFrame.
 A window of this subclass is instantiated within the init( ) method of AppletFrame.
 This example overrides the applet's start( ) and stop( ) methods so that they
show and hide the child window, respectively.
 This causes the window to be removed automatically when you terminate the applet,
when you close the window, or, if using a browser, when you move to another page.

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

// Create a subclass of Frame.


class SampleFrame extends Frame {

SampleFrame(String title) {
super(title);

MyWindowAdapter adapter = new MyWindowAdapter(this);

addWindowListener(adapter);
}

public void paint(Graphics g) {


g.drawString("This is in frame window", 10, 40);
}
}

class MyWindowAdapter extends WindowAdapter {

SampleFrame sampleFrame;

public MyWindowAdapter(SampleFrame sampleFrame) {


this.sampleFrame = sampleFrame;
}

Public void windowClosing(WindowEvent we) {


sampleFrame.setVisible(false);
}
}

// 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);
}
}
Sample output from this program is shown here:
Creating Frame Window (Creating Window Program using Frame)

 We can create a GUI using Frame in two ways:


1) By extending Frame class
2) By creating the instance of Frame class

1: creating Frame by extending Frame class

 First, create a subclass of Frame.


 Set size of frame using setSize() method and make frame window visible using setVisible()
method.
 Example:

import java.awt.*;

public class SimpleExample extends Frame{

SimpleExample(){

Button b=new Button("Button!!");

b.setBounds(50,50,50,50);

add(b);

setSize(500,300);

setTitle("This is my First AWT example");

setLayout(new FlowLayout());

setVisible(true);
}

public static void main(String args[]){

SimpleExample fr=new SimpleExample();


}
}
Output:

2: creating Frame by creating instance of Frame class

 First create object of frame object.


 When a frame object is created,by default it is invisible. we must call setVisible() method to make
the frame appear on the screen.
 We must set the size of the frame using setSize() or setBound() method.
 Example:

import java.awt.*;

public class Example2 {

Example2()
{

Frame fr=new Frame();

Label lb = new Label("UserId: ");

fr.add(lb);

TextField t = new TextField();

fr.add(t);

fr.setSize(500, 300);

fr.setLayout(new FlowLayout());

fr.setVisible(true);
}
public static void main(String args[])
{
Example2 ex = new Example2();
}
}

Output:

PANEL in AWT
Que:
1. Explain panel in java with example.
Ans:

 Panel is a subclass of container and it is the super class of Applet.

 It is a window that does not have a title bar, menu bar or border.

 A Panel is used for displaying Multiple Windows in a Single Window.

 A Panel may have any Layout. By default, it uses FlowLayout.

 Example:

import java.awt.*;
public class PanelExample {

PanelExample()
{
Frame f= new Frame("Panel Example");

Panel panel=new Panel();


panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);

Button b1=new Button("Button 1");


b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);

panel.add(b1);
panel.add(b2);

f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}

CANVAS in AWT
Que:
1. Explain Canvas class with example.
2. What is CANVAS in AWT? List its Constructors & Methods.
Ans:

 A Canvas class is a sub-class of the Component class.


 This is one another type of window which is used for creating a blank area for drawing graphics or
displaying images.
 When placed over a Frame, displays as a blank area.
 The paint method must be overridden in order to perform custom graphics on the canvas.

Constructors of Canvas
Name Description
Canvas() This constructor creates instance of a Canvas.
Canvas(GraphicsConfiguration This constructor creates instance of a Canvas with the given
config) object of Graphics Configuration.
Methods of Canvas
Method Description
Paint(Graphics g) Paint the Canvas.
Update(Graphics g) Update the Canvas.

 Example:

import java.awt.*;
import java.applet.*;
public class cn extends Applet
{
public void init()
{
MyCanvas c=new MyCanvas();
c.setVisible(true);
add(c);
}
}
class MyCanvas extends Canvas
{
public MyCanvas ()
{
setBackground (Color.GRAY);
setSize(300, 300);
}

public void paint(Graphics g)


{
g.setColor(Color.red);
g.fillOval(0, 0,40,40);
}
}
AWT Controls
Que:
1. List out AWT controls in JAVA.
2. Explain AWT label control.
3. Explain AWT push buttons control.
4. Differentiate Textarea & Textfield.
5. Differentiate Checkbox & Radio Button.
6. Which method associates a checkbox with a particular group?
7. Differentiate checkbox and radio button.
Ans:

 Controls are interactive items we use in applets and frame.


 AWT provides many ready-made and reusable GUI components.
 All the AWT controls inherit from java.awt.*.
 The AWT supports the following controls:-
Component Description
Label It is used to display information that should not be modified by users.
TextField It is useful for obtaining information from users. It considers only single line input.

TextArea It allows for the editing of a multiple lines of text.


Button It is a component that contains a label and that generates an event when it is
pressed.
CheckBox It is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not.

CheckboxGroup It is used to group the set of checkbox.


List It presents the user with a scrolling list of textitems.
Choice It is used to show drop-down menu of choices. Selected choice is shown on the top
of the menu.

Adding and Removing Controls:


 To include a control in a window, you must add it to the window. To do this, you must first create an
instance of the desired control and then add it to a window by calling add( ), which is defined by
Container.
 Once a control has been added, it will automatically be visible whenever its parent window is displayed.
 Sometimes you will want to remove a control from a window when the control is no longer needed. To do
this, call remove( ). This method is also defined by Container.

Label

 It is used to display information that should not be modified by users.


 A label is an object of type Label.

Constructors:
Name Action
Label() Create an empty label.
Label(String) Creates a label initialized with the given string, and aligned left.
Label(String, int) Creates a label with specified text and alignment indicated by the int
argument: Label.LEFT, Label.RIGHT, and Label.CENTER

Methods :
Name Action
int getAlignment() Retrieves a label's alignment setting.
String getText() Retrieves a label's test string.
void setAlignment(int align) Sets the alignment for this label to the specified
alignment. Possible values are Label.LEFT,
Label.RIGHT, and Label.CENTER
void setText(String label) Sets a label's text string.
Example:

Import java.awt.*;
Import java.applet.*;
/*
<applet code="LabelDemo" width=300 height=200>
</applet>
*/
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");

// add labels to applet window

add(one);
add(two);
add(three);
}
}

Output:-

TextField

 It is useful for obtaining information from users. It considers only single line input.
constructor Action
TextField( ) Creates an empty TextField that is 0 characters wide (it will
be resized by the current layout manager).
TextField(int) Creates an empty text field. The integer argument indicates the
minimum number of characters to display.
TextField(String) Creates a text field initialized with the given string.
TextField(String, int) Create a new textfield initialized with the specified text to be
displayed,and wide enough to hold the specified number of
columns.

Methods:
Constructor Action
String getText( ) Returns the text this text field contains (as a string)
Void setText(String) Puts the given text string into the field
int getColumns( ) Returns the width of this text field.
String select(int, int) Selects the text between the two integer positions (positions start
from 0)
Void selectAlI( ) Selects all the text in the field
Boolean isEditable( ) Returns true or false based on whether the text is editable
Void setEditable(boolean) true (the default) enables text to be edited; false freezes the text
Char getEchoChar( ) Returns the character used for masking input
Boolean echoCharIsSet() Returns true or false based on whether the field has a masking
character

Example:

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

/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/

public class TextFieldsDemo extends java.applet.Applet


{
public void init()
{
add(new Label("Enter your Name"»;
add(new TextField("your name here", 45»;

add(new Labe1("Enter your phone number"»;


add(new TextField(12»;
add(new Label("Enter your password"»;
TextFie1d t = new TextField(20);
t.setEchoCharacter('*');
add(t);
}
}

output:-

TextArea

 It allows for the editing of a multiple lines of text.


 Sometimes a single line of text input is not enough for a given task. To handle these situations, the
AWT includes a simple multiline editor called TextArea.

Constructors:

Name Action
TextArea( ) Creates an empty text area 0 rows long and 0 character wide (the
text area will be automatically resized based on the layout manager).
TextArea(int, int) Creates an empty text area with the given number of rows and
columns (characters)
TextArea(String) Creates a text area displaying the given string, which will be sized
according to the current layout manager.
TextArea(String, int, int) Creates a text area displaying the given string and with the given
dimensions

Methods :

Name Action
int getColumns() Returns the width of the text area, In characters or columns
int getRowsO Returns the number of rows in the text area
void insertText(String, Inserts the string at the given position in the text (text positions start
int) at 0).
void replaceText(String, Replaces the text between the given integer positions with the new
int, int) string

Example:
import java.awt.*;
import java.applet.*;
/*
<applet code="TextAreaDemo.class" width=300 height=250>
</applet>
*/
public class TextAreaDemo extends Applet {

TextArea tl =new TextArea("Hello", 1, 30);


TextArea t2 =new TextArea("t2", 4, 30);

public void Init()


{
add(tl);
add(t2);
}
}

Output:

Buttons
 The most widely used control is the push button. A push button is a component that contains a label
and that generates an event when it is pressed.
 Push buttons are objects of type Button.

Constructors
Name Action
Button( ) Creates an empty button with no label
Button(String) Creates a button with the given string object as a label.

Methods
Name Action
String getLabel( ) Get the label of this Button instance
Void setLabel(string) Set the label of this Button instance
Void setEnable(boolean) Enable or disable this Button. Disabled Button cannot be
Clicked.

Example:
import java.awt.event.*;
import java.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/

public class ButtonDemo extends Applet


{
Button yes,no,maybe;
public void init()
{
yes = new Button("Yes");
no = new Button("No");
maybe = new Button("Undecided");
add(yes);
add(no);
add(maybe);

}
}

Output:

Check Boxes
 A check box is a control that is used to turn an option on or off.
 It consists of a small box that can either contain a check mark or not.
 There is a label associated with each check box that describes what option the box represents.
 You change the state of a check box by clicking on it. Check boxes can be used individually or as part
of a group.
 Check boxes are objects of the Checkbox class.

Constructors:
Name Action
Checkbox( ) Creates a check box whose label is initially blank. The state
of the check box is unchecked.
1. Checkbox(String str) Creates a checkbox whose label is specified by str.
2. Checkbox(String str, boolean on) Allows you to set the initial state of the check box. If on is
true, the check box is initially checked otherwise, it is
cleared.
Methods:
Name Action
Boolean getState( ) Returns true or false, based on whether the check box is
selected
1. Void setState(Boolean on) Change state of checkbox selected or unselected.
2. String getLabel( ) Returns a string containing this check box's label
3. void setLabel(String str) Changes the text of the check box's label
4. void Used to add checkbox into checkboxGroup.
setCheckboxGroup(CheckboxGroup)
.
Example:

importjava.awt.*;
importjava.applet.*;
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet
{
String msg = "";
Checkbox Win98, winNT, solaris, mac;

public void init()


{
Win98 = new Checkbox("Windows 98/XP", null, true);
winNT = new Checkbox("Windows NT/2000");
solaris = new Checkbox("Solaris");
mac = new Checkbox("MacOS");

add(Win98);
add(winNT);
add(solaris);
add(mac);
}
public void paint(Graphics g)
{
msg = "Current state: ";
g.drawString(msg, 6, 80);
msg = " Windows 98/XP: " + Win98.getState();
g.drawString(msg, 6, 100);
msg = " Windows NT/2000: " + winNT.getState();
g.drawString(msg, 6, 120);
msg = " Solaris: " + solaris.getState();
g.drawString(msg, 6, 140);
msg = " MacOS: " + mac.getState();
g.drawString(msg, 6, 160);
}
}

Output:-

CheckboxGroup

 To create a group of checkboxes, the CheckboxGroup class is used.


 The CheckboxGroup class is used with the Checkbox class to implement radio buttons.
 All Checkbox objects that are associated with a CheckboxGroup object are treated as a single set of
radio buttons.
 Only one button in the group may be set or on at a given point in time.

Constructor

Name Action
CheckboxGroup( ) Create a new instance of the CheckboxGroup .

Methods

Name Action
getSelectedCheckbox() Returns the current choice from the check box group.
setSelectedCheckbox(Checkbox Itis used to make one of the box selected among all the
box) check boxes.

Example:

importjava.awt.*;

/*<applet code=CheckboxgroupDemo.class width=200 height=150>< / applet>* /

importjava.awt. *;
import java. applet.Applet;

public class CheckboxgroupDemo extends Applet


{
CheckboxGroup cbg = new CheckboxGroup();

public void init()


{
Checkbox c1 = new Checkbox("Hi");
c1.setCheckboxGroup(cbg);
c1.setState(false) ;
add(c1);

Checkbox c2=new Checkbox("Hello" ,cbg,false);


add(c2);

Checkbox c3 = new Checkbox("How r u?",cbg,true);


add(c3);
}
}

output

Choice (Choice List)


 It is used to create a pop-up list of items from which the user may choose one item at a time.
 The choice class is used to create dropdown list.

Constructor:

Name Action
Choice() Creates a new choice List.
Methods:

Name Action
add(String text) Add an item to the choice list.
getItem(int index) Returns the string at the specified index from the Choice list.
getItemCount() Returns the number of items in the choice list.
getSelectedIndex() Return the index of the currently selected item.
getSelectedItem() Returns the currently selected item as a string.
insert(String item, int index) Inserts the item into the choice list at the specified position.
remove(int position) Removes an item from the choice list at the specified position.
remove(String item) Removes the first occurrence of item from the Choice list.
removeAll() Removes all items from the choice list.
select(int) Selects the item at the given position.
select(String) Selects the item with the given string.

Example:

/*ChoiceListDemo.java */
importjava.awt.*;

/*<applet code=ChoiceListDemo.c1ass width=200 height=150></applet)l

importjava.awt. *;
import java. applet.Applet;

public class ChoiceListDemo extends Applet


{
public void init()
{
Choice c = new Choice();

c.addItem("Apples");
c.addI tem("Orange s");
c.addItem("Suawberries");
c.addItem("Blueberries");
c.addItem("Bananas");

add(c);
}
}

List
 The List component is a scrolling list of strings from which one or more strings can be selected.
 The List class is use for creating single- and multiple-selection list.
Constructor:
Name Action
List( ) Creates an empty scrolling list that enables only one selection
at a time.
List(int, boolean) Creates a scrolling list with the given number of visible lines on the
screen. The boolean indicates whether this list enables multiple
selections (true) or not (false).

Methods
Name Action
Void addItem(String ) Used to build the scrolling list
String getItem(int) Returns the string item at the given position.
int Countltems() Returns the number of items in the menu
Int getSelectedIndex( ) Returns the index position of the item that's selected (used for
lists that allow only single selections)
String[ ] getSelectedItems( ) returns an array containing the names of the currently selected
items
1. int[ ] getSelectedIndexes( ) returns an array containing the indexes of the currently selected
items.
2. select(int) Selects item at specified index.
3. Select(string) Selects item with that string.

/*ScrollingListDemo.java */
import java.awt.*;

/*<app1et code=ScrollingListDemo.class width=200 height=150></applet>*/

importjava.awt.*;
import java.app1et.App1et;
public class ScrollingListDemo extends App1et
{
public void init() {
List 1st = new List(5, true);

1st.addItem("CDR");
1st.addItem("CDRW");
Ist.addItem("DVD");
1st.addItem("PenDrive");
1st.addI tem("Zipdrive");
lst.addltem("RO M");

add(lst);
}
}

Output:
Sample output is shown below:-

Layout Managers

Que:
1. Differentiate border layout and flow layout.
2. List out types of Layout Manager. Explain flow layout manager with example.
3. Explain Border Layout with example.
4. Explain Flow Layout with example.
5. List layout manager classes in Java.
6. List out Layout Manager.
7. List and explain different layout managers in Java.
8. ________ Layout manager lays out the components from left to right.
9. Explain any one with example.
10. List of layout managers in java
11. Explain grid layout manager in Java.
Ans:
 The LayoutManagers are used to arrange components in particular manner.
 LayoutManager is an interface that is implemented by all the classes of layout managers.
 The layout manager set by the SetLayout() method. If we don’t use this method then default
layout manager is used.
 The setLayout( ) method has the following general form:
Void setLayout(LayoutManager layoutObj)
Here, layoutObj is a reference to the desired layout manager.
 If you wish to disable the layout manager and position components manually, pass null for layoutObj.
 If you do this, you will need to determine the shape and position of each component manually, using
the setBounds( ) method defined by Component.

Layout Manager Classes


 Some possible Layout Managers are listed in the table below:
Layout Manager Description Constants
It is used to arrange the components in a FlowLayout.LEFT,
FlowLayout line,one after another(in a flow) from left FlowLayout.CENTER,
to right. FlowLayout.RIGHT – these tell it how to
align the components in each row.
Arranges components to the top, positions in the container
BorderLayout bottom, left, right, and center of a Borderayout.NORTH,
container. BorderLayout.SOUTH,
BorderLayout.EAST,
BorderLayout.WEST,
BorderLayout.CENTER

Divide the container into equal-sized GridLayout(int rows, int


GridLayout rectangles and arrange each columns) To specify the number of
component into one of these cells. rows and columns in the grid.
CardLayout(int hgap, int vgap):
It manages the components in such a way
creates a card layout with the given
CardLayout that only one component is visible at a
horizontal and vertical
time.
gap.

FlowLayout

 FlowLayout is a simple layout manager that arrange components from upper-left corner, left to right
and top to bottom.
 FlowLayout is the default layout for panel and applet.
 By default, a flow layout uses CENTER justification, meaning that all components are centered within
the area allotted to them.

Constructors:
Constructor Description
creates the default layout, which centers components and leaves five
FlowLayout()
pixels of space between each component.
Specify how each line is aligned. Valid values for how are:
FlowLayout(int how)
FlowLayout.LEFT
FlowLayout.CENTER
FlowLayout.RIGHT
FlowLayout(int how,int Create a flowlayout with the given alignment and given horizontal and
horz, int vert) vertical gap.

Example:

Import java.awt.*;

public class Flow extends java.applet.Applet {

public void init() {

add( new Button("One") );


add( new Button("Two") );
add( new Button("Three") );
add( new Button("Four") );
add( new Button("Five") );
}
}

BorderLayout
 The BorderLayout is used to arrange the components in five regions: north,south,east,west and center.

 Each region(area) may contain one component only.


 It is the default layout of frame or window.
 The Border Layout provides five constants for each region:NORTH,SOUTH,EAST,WEST,CENTER.
 These constants are used like BorderLayout.NORTH.
 While adding the component these constants are used by using following form of add() method.
add (Component compObj, Object region);

Constructors:
Constructor Description
BorderLayout() Creates a border layout with no space between the components.
BorderLayout(int horz, int Creates a border layout with the given horizontal and vertical
vert) space between the components.

Example:

import java.awt.*;

public class Border extends java.applet.Applet {


public void init() {
setLayout( new java.awt.BorderLayout() );
add( new Button("North"), "North" );
add( new Button("East"), "East" );
add( new Button("South"), "South" );
add( new Button("West"), "West" );
add( new Button("Center"), "Center" );
}
}
Output:

Grid Layout

 As the name indicates the container is divided into a grid of cells formed by rows and columns.
 Each cell hold one component.
 Components added to the container with the GridLayout manager are arranged in order from left to
right.

Constructors of GridLayout
Constructor Description
Creates a gridlayout with one column per component in a
GridLayout ()
row.
Creates a gridlayout with the given rows and columns but
GridLayout (int rows, int columns) no space between the components.
GridLayout(int rows,int columns,int Creates a gridlayout with the given rows and columns
horz, int vert) along with given horizontal and vertical space.

Example
public class GridLayoutDemo extends Applet {
static final int n = 4;

public void init() {

setLayout(new GridLayout(n, n));


setFont(new Font("SansSerif", Font.BOLD, 24));

for(int i = 0; i< n; i++) {


for(int j = 0; j < n; j++) {
int k = i * n + j;
if(k > 0)
add(new Button("" + k));
}
}
}

CardLayout

 The Card Layout manager treats each component as a card.


 Only one card/component is visible at a time. The container acts as a stack of cards.

Constructor:

Constructor Description
CardLayout() Creates a card layout with zero horizontal and vertical space.
CardLayout(int horz,int vert) Creates a card layout with the given horizontal and vertical space.

Methods
Name Description
void first(Container a) It is used to flip to the first card of the given container.
void last(Container a) It is used to flip to the last card of the given container.
void next(Container a) It is used to flip to the next card of the given container.
void previous(Container a) It is used to flip to the previous card of the given container.
void show(Container a, String
It is used to flip to the specified card with the given name.
cardName)
 ‘a’ is a reference to the container(usually a panel) that holds the cards, and cardName
is the name of a card.
Example:

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

public class CardLayoutExample extends Frame implements ActionListener{


CardLayout card;
Button b1,b2,b3;
Container c;
CardLayoutExample(){

c=getContentPane();
card=new CardLayout(40,30);

c.setLayout(card);

b1=new Button("Apple");
b2=new Button("Boy");
b3=new Button("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

c.add("a",b1);
c.add("b",b2);
c.add("c",b3);

}
public void actionPerformed(ActionEvent e) {
card.next(c);
}

public static void main(String[] args) {


CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
}
}

Benefits of LayoutManager:
 Not necessary to compute the coordinates at which component is to be placed.
 If the Applets output frame is re-sized dynamically adjusts placement of components

Event handling in Java (Event Delegation Model)

Que:
1. Explain event handling in Java.
2. Explain event delegation model.
3. List out Interfaces of Event Listener.
4. List any five Event classes and five Listener interfaces in JAVA.
5. Event Class
6. Explain event listeners in JAVA.
7. List out types of Event classes.
Ans:
 Event Handling: It is the mechanism that controls the event and decides what should happen if an
event occurs.
 Modern approach to handle events is based on the Delegation Event Model.
 In event delegation model, a source generates an event and sends it to one or more listeners.
 In this scheme, the listener simply waits until it receives an event. Once received, the listener
processes the event and then returns.
 In the delegation event model, listeners must register with a source in order to receive an event
notification.

 The Event Delegation model is based on – The Event, Event Source and Event Listener.

Events
 An event is a change of state of an object.
 When the user interacts with a GUI application, an event is generated.
 Example: Pressing a button, Entering a character in Textbox., selecting an item or closing a
window.
 Event object is used to carry the required information about the state change.
Event Sources
 A source is an object that generates an event. 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.

Event Listeners

 A listener is an object that is notified when an event occurs.


 It has two major requirements:
(1) It must have been registered with one or more sources to receive notifications about specific types of
events.
(2) It must implement methods to receive and process these notifications. The methods that receive and
process events are defined in a set of interfaces found in java.awt.event.

Event Classes

 At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the superclass
for all events.
 Constructor:
EventObject(Object src)
Here, src is the object that generates this event.
 Methods:
1. object getSource(): It returns the object that originated the event. So if the user has clicked a
Push button, the method getSource returns the object corresponding to Push button is generated.

2. int getID(): This method returns the integer value corresponding to the type of event. For
example, if the user has clicked on the mouse, the method getID returns the integer defined as
MouseEvent.
 Events are supported by a number of Java packages, like java.util,java.awt and java.awt.event.

 The list of Event classes are as follow:

Event Classes Description Listener Interface


ActionEvent Generated when button is pressed, menu-item ActionListener
is selected, list-item is double clicked.
MouseEvent Generated when mouse is dragged, moved, MouseListener and
clicked, pressed or released also when the enters MouseMotionListener
or exit a component.
WindowEvent Generated when window is activated, WindowListener
deactivated, opened or closed.
KeyEvent Generated when input is received from KeyListener
keyboard.
FocusEvent Generated when a component gains or loses FocusListener
keyboard focus.
ItemEvent Generated when a check box or list item is ItemListener
clicked.
TextEvent Generated when the value of a text area or text TextListener
field is change.

MOUSEEVENT and MOUSELISTENER Interface


Que:
1. Explain Mouse Listener.
2. Describe MOUSEEVENT and MOUSELISTENER interface with example.
3. Explain mouseReleased method of mouse listener
4. Describe mouse listener and mouse events using proper example.
Ans:

MouseEvent :

 A MouseEvent is fired to all its registered listeners, when you press or release a mouse-button at the
source. object position the mouse-pointer at (enter) and away (exit) from the source object.

Methods:

 getPoint( ) - Returns a Point object that contains the x and y coordinates. The point is where the
event occurred.
 getClickCount() - Returns the number of times the mouse was clicked.
 getX( ) - Returns the x coordinate of the point at which the event occurred.
 GetY() - Returns the y coordinate of the point at which the event occurred.

MouseListener Interface:

 MouseEvent listener must implement the MouseListener interface, which declares the following five
abstract methods :
1. void mousePressed(MouseEvent event): Invoked when the mouse button is pressed down
2. voidmouseReleased(MouseEvent event): Invoked when the mouse button is released.
3. void mouseEntered(MouseEvent event): Invoked when the mouse enters the component.
4. void mouseExited(MouseEvent event): Invoked when the mouse exits the component.
5. void mouseClicked(MouseEvent event): Invoked when the mouse button is pressed and then
released.
Example:
public class mousedemo extends Frame implements MouseListener{
mousedemo(){
addmouseListener(this);
setvisible(true);
}
public void mousePressed(MouseEvent event){
System.out.println(“mouse is pressed”);
}
Public void mouseReleased(MouseEvent event){
System.out.println(“mouse is Released”);
}
public void mouseEntered(MouseEvent event){
System.out.println(“mouse is enterd”);
}
public void mouseExited(MouseEvent event){
System.out.println(“mouse is exited”);
}
Public void mouseClicked(MouseEvent event){
System.out.println(“mouse is clicked”);
}
public void main(String args[]){
New mousedemo();
}
KEYEVENT and KEYLISTENER Interface
Que:
1. Describe KEYEVENT and KEYLISTENER interface with example.
Ans:

KeyEvent

 A KeyEvent is fired when you pressed, released,and typed a key on the source object.
KeyListener

 A KeyEvent listener must implement KeyListenerinterface, which declares three abstract methods:
1. public void keyTyped(KeyEvent e) :Invoked when a key has been typed (pressed and released).
2. public void keyPressed(KeyEvent e): Invoked when a key has been pressed.
3. public void keyReleased(KeyEvent e): Invoked when a key has been released.
Example:

public class keydemo extends Frame implements keyListener


{
keydemo()
{
addkeylListener(this);
setvisible(true);
}
public void keyPressed(KeyEvent event){
System.out.println(“key is pressed”);
}
Public void keytyped(KeyEvent event){
System.out.println(“key is typed”);
}
public void keyReleased(KeyEvent event){
System.out.println(“key isreleased”);
}
public void main(String args[]){
new keydemo();
}
}
ActionEvent and ActionListener Interface
 Action events are generated by specific types of action that you might occur.
 for example : Clicking a button , Selecting a menu item ,Hitting Enter in a text component

Methods:

 String getActionCommand(): obtain the command name of the invoking ActionEvent object .
 void setActionCommand(): to set the command name of the invoking ActionEvent object .

ActionListener:

 ActionEvent listener must implement ActionListener interface, which declares one abstract method:
1. void actionPerformed(): When any action event occurs in an AWT component, this method is invoked.

Example:
public class actiondemo extends Frame implements ActionListener
{
Button b1=new Button();
actiondemo()
{
b1.addActionListener(this);
setvisible(true);
}
public void actionPerformed(ActionEventevent){
System.out.println(“button is pressed”);
}
public void main(String args[]){
new actiondemo();
}
}
WindowEvent and WindowListener Interface

Que:
1. Write a brief note on AWT WindowEvent Class.
Ans:

windowEvent:

 A event that indicates that a window has changed its status (opened, closed, activated, deactivated,
iconified, or deiconified).

windowListener:

1. windowActivated(WindowEvent e): Invoked when a window is activated.


2. windowClosed(WindowEvent e): Invoked when a window has been closed.
3. windowClosing(WindowEvent e): Invoked when a window is in the process of being closed.
4. windowDeactivated(WindowEvent e): Invoked when a window is de-activated.
5. windowDeiconified(WindowEvent e): Invoked when a window is de-iconified.
6. windowIconified(WindowEvent e): Invoked when a window is iconified.
7. windowOpened(WindowEvent e): Invoked when a window has been opened.
Example:

Public class windemo extends Frame implements WindowListener


{
Public windemo()
{
setSize(400,400);
setVisible(true);
addWindowListener(this);
}

Public void windowActivated(WindowEvent e)


{
System.out.println("window is activated");
}
Public void windowClosed(WindowEvent e)
{
System.out.println("window is closed");
}
Public void windowClosing(WindowEvent e)
{
System.out.println("window is closing");
}
Public void windowDeactivated(WindowEvent e)
{
System.out.println("window is deactivated");
}
Public void windowOpened(WindowEvent e)
{
System.out.println("window is open");
}
Public void windowIconified(WindowEvent e)
{

}
Public void windowDeiconified(WindowEvent e)
{
}
Public static void main(String[] args) {
new windemo();
}
}
ItemEvent and ItemListener Interface
ItemEvent:

 It is generated when a checkbox or list item is clicked or checkboxmenu item is selected or


deselected.

ItemListener:

1. itemStateChanged (ItemEvent e): The itemStateChanged() method is invoked automatically


whenever you click or unclick on the registered checkbox component.
Example:

import java.awt.*;
import java.awt.event.*;
public class ItemListenerExample implements ItemListener{
Checkbox checkBox1,checkBox2;
Label label;
ItemListenerExample(){
Frame f= new Frame("CheckBox Example");
label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);

checkBox1 = new Checkbox("C++");


checkBox1.setBounds(100,100, 50,50);

checkBox2 = new Checkbox("Java");


checkBox2.setBounds(100,150, 50,50);

f.add(checkBox1);
f.add(checkBox2);
f.add(label);

checkBox1.addItemListener(this);
checkBox2.addItemListener(this);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public void itemStateChanged(ItemEvent e) {
if(e.getSource()==checkBox1)
label.setText("C++ Checkbox: " );
if(e.getSource()==checkBox2)
label.setText("Java Checkbox: " );
}
public static void main(String args[])
{
new ItemListenerExample();
}
}

MouseMotionEvent and MouseMotionListener Interface


MouseMotionEvent:

 The Java MouseMotionListener is notified whenever you move or drag mouse

MouseMotionListener Interface

 Methods of MouseMotionListener interface given below:

1. public abstract void mouseDragged(MouseEvent e);

2. public abstract void mouseMoved(MouseEvent e);

Adapter Classes
Que:
1. State why an adapter class is useful.
Ans:

 An adapter class provides an empty implementation of all methods in an event listener interface.

 Adapter classes are useful when we want to receive and process only some of the events that are
handled by a particular event listener interface.

 We can define a new class to act as event listener by extending one of the adapter classes and
implementing only those events in which you are interested.

 The Adapter classes with their corresponding listener interfaces are given below:

Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

FocusAdapter FocusListener

 Example to use Adapter Class in Applet


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

public class AppletAdapterDemo extends Applet


{
String str="";

public void init()


{
ABC ob1 = new ABC(this);
addMouseListener(ob1);
}

public void paint(Graphics g)


{
g.drawString(str, 50, 100);
showStatus("MouseMotionAdapter is in action");
}
}

class ABC extends MouseAdapter


{
AppletAdapterDemo ob1;

public ABC(AppletAdapterDemo ob1)


{
this.ob1 = ob1;
}
public void mouseClicked(MouseEvent e)
{
ob1.str = "Mouse is clicked";
ob1.setForeground(Color.red);
ob1.repaint();
}
}

 Example to use Adapter Class in frame:


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

public class MouseAdapterExample extends MouseAdapter{


Frame f;
MouseAdapterExample(){

f=new Frame("Mouse Adapter");


f.addMouseListener(this);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void mouseClicked(MouseEvent e) {
g.fillOval(e.getX(),e.getY(),30,30);
}

public static void main(String[] args) {


new MouseAdapterExample();
} }

Menu and Menu Bar


 Top-level window can have a menu bar associated with it.
 A menu bar displays a list of top-level menu choices.
 In java, menu can be implemented using MenuBar,Menu,MenuItem.
 Menubar contains one or more Menu objects.
 Each Menu object contains a list of MenuItem object.
 Each MenuItem object represents something that can be selected by the user.
 The abstract class MenuComponent is the super class of all menu-related components.
 Menu Component hierarchy as given below:

Constructor of Menu and Menubar

Constructor Description
MenuBar() Creates a new menu bar.
Menu() To create a default menu.
Menu(String str) str specifies the name of the Menu selection
Menu(String str, Boolean flag) Str specifies the name of the Menu selection flag represents
the popup menu if set true.
MenuItem() To create a default MenuItem.
MenuItem(String str) Str is the name shown in the Menu.
MenuItem(String str, MenuShortcut key)
Key is the short cut key for that Menu Item.

Method of Menu

Method Description
setEnabled(boolean flag) To enable or disable menu item
isEnabled() To retrieve the status of the menu item.
setLabel(String str) To change the name of the menu item.
String getLabel() To retrieve the current name of the menu item.
boolean getState() Return true if the item is checked otherwise false.
void setState(Boolean flag)
To check an item, pass true and to clear an item, pass false.

add (MenuItem m) Used to add menu item in Menu.


add(Menu menu) Adds the specified menu to the menu bar.
getItem(int index) Returns the menu item at the given index
getItemCount() Returns the number of item inside the menu.
remove(MenuComponent item)
Removes menu item from menu.

remove(int index) Removes the menu located at the specified index from the
menubar.
removeAll() Removes all menu from menu bar.

Example:

import java.applet.Applet;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;

public class MenuDemo extends Frame


{
MenuBar mbar;
Menu m;

MenuDemo()
{
super("Menu Demo");

setSize(400,400); // Set size to the frame


setLayout(new FlowLayout()); // Set the layout
setVisible(true);

mbar = new MenuBar();

m = new Menu("File");

m.add(new MenuItem("New"));
m.add(new MenuItem("Open"));
m.add(new MenuItem("Save"));
m.add(new MenuItem("Save As"));
m.add(new MenuItem("Print"));
m.addSeparator(); //add separator
m.add(new MenuItem("Quit"));

mbar.add(m);

m = new Menu("Help");
m.add(new MenuItem("Help"));

m.addSeparator();
m.add(new MenuItem("About"));

mbar.add(m);

setMenuBar(mbar);

addWindowListener(new WindowAdapter(){

public void windowClosing(WindowEvent we){


System.exit(0);

}
});
}
public static void main(String args[])

{
MenuDemo MD= new MenuDemo();
}
}

Difference between swing and awt


Que:
1. What is the main difference between AWT and swing in java?
2. State two difference between SWING and AWT.
Ans:

 There are many differences between java AWT and swing that are given below:
Java AWT Java Swing
Java swing components are platform-
AWT components are platform-dependent.
independent.
AWT components are heavyweight. Swing components are lightweight.
AWTdoesn't support pluggable look and feel. Swing supports pluggable look and feel.
AWT components require java.awt package. Swing components require javax.swing package.
Swing provides more powerful components such as
AWT provides less components than Swing. tables, lists, scrollpanes, color chooser,tabbed pane
etc.
AWT doesn't follows MVC (Model View
Controller) where model represents data, view
represents presentation and controller acts as Swing follows MVC.
an interface between model and view.

Swing
Que:
1. Explain any one SWING component with example.
2. Explain any two Swing controls.
3. Compare Label and JLabel controls.
4. Describe any one swing component with example.
5. What is Swing? Explain the need of Swing.
6. List out Swing component classes.
7. Explain JButton AWT control in java.
8. Explain JComboBox AWT control in java.
Ans:
 Swing is part of Java Foundation Classes (JFC). It is an API for providing a graphical user
interface (GUI) for Java programs.
 Swing is used to create window-based applications. It is built on the top of AWT (Abstract Windowing
Toolkit) API and entirely written in java.
 Java Swing provides platform-independent and lightweight components.
 It has more powerful and flexible components than AWT.
 In addition to familiar components such as buttons, check boxes and labels, Swing provides several
advanced components such as tabbed panel, scroll panes, trees, tables, and lists.
 The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.
Hierarchy of Java Swing classes

 JFrame, JPanel, JWindow is the Swing's version of Frame, Panel and Windows respectively.

JApplet

 Fundamental to Swing is the JApplet class.


 The JApplet class extends the Applet class.
 JApplet is rich with functionality that is not in Applet.
 We can use JApplet that can have all the controls of swing.

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

public class EventJApplet extends JApplet implements ActionListener{

JButton b;
JTextField tf;

public void init(){

tf=new JTextField();
tf.setBounds(30,40,150,20);
b=new JButton("Click");
b.setBounds(80,150,70,40);

add(b);
add(tf);
b.addActionListener(this);

setLayout(null);
}

public void actionPerformed(ActionEvent e){


tf.setText("Welcome");
}
}

JLabel
 JLabel is used to display a single line of read only text.
 It inherits JComponent class.
 Constructor of JLabel
Constructor Description
Creates label with no image and with an empty string for the
JLabel()
title.
JLabel(Icon image) Creates a label with the specified image.
JLabel(String text) Creates a label with the specified text.
JLabel(Icon image, int Creates a label with the specified image and horizontal
horizontalAlignment) alignment.
 Methods of JLabel

Constructor Description
getText() Returns the string that associate with the label.
setText(String text) Set the specified text to label.
getIcon() Returns the image that displays the label.
setIcon(Icon image) Set the image to the label.
getHorizontalAlignment() Returns the alignment of the label along the X axis.
setHorizontalAlignment(int
Sets the alignment of the label along the X axis
alignment)
Example:

import javax.swing.*;
class LabelExample
{
public static void main(String args[])
{
JFrame f= new JFrame("Label Example");
JLabel l1,l2;

l1=new JLabel("First Label.");


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

l2=new JLabel("Second Label.");


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

f.add(l1);
f.add(l2);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
}
JTextField
 The class JTextField is a component which allows the editing of a single line of text.
 It inherits JTextComponent class.
 Constructor of JLabel:

Constructor Description
JTextField() Creates a default text field.
Creates a new empty text field with the specified number of
JTextField(int columns)
character.
JTextField(String text) Creates a new text field initialized with the specified text.
Creates a new text field initialized with the specified text to be
JTextField(String text, int
displayed, and wide enough to hold the specified number of
columns)
columns.
 Methods of JTextField

Method Description
getText() Return the text this text field contains (as a string).
setText() Puts the given text string into the field.
getColumns() Returns the width of this text field.
getSelectedText( ) Get the currently selected text.

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);
}
}
JButton
 The JButton class is used to create a labeled button.

 Application result in some action when the button is pushed.

 It inherits AbstractButton class.


 Constructors of JButton
Constructor Description
JButton() Creates a button with an empty string for its label.
JButton(String text) Creates a button with the given string as a label.
JButton(Icon image) Creates a button with an specified image.
JButton(String text, Icon icon)
Creates a button with specified text and an image.

 Methods of JButton
Method Description
getLabel() Get the label of the Button.
setLabel(string text) Set the label of the Button with given text.
setEnable(boolean) Enable or disable this Button. Disabled Button cannot be clicked.
Example:

import javax.swing.*;

public class ButtonExample {

public static void main(String[] args) {


JFrame f=new JFrame("Button Example");

JButton b=new JButton("Click Here");


b.setBounds(50,100,95,30);

f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
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.

Constructors of the checkbox


Constructor Description
JCheckbox() Creates a check box with no image and text
JCheckbox(String text) Creates a checkbox with the given string as a label.
JCheckBox(Icon image) Creates a check box with an image.
JCheckbox(String text, boolean Creates a checkbox with the given string as a label and sets the
state) Specified state(Selected/Deselected by True/False).
JCheckBox(String text, Icon
Creates a checkbox with specified text and image
image)
Checkbox(String text, Icon Creates a checkbox with the given string as a label,image,and
image, boolean state) set to the specified state.
 Methods of JCheckBox:
Method Description
getText() Returns the label of the check box.
setText(String text) Sets the check box's label by given text.
isSelected() Check whether checkbox is selected or not.

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);
f.add(checkBox2);

f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
JRadioButton
 The JRadioButton class is used to create a radiobutton.
 It is used to choose one option from multiple options.
 It should be added in Group to select one radio button only by using ButtonGroup class.
 By default radio button is not selected.
 Constructors of JRadioButton:
Constructor Description
JRadioButton() Creates radio button with no text.
JRadioButton(Icon image) Creates radio button with the specified image but no text
JRadioButton(String text) Creates radio button with the specified text.
JRadioButton(String text, Icon image)
Creates radio button with the specified image and text.
JRadioButton(Icon image,boolean Creates a radio button with the specified image and selection
selected) state, but no text.
JRadioButton(String text,boolean Creates a radio button with the specified text and selection
selected) state.
JRadioButton(String text, Icon Creates a radio button with the specified text, image, and
image, boolean selected) selection state.
 Methods of JRadioButton is same as JCheckBox:

Method Description
getText() Returns the label of the check box.
setText(String text) Sets the check box's label by given text.
isSelected() Check whether checkbox is selected or not.

Example:
import javax.swing.*;
public class RadioButtonExample {

JFrame f;
RadioButtonExample(){
f=new JFrame();

JRadioButton r1=new JRadioButton("A) Male");


JRadioButton r2=new JRadioButton("B) Female");

r1.setBounds(75,50,100,30);
r2.setBounds(75,100,100,30);

ButtonGroup bg=new ButtonGroup();


bg.add(r1);
bg.add(r2);
f.add(r1);
f.add(r2);

f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new RadioButtonExample();
}
}

JComboBox
 TheJComboBox class is used to create drop-downlist. At a time only one item can be selected from
the item list.
 The JComboBox offers an editable option.
 It inherits JComponent class.
 Constructors of JcomboBox:

Constructor Description
JComboBox() Creates a JComboBox with a default data model.
Creates a JComboBox that takes its items from an existing
JComboBox(Object[] items)
array.
Creates a JComboBox that contains the elements in the
JComboBox(Vector<?> items)
specified Vector.
 Methods of JcomboBox:

Method Description
addItem(Object object) It is used to add an item to the item list.
removeItem(Object object) It is used to delete an item from the item list.
removeAllItems() It is used to remove all the items from the list.
getItemCount() Returns the number of items in the list.
getSelectedIndex() Returns the index of the selected item.
setSelectedIndex(int index) Selects the item at given index.
getSelectedItem() Returns the selected item.

Example:

import javax.swing.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");

String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);

cb.setBounds(50, 50,90,20);
f.add(cb);

f.setLayout(null);
f.setSize(400,500);
f.setVisible(true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}
Menus
 Menu hierarchy is as given below:
JMenuBar

 Constructor of JMenuBar

Constructor Description
JMenuBar() Creates a new menu bar.

 Methods of JMenuBar

Method Description
JMenu add(JMenu c) Appends the specified menu to the end of the menu bar.
getComponentIndex(Component c) Returns the index of the specified component.
Returns the margin between the menubar's border and its
Insets getMargin()
menus.
Sets the margin between the menubar's border and its
void setMargin(Insets m)
menus.
JMenu getMenu(int index) Returns the menu at the specified position in the menubar.
int getMenuCount() Returns the number of items in the menu bar.
Returns true if the menu bar currently has a component
boolean isSelected()
selected.

JMenuItem

 The JMenuItem class represents the actual item in a menu.


 All items in a menu should derive from class JMenuItem, or one of its subclasses.
Constructor of JMenuBar
Constructor Description
JMenuItem() Creates a JMenuItem with no set text or image.
JMenuItem(Icon image) Creates a JMenuItem with the specified image.
JMenuItem(String text) Creates a JMenuItem with the specified text.
JMenuItem(String text, Icon image)
Creates a JMenuItem with the specified text and icon.
JMenuItem(String text, int mnemonic) Creates a JMenuItem with the specified text and
keyboard mnemonic.
Methods of JMenuBar

Method Description
JMenu add(JMenu c) Appends the specified menu to the end of the menu bar.
getComponentIndex(Component c)
Returns the index of the specified component.
Returns the margin between the menubar's border and its
Insets getMargin()
menus.
Sets the margin between the menubar's border and its
void setMargin(Insets m)
menus.
JMenu getMenu(int index) Returns the menu at the specified position in the menu bar.
int getMenuCount() Returns the number of items in the menu bar.
Returns true if the menu bar currently has a component
boolean isSelected()
selected.
JMenu

 The JMenu class represents pull-down menu component which is deployed from a menubar.

Constructor of JMenu
Constructor Description
JMenu() Creates a JMenu with no text.
JMenu(String text) Creates a JMenu with the specified text.
Creates a JMenu with the specified text and specified asatear-
JMenu(String s, boolean b)
off menu or not.

Methods of JMenu

Method Description
Component add(Component c) Appends a component to the end of this menu.
Component add(Component c, Adds the specified component to this container at the given
int index) position.
Creates a menuitem with the specified text and append sit to
JMenuItemadd(String text)
the end of this menu
void addSeparator() Appends a new separator to the end of the menu.
JMenuItem getItem(int pos) Returns the JMenuItem at the specified position.
Returns the number of items on the menu,including
int getItemCount()
separators.
Inserts a new menu item with the specified text at a given
void insert(String text, int pos)
position.
void insertSeparator(int index) Inserts a separator at the specified position.
boolean isSelected() Returns true if the menu is currently selected.
void remove(int pos) Removes the menu item at the specified index from this menu
void remove(JMenuItem item) Removes the specified menu item from this menu.
void removeAll() Removes all menu items from this menu.

You might also like