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

Unit-8 Event handling and GUI programming (E-next.in)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

Unit-8 Event handling and GUI programming (E-next.in)

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

Unit-8 Event handling and GUI programming

Q.1 Difference between AWT and Swing.


AWT Swing
1) AWT stand for Abstract Windows 1) Swing also called as JFC’s (Java
Toolkit. Foundation classes).
2) AWT components are called Heavy 2) Swings are called light weight
weight component. component.
3) AWT components require java.awt 3) Swing components require javax.swing
package. package.
4) AWT components are platform 4) Swing components are made in purely
dependent. java and they are platform
independent.
5) AWT doesn’t support pluggable look 5) Swing support pluggable look and feel.
and feel.
6) AWT programs are not portable. 6) Swing programs are portable.
7) AWT is old framework for creating 7) Swing is new framework for creating
GUIs GUIs
8) AWT supports limited number of GUI 8) Swing provides advanced GUI controls
controls. like Jtable, JTabbedPane etc.
9) More code is needed to implement 9) Less code is needed to implement
AWT controls functionality. Swing controls functionality.
10) AWT doesn’t follow MVC. 10) Swing support MVC.
11) AWT is slower then Swing. 11) Swing is Faster then AWT.
12) AWT components are Button, 12) Swing components are JRadioButton,
TextField, Label, Frame and Panel. JCheckbox, JMenu etc.

Q.2 Compare Applet and Application.


Applet Application
1) Applet are specific programs that require 1) Application are stand-alone Java
use of a browser and should be included programs that run directly on your
in an HTML web document. machine.
2) Applet cannot run without the help of a 2) Application programs run with the help
browser. of a virtual machine.
3) Applet initialize through init() method. 3) Application starts its execution through
main() method.
4) Do not use the main method. 4) Uses the main method for execution.
5) The files cannot be read and write on the 5) Application are capable of performing
local computer through applet. those operations to the files on the local
computer.
6) Cannot communicate with other servers. 6) Communication with other servers is
probably possible.
7) Applet cannot access files residing on 7) Can access any data or file available on
the local computer. the system.
8) Requires highest security for the system 8) Does not require any security.
as they are untrusted.
9) Applets are created by extending the 9) Application are created by writing public
java.applet.Applet static void main(String args[]) method.

Khan S. Alam 1 https://E-next.in


Unit-8 Event handling and GUI programming

Q.3 Explain Life Cycle of Applet with a suitable program.


Applet Life Cycle
 Java applet inherits features from the class Applet. Thus, whenever an applet is
created, it undergoes a series of changes from initialization to destruction.
 Various stages of an applet life cycle are depicted in the figure below:

Life Cycle of Applet

1. Born or Initial State


 When a new applet is born or created, it is activated by calling init() method.
 At this stage, new objects to the applet are created, initial values are set, images are
loaded and the colors of the images are set.
 An applet is initialized only once in its lifetime.
It's general form is:
public void init( )
{
//Action to be performed
}

2. Running State
 An applet achieves the running state when the system calls the start() method.
 This occurs as soon as the applet is initialized.
 An applet may also start when it is in idle state.
 At that time, the start() method is overridden.
It's general form is:
public void start( )
{
//Action to be performed
}

Khan S. Alam 2 https://E-next.in


Unit-8 Event handling and GUI programming

3. Idle State
 An applet comes in idle state when its execution has been stopped either implicitly
or explicitly.
 An applet is implicitly stopped when we leave the page containing the currently
running applet.
 An applet is explicitly stopped when we call stop() method to stop its execution.
It's general form is:
public void stop()
{
//Action to be performed
}

4. Dead State
 An applet is in dead state when it has been removed from the memory.
 This can be done by using destroy() method.
It's general form is:
public void destroy( )
{
//Action to be performed
}

5. Display State
 Apart from the above stages, Java applet also possess paint( ) method.
 This method helps in drawing, writing and creating colored backgrounds of the
applet.
 It takes an argument of the graphics class.
 To use the graphics, it imports the package java.awt.Graphics
It's general form is:
public void paint(Graphics g)
{
//Display Statements
}

Khan S. Alam 3 https://E-next.in


Unit-8 Event handling and GUI programming

Example: 1st Program: Applet program – LifeTest.java

importjava.awt.Graphics;
importjava.applet.Applet;

public class LifeTest extends Applet


{

public void init()


{
System.out.println("init(): applet started");
}

public void start()


{
System.out.println("start(): applet activated");
}

public void paint(Graphics g)


{
System.out.println("paint(): applet running");
}

public void stop()


{
System.out.println("stop(): applet inactivated ");
}

public void destroy()


{
System.out.println("destroy(): applet destroyed");
}
}

2nd Program: HTML Program – Life.html


<applet code="LifeTest.class" width="250" height="125">
</applet>

Output:
init(): applet started
start(): applet activated
paint(): applet running
stop(): applet inactivated
destroy(): applet destroyed

Khan S. Alam 4 https://E-next.in


Unit-8 Event handling and GUI programming

Q.4 Explain Event delegation Method? Explain it? Explain ItemListener and Mouselistner
interface.
Q.5 Write Applet program to handle mouse events.
Q.6 What is Adapter class.
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.

Event Delegation method


 It is important to consider how users interact with the user interface when designing
a GUI.
 The GUI may require users to click, resize, or drag and drop components of the
interface, and input data using the keyboard.
 These actions will result to an event and you need to write a code to handle them.
 Event handling code deals with events generated by GUI user interaction.
 The best practice for coding event handlers are outlined in the event delegation
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.
 In the delegation event model, listeners must register with a source in order to
receive an event notification.

Event delegation Model

The event delegation model comprises three elements


1) Event source
2) Event listener
3) Adapter

Khan S. Alam 5 https://E-next.in


Unit-8 Event handling and GUI programming

1) Event source
 An event source is a component, such as a GUI component, that generates an event.
 The event source can be generated by any type of user interaction.
 You can also combine a number of different types of events into one event object.
 For example, if a user clicks and drags an icon, you can sum up the mouse-clicked
event and the mouse-moved event into one event object.
 In the event delegation model, a class represents each event type.
 Event objects are all defined in the java.util.EventObject subclasses.
Here is the general form:
 public void addTypeListener(TypeListener el)

2) Event listener
 It is also known as event handler.
 Listener is responsible for generating response to an event.
 From java implementation point of view the listener is also an object.
 Event listeners are objects that receive notification of an event.
 Listener waits until it receives an event. Once the event is received, the listener
process the event an then returns.
 To receive notification of an event, the object must be registered with the event
source. To subscribe to the event source, you implement the appropriate listener
interface.
 All listeners are implementations of the Event Listener interface or one of its
subinterfaces.
 The Java API provides a predefined listener interface for each set of event types that
a source can fire.
 For example, the MouseListenerinterface deals with mouse events, and the
ActionListener interface deals with action events fired by buttons and other
components.

3) Adapter
 Adapters are abstract classes that implement listener interfaces using predefined
methods. These are provided for convenience.
 You can use an adapter to apply one listener's methods without having to implement
all other methods.
 Adapters provide empty implementations for all interfaces' methods, so you only
need to override the method you are interested in.

Advantages
 It is simple and well suited to an object-oriented programming environment.

Disadvantages
 An event can only be handled by the component from which it originated or by one
of the containers of the originating component.
 In order to handle events, you must either subclass the component that receives the
event or create a handleEvent() method at the base container.

Khan S. Alam 6 https://E-next.in


Unit-8 Event handling and GUI programming

Java ItemListener Interface


 The class which processes the Item Event should implement this interface.
 The object of that class must be registered with a component.
 The object can be registered using the addItemListener() method.
 When the action event occurs, that object's itemStateChangedmethod is invoked.
 The Java ItemListener is notified whenever you click on the checkbox.
 It is notified against ItemEvent.
 The ItemListener interface is found in java.awt.event package.
 It has only one method: itemStateChanged().

itemStateChanged() method
 The itemStateChanged() method is invoked automatically whenever you click or
unclick on the registered checkbox component.
 public abstract void itemStateChanged(ItemEvent e));

Interface declaration
Following is the declaration for java.awt.event.ItemListener
 interface public interface ItemListener extends EventListener

Interface methods Method & Description


 void itemStateChanged(ItemEvent e)
 Invoked when an item has been selected or deselected by the user.

Methods inherited
 This interface inherits methods from the following interfaces: java.awt.EventListener

Create ItemListener for AWT Choice ItemListener catches ItemEvent.


The following example illustrates it.
import java.awt.*;
import java.awt.event.*;

class ChoiceAction extends Frame


{
Choice c;
Label l;

public ChoiceAction()
{
setTitle("Choice with ItemListener Demo"); // Set frame properties
setSize(400,400);
setLayout(new FlowLayout());
setLocationRelativeTo(null);
setVisible(true);

c=new Choice(); // Create choice


l=new Label(); // Create label

Khan S. Alam 7 https://E-next.in


Unit-8 Event handling and GUI programming

c.add("Apple"); // Add items


c.add("Mango");
c.add("Guava");
c.add("Orange");
c.add("Pineapple");
c.add("Grapes");

add(c); // Add choice


add(l); // Add label

c.addItemListener(new ItemListener() // Add item listener


{
public void itemStateChanged(ItemEvent ie)
{
l.setText("You selected "+c.getSelectedItem());
}
});
}

public static void main(String args[])


{
new ChoiceAction();
}
}

ChoiceAction() : Code illustrating item listener on Choice is written here


new ChoiceAction() : Create the object for the class ChoiceAction

Output:

Khan S. Alam 8 https://E-next.in


Unit-8 Event handling and GUI programming

Java MouseListener Interface


 The Java MouseListener is notified whenever you change the state of mouse. It is
notified against Mouse Event.
 The MouseListener interface is found in java.awt.event package.
 It has five methods.
 The class which processes the Mouse Event should implement this interface.
 The object of that class must be registered with a component.
 The object can be registered using the addMouseListener() method.

Mouse events are of two types.


 MouseListener handles the events when the mouse is not in motion.
 While MouseMotionListener handles the events when mouse is in motion.

Interface Declaration
Following is the declaration for java.awt.event.MouseListener interface:
 public interface MouseListener extends EventListener

Methods of MouseListener interface


 There are five types of events that MouseListener can generate. There are five
abstract functions that represent these five events. The abstract functions are:
No. Method Description
1 void mouseClicked(MouseEvent e); Invoke when Mouse key is pressed/released
2 void mouseEntered(MouseEvent e); Invoke when Mouse entered the component
3 void mouseExited(MouseEvent e); Invoke when Mouse exited the component
4 void mousePressed(MouseEvent e); Invoke when Mouse key is pressed
5 void mouseReleased(MouseEvent e); Invoke when Mouse key is released

Methods Inherited
This interface inherits methods from the following interfaces: java.awt.EventListener

Java MouseListener Example:


import java.awt.*;
import java.awt.event.*;
public class MouseListenerExample extends Frame implements MouseListener
{
Label l;

MouseListenerExample()
{
addMouseListener(this);
l=new Label();
l.setBounds(20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);

Khan S. Alam 9 https://E-next.in


Unit-8 Event handling and GUI programming

public void mouseClicked(MouseEvent e)


{
l.setText("Mouse Clicked");
}

public void mouseEntered(MouseEvent e)


{
l.setText("Mouse Entered");
}

public void mouseExited(MouseEvent e)


{
l.setText("Mouse Exited");
}

public void mousePressed(MouseEvent e)


{
l.setText("Mouse Pressed");
}

public void mouseReleased(MouseEvent e)


{
l.setText("Mouse Released");
}

public static void main(String[] args)


{
new MouseListenerExample();
}
}
Output:

Khan S. Alam 10 https://E-next.in


Unit-8 Event handling and GUI programming

Q.7 State the five Layouts in Layout Manager for Java AWT. Show the layouts displayed by
each of these Layout.
Q.8 What is Layout? Explain diffrent types of layout manager in detail?
Q.9 Write a short note on BorderLyout and GridLayout.
Layout
 Layout means the arrangement of components within the container.
 In other way we can say that placing the components at a particular position within
the container.
 The task of layouting the controls is done automatically by the Layout Manager.

Layout Manager
 The layout manager automatically positions all the components within the container.
 If we do not use layout manager then also the components are positioned by the
default layout manager.
 It is possible to layout the controls by hand but it becomes very difficult because of
the following two reasons.
 It is very tedious to handle a large number of controls within the container.
 Oftenly the width and height information of a component is not given when we need
to arrange them.
 Java provide us with various layout manager to position the controls. The properties
like size, shape and arrangement varies from one layout manager to other layout
manager.
 When the size of the applet or the application window changes the size, shape and
arrangement of the components also changes in response i.e. the layout managers
adapt to the dimensions of applet viewer or the application window.
 The layout manager is associated with every Container object. Each layout manager
is an object of the class that implements the LayoutManager interface.

Java LayoutManagers:
 The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers.
 There are following AWT and Swing classes that represents the layout managers:
1) java.awt.BorderLayout
2) java.awt.FlowLayout
3) java.awt.GridLayout
4) java.awt.CardLayout
5) java.awt.GridBagLayout
6) javax.swing.BoxLayout
7) javax.swing.GroupLayout
8) javax.swing.ScrollPaneLayout
9) javax.swing.SpringLayout etc.

Khan S. Alam 11 https://E-next.in


Unit-8 Event handling and GUI programming

1. Java 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 BorderLayout provides five constants for each region:


1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER

Constructors of BorderLayout class:


 BorderLayout(): creates a border layout but with no gaps between the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given horizontal
and vertical gaps between the components.

Example of BorderLayout class:

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

public class Border


{
JFrame f;

Border()
{
f=new JFrame();

JButton b1=new JButton("NORTH");;


JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;

f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);

f.setSize(300,300);
f.setVisible(true);
}

Khan S. Alam 12 https://E-next.in


Unit-8 Event handling and GUI programming

public static void main(String[] args)


{
new Border();
}
}

Output:

2. Java GridLayout
 The GridLayout is used to arrange the components in rectangular grid.
 One component is displayed in each rectangle.

Constructors of GridLayout class


1. GridLayout(): creates a grid layout with one column per component in a row.
2. GridLayout(int rows, int columns): creates a grid layout with the given rows and
columns but no gaps between the components.
3. GridLayout(int rows, int columns, inthgap, intvgap): creates a grid layout with the
given rows and columns alongwith given horizontal and vertical gaps.

Example of GridLayout class

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

public class MyGridLayout


{
JFrame f;

MyGridLayout()
{
f=new JFrame();

Khan S. Alam 13 https://E-next.in


Unit-8 Event handling and GUI programming

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);
f.add(b6);
f.add(b7);
f.add(b8);
f.add(b9);

f.setLayout(new GridLayout(3,3)); //setting grid layout of 3 rows and 3 columns

f.setSize(300,300);
f.setVisible(true);
}

public static void main(String[] args)


{
new MyGridLayout();
}
}
Output:

Khan S. Alam 14 https://E-next.in


Unit-8 Event handling and GUI programming

3. Java FlowLayout
 The FlowLayout is used to arrange the components in a line, one after another (in a
flow).
 It is the default layout of applet or panel.

Fields of FlowLayout class


1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING

Constructors of FlowLayout class


1. FlowLayout(): creates a flow layout with centered alignment and a default 5 unit
horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a default 5
unit horizontal and vertical gap.
3. FlowLayout(int align, inthgap, intvgap): creates a flow layout with the given
alignment and the given horizontal and vertical gap.

Example of FlowLayout class

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

public class MyFlowLayout


{
JFrame f;

MyFlowLayout()
{
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

f.add(b1);
f.add(b2);
f.add(b3);
f.add(b4);
f.add(b5);

f.setLayout(new FlowLayout(FlowLayout.RIGHT)); //setting flow layout of right alignment

Khan S. Alam 15 https://E-next.in


Unit-8 Event handling and GUI programming

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

Output:

4. Java BoxLayout
 The BoxLayout is used to arrange the components either vertically or horizontally.
 For this purpose, BoxLayout provides four constants. They are as follows:
Fields of BoxLayout class
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS

Constructor of BoxLayout class


 BoxLayout(Container c, int axis): creates a box layout that arranges the components
with the given axis.

Example of BoxLayout class with Y-AXIS:

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

public class BoxLayoutExample1 extends Frame


{
Button buttons[];

Khan S. Alam 16 https://E-next.in


Unit-8 Event handling and GUI programming

public BoxLayoutExample1 ()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));

setSize(400,400);
setVisible(true);
}

public static void main(String args[])


{
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}

Output:

Example of BoxLayout class with X-AXIS

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

public class BoxLayoutExample2 extends Frame


{
Button buttons[];

Khan S. Alam 17 https://E-next.in


Unit-8 Event handling and GUI programming

public BoxLayoutExample2()
{
buttons = new Button [5];
for (int i = 0;i<5;i++)
{
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}

setLayout (new BoxLayout(this, BoxLayout.X_AXIS));

setSize(400,400);
setVisible(true);
}
public static void main(String args[])
{
BoxLayoutExample2 b=new BoxLayoutExample2();
}
}

Output:

5. Java CardLayout
 The CardLayout class manages the components in such a manner that only one
component is visible at a time.
 It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class


1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(inthgap, intvgap): creates a card layout with the given horizontal and
vertical gap.

Khan S. Alam 18 https://E-next.in


Unit-8 Event handling and GUI programming

Commonly used methods of CardLayout class


1. public void next(Container parent): is used to flip to the next card of the given
container.
2. public void previous(Container parent): is used to flip to the previous card of the
given container.
3. public void first(Container parent): is used to flip to the first card of the given
container.
4. public void last(Container parent): is used to flip to the last card of the given
container.
5. public void show(Container parent, String name): is used to flip to the specified
card with the given name.

Example of CardLayout class

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

public class CardLayoutExample extends JFrame implements ActionListener


{

CardLayout card;
JButton b1,b2,b3;
Container c;

CardLayoutExample()
{
c=getContentPane();
card=new CardLayout(40,30); //create object with 40 hor space and 30 ver space
c.setLayout(card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

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

Khan S. Alam 19 https://E-next.in


Unit-8 Event handling and GUI programming

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

Output:

Khan S. Alam 20 https://E-next.in


Unit-8 Event handling and GUI programming

Q.10 Explain any five swing components with an example.


Swing components
 A component is an independent visual control.
 Swing Framework contains a large set of components which provide rich
functionalities and allow high level of customization.
 They all are derived from JComponent class. All these components are lightweight
components.
 This class provides some common functionality like pluggable look and feel, support
for accessibility, drag and drop, layout, etc.
 A container holds a group of components. It provides a space where a component
can be managed and displayed.

Containers are of two types:


1. Top level Containers
 It inherits Component and Container of AWT.
 It cannot be contained within other containers.
 Heavyweight.
 Example: JFrame, JDialog, JApplet
2. Lightweight Containers
 It inherits JComponent class.
 It is a general purpose container.

Swing components

Khan S. Alam 21 https://E-next.in


Unit-8 Event handling and GUI programming

1. JButton
 JButton class provides functionality of a button.
 JButton class has three constuctors,
1. JButton(Icon ic)
2. JButton(String str)
3. JButton(String str, Icon ic)
 It allows a button to be created using icon, a string or both.
 JButton supports ActionEvent.
 When a button is pressed an ActionEvent is generated.

Example using JButton


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

public class testswing extends JFrame


{
testswing()
{

JButton bt1 = new JButton("Yes"); //Creating a Yes Button.


JButton bt2 = new JButton("No"); //Creating a No Button.

add(bt1); //adding Yes button to frame.


add(bt2); //adding No button to frame.

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.


setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
setVisible(true);
}

public static void main(String[] args)


{
newtestswing();
}
}

Output:

Khan S. Alam 22 https://E-next.in


Unit-8 Event handling and GUI programming

2. JTextField
 JTextField is used for taking input of single line of text. It is most widely used text
component.
 It has three constructors,
1. JTextField(int cols)
2. JTextField(String str, int cols)
3. JTextField(String str)
 cols represent the number of columns in text field.

Example using JTextField


Import javax.swing.*;
Import java.awt.event.*;
Import java.awt.*;

public class MyTextField extends JFrame


{
public MyTextField()
{

JTextField jtf = new JTextField(20); //creating JTextField.


add(jtf); //adding JTextField to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args)


{
newMyTextField();
}
}
Output:

Khan S. Alam 23 https://E-next.in


Unit-8 Event handling and GUI programming

3. JCheckBox
 JCheckBox class is used to create checkboxes in frame.
 Following is constructor for
1. JCheckBox,
2. JCheckBox(String str)

Example using JCheckBox

Import javax.swing.*;
Import java.awt.event.*;
Import java.awt.*;

public class Test extends JFrame


{
public Test()
{

JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.


add(jcb); //adding JCheckBox to frame.

jcb = new JCheckBox("no"); //creating JCheckBox.


add(jcb); //adding JCheckBox to frame.

jcb = new JCheckBox("maybe"); //creating JCheckBox.


add(jcb); //adding JCheckBox to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args)


{
new Test();
}
}

Output:

Khan S. Alam 24 https://E-next.in


Unit-8 Event handling and GUI programming

4. JRadioButton
 Radio button is a group of related button in which only one can be selected.
 JRadioButton class is used to create a radio button in Frames.
 Following is the constructor for JRadioButton,
JRadioButton(String str)

Example using JRadioButton

importjavax.swing.*;
importjava.awt.event.*;
importjava.awt.*;

public class Test extends JFrame


{
public Test()
{

JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.


add(jcb);
//adding JRadioButton to frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("C"); //creating JRadioButton.


add(jcb); //adding JRadioButton to frame.

jcb = new JRadioButton("none"); //creating JRadioButton.


add(jcb); //adding JRadioButton to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args)


{
new Test();
}
}
Output:

Khan S. Alam 25 https://E-next.in


Unit-8 Event handling and GUI programming

5. JComboBox
 Combo box is a combination of text fields and drop-down list.
 JComboBox component is used to create a combo box in Swing.
 Following is the constructor for JComboBox,
JComboBox(String arr[])

Example using JComboBox

importjavax.swing.*;
importjava.awt.event.*;
importjava.awt.*;

public class Test extends JFrame


{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.

public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list of name.
add(jc); //adding JComboBox to frame.

setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}

public static void main(String[] args)


{
new Test();
}
}

Output:

Khan S. Alam 26 https://E-next.in


Unit-8 Event handling and GUI programming

Q.11 Write a program to create a Web based GUI application for student registration form
using swing.
Q.12 Write a program to create a GUI by using any five controls of AWT.

Program for Student Registration Form:


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

public class swingForm extends JApplet


{
swingForm()
{
String lang [] = {“C”,”C++”,”Java”,”Pascal”,”PHP”,”.Net”};

JFframe jf = new JFrame (“Swing Component”);

JButton bok = new JButton (“Ok”);


JButton bclear = new JButton (“Clear”);

JRadioButton rm = new JRadioButton (“Male”, true);


JRadioButton rf = new JRadioButton (“Female”);
ButtonGroup bg = new ButtonGroup();
bg.add(rm);
bg.add(rf);

JLabel lgender = new Label (“Gender”);


JLabel los = new Label (“Operating System”);
JLabel lblank = new JLabel();

JCheckBox cb1 = new JCheckBox(“Dos”);


JCheckBox cb2 = new JCheckBox(“Windows”);
JCheckBox cb3 = new JCheckBox(“Linux”);
JCheckBox cb4 = new JCheckBox(“Mac”);

JLabel llang = new JLabel (“Languages Know”);


JList list = new JList (lang);

JScrollpane sb1 = new JScrollPane(list, ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS,


ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);

JLabel lna = new JLabel (“Name”);


JLabel ladd = new JLabel (“Address”);

JTextField tname = new JTextField(20);


JTextArea tadd = new JTextArea(2,20);

Khan S. Alam 27 https://E-next.in


Unit-8 Event handling and GUI programming

JPanel jp1 = new JPanel();


JPanel jp2 = new JPanel(new GridLayout(1,3));
JPanel jp3 = new JPanel();
JPanel jp4 = new JPanel(new GridLayout(1,2));

JPanel jp5 = new JPanel();


JPanel jp6 = new JPanel(new GridLayout(5,1));

jp1.add (lna);
jp1.add (tname);
jp1.add (ladd);
jp1.add (tadd);

jp2.add (lgender);
jp2.add (rm);
jp2.add (rf);

jp3.setLayout(new GridLayout(2,3));
jp3.add (los);
jp3.add (cb1);
jp3.add (cb2);
jp3.add (cb3);
jp3.add (cb4);

jp4.add (llang);
jp4.add (sb1, BorderLayout.NORTH);
jp4.add (bok);
jp4.add (bclear);

jp6.add (jp1);
jp6.add (jp2);
jp6.add (jp3);
jp6.add (jp4);
jp6.add (jp5);

jf.add (jp6);

jf.setDeafaultCloseOperation (jf.EXIT_ON_CLOSE);
jf.setSize (350, 400);
jjf.setVisible (true);
}

Public static void main (String [] args)


{
New swingForm();
}
}

Khan S. Alam 28 https://E-next.in


Unit-8 Event handling and GUI programming

Output:

Khan S. Alam 29 https://E-next.in


Unit-8 Event handling and GUI programming

Q.13 Write an applet program that will show GUI components like line, ellipse, polygon,
etc.
1. Applet Line Program:
//Drawing Lines

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

/*
<applet code="Lines" width=300 Height=250>
</applet>
*/

public class Lines extends Applet


{
public void paint(Graphics g)
{
g.drawLine(0,0,100,100);
g.drawLine(0,100,100,0);
g.drawLine(40,25,250,180);
g.drawLine(5,290,80,19);
}
}

Output:

Khan S. Alam 30 https://E-next.in


Unit-8 Event handling and GUI programming

2. Applet Rectangle Program

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

/*
<applet code="Rectangle" width=300 Height=300>
</applet>
*/

public class Rectanlge extends Applet


{
public void paint(Graphics g)
{
g.drawRect(10,10,60,50);
g.fillRect(100,100,100,0);
g.drawRoundRect(190,10,60,50,15,15);
g.fillRoundRect(70,90,140,100,30,40);
}
}

Output:

Khan S. Alam 31 https://E-next.in


Unit-8 Event handling and GUI programming

3. Applet Ellipses Program

*/
import java.awt.*;
import java.applet.*;
/*

<applet code="Ellipses" width=300 Height=300>


</applet>
*/

public class Ellipses extends Applet


{
public void paint(Graphics g)
{
g.drawOval(10,10,60,50);
g.fillOval(100,10,75,50);
g.drawOval(190,10,90,30);
g.fillOval(70,90,140,100);
}
}

Output:

Khan S. Alam 32 https://E-next.in


Unit-8 Event handling and GUI programming

4. Applet Arcs Program

*/
import java.awt.*;
import java.applet.*;
/*

<applet code="Arcs" width=300 Height=300>


</applet>
*/

public class Arcs extends Applet


{
public void paint(Graphics g)
{
g.drawArc(10,40,70,70,0,75);
g.fillArc(100,40,70,70,0,75);
g.drawArc(10,100,70,80,0,175);
g.fillArc(100,100,70,90,0,270);
g.drawArc(200,80,80,80,0,180);
}
}

Output:

Khan S. Alam 33 https://E-next.in


Unit-8 Event handling and GUI programming

5. Applet Polygon Program

*/
import java.awt.*;
import java.applet.*;
/*
<applet code="Polygon" width=300 Height=300>
</applet>
*/

public class Polygon extends Applet


{
public void paint(Graphics g)
{
int xpoints[]={30,200,30,200,30};
int ypoints[]={30,30,200,200,30};
int num=5;
g.drawPolygon(xpoints,ypoints,num);
}
}

Output:

Khan S. Alam 34 https://E-next.in

You might also like