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

JAVA UNIT - V

Uploaded by

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

JAVA UNIT - V

Uploaded by

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

R20 CMR Technical Campus

UNIT – V

GUI PROGRAMMING WITH SWING


Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based applications in
java. Java AWT components are platform-dependent i.e. components are displayed according to
the view of operating system. AWT is heavyweight i.e. its components are using the resources of OS.

The java.awt package provides classes for AWT Api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.

Fig: Java AWT Hierarchy

Limitations of AWT

The AWT defines a basic set of controls, windows, and dialog boxes that support a usable, but
limited graphical interface. One reason for the limited nature of the AWT is that it translates its
various visual components into their corresponding, platform-specific equivalents or peers. This

1 Syeda Sumaiya Afreen


R20 CMR Technical Campus
means that the look andfeel of a component is defined by the platform, not by java. Because the
AWT components use native code resources, they are referred to as heavy weight.

The use of native peers led to several problems. First, because of variations between operating
systems, acomponent might look, or even act, differently on different platforms. This variability
threatened java’s philosophy:

• First, write once run anywhere.


• Second, the look and feel of each component was fixed and could not be changed.
• Third, the use of heavyweight components caused some frustrating restrictions.

Model-View-Controller Architecture

The model-view-controller architecture (MVC) is the fundamental design behind each of its
components. Essentially, MVC breaks GUI components into three elements. Each of these
elements plays a crucial role in how the component behaves.

Model:
The model encompasses the state data for each component. There are different models for
different typesof components. For example, the model of a scrollbar component might contain
information about the current position of its adjustable “thumb,” its minimum and maximum
values, and the thumb’s width (relative to the range of values). A menu, on the other hand, may
simply contain a list of the menu items the user can select from. Note that this information
remains the same no matter how the component is painted on the screen; model data always exists
independent of the component’s visual representation.

View
The view refers to how you see the component on the screen. For a good example of how views
can differ,look at an application window on two different GUI platforms. Almost all window
frames will have a titlebar spanning the top of the window. However, the titlebar may have a
close box on the left side (like the olderMacOS platform), or it may have the close box on the
2 Syeda Sumaiya Afreen
R20 CMR Technical Campus
right side (as in the Windows 95 platform). These are examples of different types of views for
the same window object.

Controller
The controller is the portion of the user interface that dictates how the component interacts with
events. Events come in many forms — a mouse click, gaining or losing focus, a keyboard event
that triggers a specific menu command, or even a directive to repaint part of the screen. The
controller decides how eachcomponent will react to the event—if it reacts at all.

Container
The Container is a component in AWT that can contain another components like buttons,

3 Syeda Sumaiya Afreen


R20 CMR Technical Campus
textfields, labels etc. The classes that extends Container class are known as container such as
Frame, Dialog and Panel.

Window
The window is the container that have no borders and menu bars. You must use frame, dialog or
another window for creating a window.

Panel
The Panel is the container that doesn't contain title bar and menu bars. It can have other
components likebutton, textfield etc.

Frame
The Frame is the container that contain title bar and can have menu bars. It can have other
components like button, textfield etc.

Useful Methods of Component class

Method Description

public void add(Component inserts a component on this component.


c)

public void setSize(int sets the size (width and height) of the
width,int height) component.

public void defines the layout manager for the


setLayout(LayoutManager m) component.

public void changes the visibility of the component, by


setVisible(boolean status) default false.

AWT Example
4 Syeda Sumaiya Afreen
R20 CMR Technical Campus
To create simple awt example, you need a frame. There are two ways to create a frame in AWT.
o By extending Frame class (inheritance)
o By creating the object of Frame class (association)
AWT Example by Inheritance
1. import java.awt.*;
2. class First extends Frame{
3. First(){
4. Button b=new Button("click me");
5. b.setBounds(30,100,80,30);// setting button position
6. add(b);//adding button into frame
7. setSize(300,300);//frame size 300 width and 300 height
8. setLayout(null);//no layout manager
9. setVisible(true);//now frame will be visible, by default not visible
10. }
11. public static void main(String args[]){
12. First f=new First();
13. }}

Output:

AWT Example by Association


1. import java.awt.*;

5 Syeda Sumaiya Afreen


R20 CMR Technical Campus
2. class First2{
3. First2(){
4. Frame f=new Frame();
5. Button b=new
Button("click me");
6. b.setBounds(30,50,80,30
);
7. f.add(b);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void
main(String args[]){
13. First2 f=new First2();
14. }}
Output:

Components

AWT Button
The button class is used to create a labeled button that has platform independent implementation.
Theapplication result in some action when the button is pushed.
6 Syeda Sumaiya Afreen
R20 CMR Technical Campus

AWT Button Example


1. import java.awt.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. Frame f=new Frame("Button Example");
5. Button b=new
Button("Click Here");
6. b.setBounds(50,100,80,30
);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(t
rue);
11. }}
Output:

AWT Label
The object of Label class is a component for placing text in a container. It is used to display a
single line ofread only text. The text can be changed by an application but a user cannot edit it
7 Syeda Sumaiya Afreen
R20 CMR Technical Campus
directly.

AWT Label Example


1. import java.awt.*;
2. class LabelExample{
3. public static void main(String args[]){
4. Frame f= new Frame("Label Example");
5. Label l1,l2;
6. l1=new Label("First Label.");
7. l1.setBounds(50,100, 100,30);
8. l2=new Label("Second Label.");
9. l2.setBounds(50,150, 100,30);
10. f.add(l1);
11. f.add(l2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }}
Output:

AWT TextField
The object of a TextField class is a text component that allows the editing of a single line text. It
inheritsTextComponent class.
AWT TextField Example
8 Syeda Sumaiya Afreen
R20 CMR Technical Campus
1. import java.awt.*;
2. class TextFieldExample{
3. public static void main(String args[]){
4. Frame f= new Frame("TextField Example");
5. TextField t1,t2;
6. t1=new TextField("Welcome to CMR TC.");
7. t1.setBounds(50,100, 200,30);
8. t2=new TextField("II CSM");
9. t2.setBounds(50,150, 200,30);
10. f.add(t1);
11. f.add(t2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }}

Output:

AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the editing of
multiple linetext. It inherits TextComponent class.
AWT TextArea Example
9 Syeda Sumaiya Afreen
R20 CMR Technical Campus
1. import java.awt.*;
2. public class TextAreaExample
3. {
4. TextAreaExample(){
5. Frame f= new Frame();
6. TextArea area=new TextArea("Welcome to CMR TC"); \
7. area.setBounds(10,50, 300,300);
8. f.add(area);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();
16. } }

Output:

AWT Checkbox
The Checkbox class is used to create a checkbox. It is used to turn an option on (true) or off
(false). Clickingon a Checkbox changes its state from "on" to "off" or from "off" to "on".
AWT Checkbox Example
1. import java.awt.*;
10 Syeda Sumaiya Afreen
R20 CMR Technical Campus
2. public class CheckboxExample
3. {
4. CheckboxExample(){
5. Frame f= new Frame("Checkbox Example");
6. Checkbox checkbox1 = new Checkbox("C++");
7. checkbox1.setBounds(100,100, 50,50);
8. Checkbox checkbox2 = new Checkbox("Java", true);
9. checkbox2.setBounds(100,150, 50,50);
10. f.add(checkbox1);
11. f.add(checkbox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new CheckboxExample();
19. } }

Output:

AWT CheckboxGroup
The object of CheckboxGroup class is used to group together a set of Checkbox. At a time only

11 Syeda Sumaiya Afreen


R20 CMR Technical Campus
one check box button is allowed to be in "on" state and remaining check box button in "off" state.
It inherits the object class.

Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for
creating radio buttons in AWT.

AWT CheckboxGroup Example


1. import java.awt.*;
2. public class CheckboxGroupExample
3. {
4. CheckboxGroupExample(){
5. Frame f= new Frame("CheckboxGroup Example");
6. CheckboxGroup cbg = new CheckboxGroup();
7. Checkbox checkBox1 = new
Checkbox("C++", cbg, false);
8. checkBox1.setBounds(100,100, 50,50);
9. Checkbox checkBox2 = new Checkbox("Java", cbg, true);
10. checkBox2.setBounds(100,150, 50,50);
11. f.add(checkBox1);
12. f.add(checkBox2);
13. f.setSize(400,400);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String args[])
18. {
19. new CheckboxGroupExample();
20. } }
Output:

12 Syeda Sumaiya Afreen


R20 CMR Technical Campus

AWT Choice
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on thetop of a menu. It inherits Component class.
AWT Choice Example
1. import java.awt.*;
2. public class ChoiceExample
3. {
4. ChoiceExample(){
5. Frame f= new Frame();
6. Choice c=new Choice();
7. c.setBounds(100,100, 75,75);
8. c.add("Item 1");
9. c.add("Item 2");
10. c.add("Item 3");
11. c.add("Item 4");
12. c.add("Item 5");
13 Syeda Sumaiya Afreen
R20 CMR Technical Campus
13. f.add(c);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ChoiceExample();
21. } }

Output:

AWT List
The object of List class represents a list of text items. By the help of list, user can choose either
one itemor multiple items. It inherits Component class.
AWT List Example
1. import java.awt.*;
2. public class ListExample
3. {
4. ListExample(){
5. Frame f= new Frame();
6. List l1=new List(5);
14 Syeda Sumaiya Afreen
R20 CMR Technical Campus
7. l1.setBounds(100,100, 75,75);
8. l1.add("Item 1");
9. l1.add("Item 2");
10. l1.add("Item 3");
11. l1.add("Item 4");
12. l1.add("Item 5");
13. f.add(l1);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. } }

Output:

AWT Canvas
The Canvas control represents a blank rectangular area where the application can draw or
trapinput events from the user. It inherits the Component class.
AWT Canvas Example
1. import java.awt.*;
2. public class CanvasExample
3. {
4. public
15 Syeda Sumaiya Afreen
R20 CMR Technical Campus
CanvasExample()
5. {
6. Frame f= new Frame("Canvas Example");
7. f.add(new MyCanvas());
8. f.setLayout(n
ull);
9. f.setSize(400, 400);
10. f.setVisible(true);
11. }
12. public static void main(String args[])
13. {
14. new CanvasExample();
15. }
16. }
17. class MyCanvas extends Canvas
18. {
19. public MyCanvas() {
20. setBackground (Color.GRAY);
21. setSize(300, 200);
22. }
23. public void paint(Graphics g)
24. {
25. g.setColor(Color.red);
26. g.fillOval(75, 75, 150, 75);
27. } }
Output:

16 Syeda Sumaiya Afreen


R20 CMR Technical Campus
AWT Scrollbar
The object of Scrollbar class is used to add horizontal and vertical scrollbar. Scrollbar is a
GUI componentallows us to see invisible number of rows and columns.
AWT Scrollbar Example
1. import java.awt.*;
2. class ScrollbarExample{
3. ScrollbarExample(){
4. Frame f= new Frame("Scrollbar Example");
5. Scrollbar s=new Scrollbar();
6. s.setBounds(100,100, 50,100);
7. f.add(s);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public static void main(String args[]){
13. new ScrollbarExample();
14. }}
Output:

AWT MenuItem and Menu


The object of MenuItem class adds a simple labeled menu item on menu. The items used in a
menu mustbelong to the MenuItem or any of its subclass.

The object of Menu class is a pull down menu component which is displayed on the menu bar.

17 Syeda Sumaiya Afreen


R20 CMR Technical Campus
It inheritsthe MenuItem class.
AWT MenuItem and Menu Example
1. import java.awt.*;
2. class
MenuExample 3.
{
4. MenuExample(){
5. Frame f= new Frame("Menu and MenuItem Example");
6. MenuBar mb=new MenuBar();
7. Menu menu=new Menu("Menu");
8. Menu submenu=new Menu("Sub Menu");
9. MenuItem i1=new MenuItem("Item 1");
10. MenuItem i2=new MenuItem("Item 2");
11. MenuItem i3=new MenuItem("Item 3");
12. MenuItem i4=new MenuItem("Item 4");
13. MenuItem i5=new MenuItem("Item 5");
14. menu.add(i1);
15. menu.add(i2);
16. menu.add(i3);
17. submenu.add(i4);
18. submenu.add(i5);
19. menu.add(submenu);
20. mb.add(menu);
21. f.setMenuBar(mb);
22. f.setSize(400,400);
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public static void main(String args[])
27. {

18 Syeda Sumaiya Afreen


R20 CMR Technical Campus
28. new MenuExample();
29. }}

Output:

AWT PopupMenu
PopupMenu can be dynamically popped up at specific position within a component. It inherits the
Menu class.
AWT PopupMenu Example
1. import java.awt.*;
2. import java.awt.event.*;
3. class
PopupMenuExample
4. {
5. PopupMenuExample(){
6. final Frame f= new Frame("PopupMenu Example");
7. final PopupMenu popupmenu = new PopupMenu("Edit");
8. MenuItem cut = new MenuItem("Cut");
9. cut.setActionCommand("Cut");
10. MenuItem copy = new MenuItem("Copy");
11. copy.setActionCommand("Copy");
12. MenuItem paste = new MenuItem("Paste");

19 Syeda Sumaiya Afreen


R20 CMR Technical Campus
13. paste.setActionCommand("Paste");
14. popupmenu.add(cut);
15. popupmenu.add(copy);
16. popupmenu.add(paste);
17. f.addMouseListener(new MouseAdapter() {
18. public void mouseClicked(MouseEvent e) {
19. popupmenu.show(f , e.getX(), e.getY());
20. }
21. });
22. f.add(popupmenu);
23. f.setSize(400,400);
24. f.setLayout(null);
25. f.setVisible(true);
26. }
27. public static void main(String args[])
28. {
29. new
PopupMenuExample(); 30.
}}
Output:

AWT Panel
The Panel is a simplest container class. It provides space in which an application can attach any
othercomponent. It inherits the Container class. It doesn't have title bar.
AWT Panel Example
1. import java.awt.*;
20 Syeda Sumaiya Afreen
R20 CMR Technical Campus
2. public class PanelExample {
3. PanelExample()
4. {
5. Frame f= new Frame("Panel Example");
6. Panel panel=new Panel();
7. panel.setBounds(40,80,200,200);
8. panel.setBackground(Color.gray);
9. Button b1=new
Button("Button 1");
10. b1.setBounds(50,100,80,30);
11. b1.setBackground(Color.yellow);
12. Button b2=new Button("Button 2");
13. b2.setBounds(100,100,80,30);
14. b2.setBackground(Color.green);
15. panel.add(b1); panel.add(b2);
16. f.add(panel);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String args[])
22. {
23. new
PanelExample();
24. } }
Output:

21 Syeda Sumaiya Afreen


R20 CMR Technical Campus
AWT Dialog
The Dialog control represents a top level window with a border and a title used to take some
form of inputfrom the user. It inherits the Window class. Unlike Frame, it doesn't have
maximize and minimize buttons.

Note: Frame and Dialog both inherits Window class. Frame has maximize and minimize
buttons but Dialogdoesn't have.
AWT Dialog Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class DialogExample {
4. private static Dialog d;
5. DialogExample() {
6. Frame f= new Frame();
7. d = new Dialog(f , "Dialog Example", true);
8. d.setLayout( new FlowLayout() );
9. Button b = new Button ("OK");
10. b.addActionListener ( new ActionListener()
11. {
12. public void actionPerformed( ActionEvent e )
13. {
14. DialogExample.d.setVisible(false);
15. }
16. });
17. d.add( new Label ("Click button to continue."));
18. d.add(b);
19. d.setSize(300,300);
20. d.setVisible(true);
21. }
22. public static void main(String args[])

22 Syeda Sumaiya Afreen


R20 CMR Technical Campus
23. {
24. new
DialogExample();
25. } }
Output:

Understanding Layout Managers

The LayoutManagers are used to arrange components in a particular manner. LayoutManager is an


interfacethat is implemented by all the classes of layout managers. There are following 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

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

23 Syeda Sumaiya Afreen


R20 CMR Technical Campus
5. public static final int CENTER

Constructors of BorderLayout class:


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

Example of BorderLayout class:


1. import java.awt.*;
2. import
javax.swing.*; 3.
4. public class Border {
5. JFrame f;
6. Border(){
7. f=new
JFrame(); 8.
9. JButton b1=new JButton("NORTH");;
10. JButton b2=new JButton("SOUTH");;
11. JButton b3=new JButton("EAST");;
12. JButton b4=new JButton("WEST");;
13. JButton b5=new
JButton("CENTER");; 14.
15. f.add(b1,BorderLayout.NORTH);
16. f.add(b2,BorderLayout.SOUTH);
17. f.add(b3,BorderLayout.EAST);
18. f.add(b4,BorderLayout.WEST);
19. f.add(b5,BorderLayout.
CENTER); 20.
21. f.setSize(300,300);
22. f.setVisible(true);

24 Syeda Sumaiya Afreen


R20 CMR Technical Campus
23. }
24. public static void main(String[] args) {
25. new
Border();
26. } }
Output:

GridLayout

The GridLayout is used to arrange the components in rectangular grid. One component is displayed in
eachrectangle.
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 nogaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid layout with the
given rowsand columns along with given horizontal and vertical gaps.

Example of GridLayout class


1. import java.awt.*;
2. import javax.swing.*;
3. public class MyGridLayout{
4. JFrame f;
5. MyGridLayout(){
25 Syeda Sumaiya Afreen
R20 CMR Technical Campus
6. f=new JFrame();
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. JButton b6=new JButton("6");
13. JButton b7=new JButton("7");
14. JButton b8=new JButton("8");
15. JButton b9=new JButton("9");
16. f.add(b1);
17. f.add(b2);
18. f.add(b3);
19. f.add(b4) ;
20. f.add(b5);
21. f.add(b6);
22. f.add(b7);
23. f.add(b8);
24. f.add(b9);
25. f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3
columns
26. f.setSize(300,300);
27. f.setVisible(true);
28. }
29. public static void main(String[] args) {
30. new MyGridLayout();
31. }}

Output:

26 Syeda Sumaiya Afreen


R20 CMR Technical Campus

FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a flow). It is
the defaultlayout 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 andvertical gap.

2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unithorizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the given
alignment andthe given horizontal and vertical gap.

Example of FlowLayout class


1. import java.awt.*;
2. import javax.swing.*;
3. public class MyFlowLayout{
4. JFrame f;
5. MyFlowLayout(){
6. f=new JFrame();
27 Syeda Sumaiya Afreen
R20 CMR Technical Campus
7. JButton b1=new JButton("1");
8. JButton b2=new JButton("2");
9. JButton b3=new JButton("3");
10. JButton b4=new JButton("4");
11. JButton b5=new JButton("5");
12. f.add(b1);f.add(b2);f.add(b3);f.a
dd(b4);f.add(b5);
13. f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment
14.

21. f.setVisible(true);
22. }
23. public static void main(String[] args) {
24. new
MyFlowLayout();
25. } }
Output:

CardLayout

The CardLayout class manages the components in such a manner that only one component is
visible at atime. 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.
28 Syeda Sumaiya Afreen
R20 CMR Technical Campus
2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical
gap.

Commonly used methods of CardLayout class


o public void next(Container parent): is used to flip to the next card of the given container.
o public void previous(Container parent): is used to flip to the previous card of
the givencontainer.
o public void first(Container parent): is used to flip to the first card of the given container.
o public void last(Container parent): is used to flip to the last card of the given container.
o public void show(Container parent, String name): is used to flip to the specified card
with thegiven name.

Example of CardLayout class


1. import java.awt.*;
2. import
java.awt.event.*;
3.
4. import
javax.swing.*;
5.
6. public class CardLayoutExample extends JFrame implements ActionListener{

7. CardLayout card;
8. JButton b1,b2,b3;
9. Container c;
10. CardLayoutExa
mple(){ 11.
12. c=getContentPane();
13. card=new CardLayout(40,30);
14. //create CardLayout object with 40 hor space and 30 ver space

29 Syeda Sumaiya Afreen


R20 CMR Technical Campus
15. c.setLayout(
card); 16.
17. b1=new JButton("Apple");
18. b2=new JButton("Boy");
19. b3=new JButton("Cat");
20. b1.addActionListener(this);
21. b2.addActionListener(this);
22. b3.addActionListener(this);
23. c.add("a",b1);
24. c.add("b",b2);
25. c.add("c",b3);
26. }public void actionPerformed(ActionEvent e) {
27. card.next(c);
28. }
29. public static void main(String[] args) {
30. CardLayoutExample cl=new CardLayoutExample();
31. cl.setSize(400,400);
32. cl.setVisible(true);
33. cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
34. } }

Output:

GridBagLayout
The Java GridBagLayout class is used to align components vertically, horizontally or along their
30 Syeda Sumaiya Afreen
R20 CMR Technical Campus
baseline.

The components may not be of same size. Each GridBagLayout object maintains a dynamic,
rectangular grid of cells. Each component occupies one or more cells known as its display area.
Each component associates an instance of GridBagConstraints. With the help of constraints
object we arrange component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine component's size.

Fields

Modifier and Type Field Description

double[] columnWeight It is used to hold the overrides to the column weights.


s

int[] columnWidths It is used to hold the overrides to the column minimum


width.

protected comptable It is used to maintains the association between a


Hashtable<Component,Gr component and its gridbag constraints.
idBagC onstraints>

protected defaultConstra It is used to hold a gridbag constraints instance


GridBagConstraints ints containing the default values.

protected layoutInfo It is used to hold the layout information for the gridbag.
GridBagLayoutInfo

31 Syeda Sumaiya Afreen


R20 CMR Technical Campus
protected static int MAXGRIDSI No longer in use just for backward compatibility
ZE

protected static int MINSIZE It is smallest grid that can be laid out by the grid bag
layout.

protected static int PREFERRED It is preferred grid size that can be laid out by the grid
SIZE bag layout.

int[] rowHeights It is used to hold the overrides to the row minimum


heights.

double[] rowWeights It is used to hold the overrides to the row weights.

Useful Methods

Modifier and Method Description


Type

Void addLayoutComponent(Co It adds specified component to the layout,


mponent comp, Object using the specified constraints object.
constraints)

Void addLayoutComponent(St It has no effect, since this layout manager


ring name, Component does not use a per- component string.
comp)

protected void adjustForGravity(GridBag It adjusts the x, y, width, and height fields to


Constraints constraints, the correct values depending on the
Rectangle r) constraint geometry and pads.

protected void AdjustForGravity(GridBa This method is for backwards compatibility


gConstraints constraints, only
Rectangle r)

protected void arrangeGrid(Container parent) Lays out the grid.

32 Syeda Sumaiya Afreen


R20 CMR Technical Campus

protected void ArrangeGrid(Container This method is obsolete and supplied


parent) for backwards compatibility

GridBagConstr getConstraints(Component It is for getting the constraints for the


aints comp) specified component.

Float getLayoutAlignmentX(Contai It returns the alignment along the x axis.


ner parent)

Float getLayoutAlignmentY(Contai It returns the alignment along the y axis.


ner parent)

int[][] getLayoutDimensions() It determines column widths and row


heights for the layout grid.

protected getLayoutInfo(Container This method is obsolete and supplied


GridBagLayoutI parent, int sizeflag) for backwards compatibility.
nfo

protected GetLayoutInfo(Container This method is obsolete and supplied


GridBagLayoutI parent, int sizeflag) for backwards compatibility.
nfo

Point getLayoutOrigin() It determines the origin of the layout area, in


the graphics coordinate space of the target
container.

double[][] getLayoutWeights() It determines the weights of the layout


grid's columns and rows.

protected getMinSize(Contain It figures out the minimum size of the master


Dimension er parent, based on the information from
GridBagLayoutInfo getLayoutInfo.
info)

protected GetMinSize(Contain This method is obsolete and supplied


Dimension er parent, for backwards compatibility only

33 Syeda Sumaiya Afreen


R20 CMR Technical Campus
GridBagLayoutInfo
info)

Example 1
1. import java.awt.Button;
2. import java.awt.GridBagConstraints;
3. import
java.awt.GridBagLayout; 4.
5. import javax.swing.*;
6. public class GridBagLayoutExample extends JFrame{

7. public static void main(String[] args) {


8. GridBagLayoutExample a = new
GridBagLayoutExample(); 9. }
10. public GridBagLayoutExample() {
11. GridBagLayout grid = new GridBagLayout();
12. GridBagConstraints gbc = new GridBagConstraints();
13. setLayout(grid);
14. setTitle("GridBag Layout Example");
15. GridBagLayout layout = new GridBagLayout();
16. this.setLayout(layout);
17. gbc.fill = GridBagConstraints.HORIZONTAL;
18. gbc.gridx = 0;
19. gbc.gridy = 0;
20. this.add(new Button("Button One"), gbc);
21. gbc.gridx = 1;
22. gbc.gridy = 0;
23. this.add(new Button("Button two"), gbc);
24. gbc.fill = GridBagConstraints.HORIZONTAL;
25. gbc.ipady = 20;
34 Syeda Sumaiya Afreen
R20 CMR Technical Campus
26. gbc.gridx = 0;
27. gbc.gridy = 1;
28. this.add(new Button("Button Three"), gbc);
29. gbc.gridx = 1;
30. gbc.gridy = 1;
31. this.add(new Button("Button Four"), gbc);
32. gbc.gridx = 0;
33. gbc.gridy = 2;
34. gbc.fill = GridBagConstraints.HORIZONTAL;
35. gbc.gridwidth = 2;
36. this.add(new Button("Button
Five"), gbc); 37.
setSize(300, 300);
38. setPreferredSize(getSize());
39. setVisible(true);
40. setDefaultCloseOperation(EXIT_O
N_CLOSE); 41. } }
Output:

EVENT HANDLING(EVENT AND LISTENER)


Changing the state of an object is known as an event. For example, click on button, dragging
mouse etc. The java.awt.event package provides many event classes and Listener interfaces for
event handling.
35 Syeda Sumaiya Afreen
R20 CMR Technical Campus

The Delegation Event Model


The modern approach to handling events is based on the delegation event model, which defines
standard and consistent mechanisms to generate and process events. Its concept is quite simple: a
source generatesan event and sends it to one or more listeners. In this scheme, the listener simply
waits until it receives anevent. Once an event is received, the listener processes the event and then
returns. The advantage of thisdesign is that the application logic that processes events is cleanly
separated from the user interface logic that generates those events. A user interface element is
able to “delegate” the processing of an event to aseparate piece of code.

In the delegation event model, listeners must register with a source in order to receive an event
notification.This provides an important benefit: notifications are sent only to listeners that want
to receive them.

Events
In the delegation model, an event is an object that describes a state change in a source. Among
other causes, an event can be generated as a consequence of a person interacting with the elements
in a graphicaluser interface. Some of the activities that cause events to be generated are pressing
a button, entering a character via the keyboard, selecting an item in a list, and clicking the mouse.
Many other user operationscould also be cited as examples.

Events may also occur that are not directly caused by interactions with a user interface. For
example, an event may be generated when a timer expires, a counter exceeds a value, a software
or hardware failure occurs, or an operation is completed. You are free to define events that are
appropriate for your application.

Event Sources
A source is an object that generates an event. This occurs when the internal state of that object
changes insome way. Sources may generate more than one type of event.

36 Syeda Sumaiya Afreen


R20 CMR Technical Campus
A source must register listeners in order for the listeners to receive notifications about a specific
type of event. Each type of event has its own registration method. Here is the general form:
public void addTypeListener (TypeListener el )

Here, Type is the name of the event, and el is a reference to the event listener. For example, the
method that registers a keyboard event listener is called addKeyListener( ). The method that
registers a mouse motion listener is called addMouseMotionListener( ). When an event occurs,
all registered listeners are notified and receive a copy of the event object. This is known as
multicasting the event. In all cases, notifications are sent only to listeners that register to receive
them.

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

The methods that receive and process events are defined in a set of interfaces, such as those
foundin java.awt.event. For example, the MouseMotionListener interface defines two methods
to receive notifications when the mouse is dragged or moved. Any object may receive and process
one or both of these events if it provides an implementation of this interface.

Event Classes
The classes that represent events are at the core of Java’s event handling mechanism. Thus, a
discussion of event handling must begin with the event classes. It is important to understand,
however, that Java defines several types of events and that not all event classes can be discussed
in this chapter. Arguably, the most widely used events at the time of this writing are those defined
by the AWT and those defined bySwing. This chapter focuses on the AWT events. (Most of these
events also apply to Swing.)

At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the
37 Syeda Sumaiya Afreen
R20 CMR Technical Campus
superclass for allevents. Its one constructor is shown here:
EventObject(Object src)
Here, src is the object that generates this event.

EventObject defines two methods: getSource( ) and toString( ). The getSource( ) method returns
the source of the event. Its general form is shown here:
Object getSource( )
As expected, toString( ) returns the string equivalent of the event.

Event classes and Listener interfaces


Event Classes Listener Interfaces

ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

38 Syeda Sumaiya Afreen


R20 CMR Technical Campus
Steps to perform Event Handling
Following steps are required to perform event
handling:
1. Register the component with the Listener
Registration Methods
For registering the component with the Listener, many classes provide the registration
methods.For example:
o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

We can put the event handling code into one of the following places:

1. Within class

2. Other class

event handling by implementing ActionListener


1. import java.awt.*;

39 Syeda Sumaiya Afreen


R20 CMR Technical Campus
2. import java.awt.event.*;
3. class AEvent extends Frame implements ActionListener{
4. TextField tf;
5. AEven
t(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new
Button("click me");
10. b.setBounds(100,120,80,
30);
11. //register listener
12. b.addActionListener(this);//passing
current instance
13. //add components and set size, layout and visibility
14. add(b);add(t
f);
15. setSize(300,300);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void
actionPerformed(ActionEvent e){
20. tf.setText("Welcome");
21. }
22. public static void main(String args[]){
23. new AEvent();
24. }}

40 Syeda Sumaiya Afreen


R20 CMR Technical Campus
Output:

event handling by outer class


1. import java.awt.*;
2. import java.awt.event.*;
3. class AEvent2 extends Frame{
4. TextField tf;
5. AEvent2(){
6. //create components
7. tf=new TextField();
8. tf.setBounds(60,50,170,20);
9. Button b=new
Button("click me"); 10.
b.setBounds(100,120,80,30);
11. //register listener
12. Outer o=new Outer(this);
13. b.addActionListener(o);//passing outer class instance
14. //add components and set size, layout and visibility
15. add(b);add(t
f); 16.
setSize(300,300)
;
17. setLayout(null);
18. setVisible(true);
19. }
20. public static void main(String args[]){
21. new
41 Syeda Sumaiya Afreen
R20 CMR Technical Campus
AEvent2();
22. } }

1. import java.awt.event.*;
2. class Outer implements ActionListener{
3. AEvent2 obj;
4. Outer(AEvent2 obj){
5. this.obj=
obj; 6. }
7. public void actionPerformed(ActionEvent e){
8. obj.tf.setText("welc
ome"); 9. }}
Output:

MouseListener Interface
The Java MouseListener is notified whenever you change the state of mouse. It is notified
againstMouseEvent. The MouseListener interface is found in java.awt.event package. It has five
methods.
Methods of MouseListener interface
1. public abstract void mouseClicked(MouseEvent e);
2. public abstract void mouseEntered(MouseEvent e);

42 Syeda Sumaiya Afreen


R20 CMR Technical Campus
3. public abstract void mouseExited(MouseEvent e);

4. public abstract void mousePressed(MouseEvent e);


5. public abstract void mouseReleased(MouseEvent e);
Example1
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseListenerExample extends Frame implements MouseListener{
4. Label l;
5. MouseListenerExample(){

6. addMouseListener
(this); 7.
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. add(l);
11. setSize(300,300);
12. setLayout(null);
13. setVisible(true);
14. }
15. public void mouseClicked(MouseEvent e) {
16. l.setText("Mouse Clicked");
17. }
18. public void mouseEntered(MouseEvent e) {
19. l.setText("Mouse Entered");
20. }
21. public void mouseExited(MouseEvent e) {
22. l.setText("Mouse Exited");
23. }
24. public void mousePressed(MouseEvent e) {
25. l.setText("Mouse Pressed");
43 Syeda Sumaiya Afreen
R20 CMR Technical Campus
26. }
27. public void mouseReleased(MouseEvent e) {
28. l.setText("Mouse Released");
29. }
30. public static void main(String[] args) {
31. new
MouseListenerExample();
32. } }
Output:

KeyListener Interface
The Java KeyListener is notified whenever you change the state of key. It is notified against
KeyEvent. TheKeyListener interface is found in java.awt.event package. It has three methods.
Methods of KeyListener interface
1. public abstract void keyPressed(KeyEvent e);
2. public abstract void keyReleased(KeyEvent e);
3. public abstract void keyTyped(KeyEvent e);
KeyListener Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class KeyListenerExample extends Frame implements KeyListener{
4. Label l;
5. TextArea area;
6. KeyListenerExa
mple()
44 Syeda Sumaiya Afreen
R20 CMR Technical Campus
7. {
8. l=new Label();
9. l.setBounds(20,50,100,20);
10. area=new TextArea();
11. area.setBounds(20,80,300, 300);
12.
area.addKeyListene
r(this); 13.
add(l);add(area);
14. setSize(400,400);
15. setLayout(null);
16. setVisible(true);
17.}
18. public void keyPressed(KeyEvent e) {
19. l.setText("Key Pressed");
20. }
21. public void keyReleased(KeyEvent e) {
22. l.setText("Key Released");
23. }
24. public void keyTyped(KeyEvent e) {
25. l.setText("Key Typed");
26.

} 27.
28. public static void
main(String[] args) {
29. new
KeyListenerExample(); 30.
} }
Output:

45 Syeda Sumaiya Afreen


R20 CMR Technical Campus

Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If you inherit the
adapter class, youwill not be forced to provide the implementation of all the methods of listener
interfaces. So it saves code.

The adapter classes are found in java.awt.event, java.awt.dnd and javax.swing.event


packages. The Adapterclasses with their corresponding listener interfaces are given below.

MouseAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseAdapterExample extends MouseAdapter{
4. Frame f;
5. MouseAdapterExample(){
6. f=new Frame("Mouse Adapter");
7. f.addMouseListene
r(this);
8. f.setLayout(null);
9. f.setVisible(true);
10. }
11. public void mouseClicked(MouseEvent e)
12. {
13. Graphics g=f.getGraphics();
14. g.setColor(Color.BLUE);

46 Syeda Sumaiya Afreen


R20 CMR Technical Campus
15. g.fillOval(e.getX(),e.getY(),30,30);
16. }
17. public static void main(String[]
args)
18. {
19. new
MouseAdapterExample();
20. } }
Output:

MouseMotionAdapter Example
1. import java.awt.*;
2. import java.awt.event.*;
3. public class MouseMotionAdapterExample extends MouseMotionAdapter{
4. Frame f;
5. MouseMotionAdapterExample(){
6. f=new Frame("Mouse Motion Adapter");
7. f.addMouseMotionListe
ner(this);
8. f.setSize(300,300);
9. f.setLayout(null);
10. f.setVisible(true);
11. }
12. public void mouseDragged(MouseEvent e) {
13. Graphics g=f.getGraphics();
14. g.setColor(Color.ORANGE);
15. g.fillOval(e.getX(),e.getY(),20,20);
47 Syeda Sumaiya Afreen
R20 CMR Technical Campus
16. }
17. public static void main(String[] args) {
18. new
MouseMotionAdapterExample()
;
19. }}
Output:

Java Inner Classes

Java inner class or nested class is a class which is declared inside the class or interface.

We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.

Additionally, it can access all the members of outer class including private data members and methods.

Syntax of Inner class

1. class Java_Outer_class{

2. //code
3. class Java_Inner_class{

4. //code
5. }

6. }

48 Syeda Sumaiya Afreen


R20 CMR Technical Campus

Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:

1) Nested classes represent a special type of relationship that is it can access all the members (data

members and methods) of outer class including private.

2) Nested classes are used to develop more readable and maintainable code because itlogically

group classes and interfaces in one place only.


3) Code Optimization: It requires less code to write.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested classes
are also known as inner classes.

o Non-static nested class (inner class)

1. Member inner class

2. Anonymous inner class

3. Local inner class

o Static nested class

Type Description

MemberInner Class A class created within class and outside method.

Anonymous Inner Class A class created for implementing interface or


extending class. Its name is decided by the java

49 Syeda Sumaiya Afreen


R20 CMR Technical Campus
compiler.

Local Inner Class A class created within method.

Static Nested Class A static class created within class.

Nested Interface An interface created within class or interface.

Java Anonymous inner class

A class that have no name is known as anonymous inner class in java. It should be used if youhave to

override method of class or interface. Java Anonymous inner class can be created by two ways:

1. Class (may be abstract or concrete).

2. Interface

Java anonymous inner class example using class

1. abstract class Person{

2. abstract void eat();


3. }

4. class TestAnonymousInner{
5. public static void main(String args[]){

6. Person p=new Person(){


7. void eat(){System.out.println("nice fruits");}

8. };
9. p.eat();

50 Syeda Sumaiya Afreen


R20 CMR Technical Campus
10. }
11. }
Test it Now

Output:

nice fruits

Internal working of given code

1. Person p=new Person(){

2. void eat(){System.out.println("nice fruits");}


3. };

1. A class is created but its name is decided by the compiler which extends the Person class and
provides the implementation of the eat() method.
2. An object of Anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler

1. import java.io.PrintStream;

2. static class TestAnonymousInner$1 extends Person


3. {

4. TestAnonymousInner$1(){}
5. void eat()

6. {
System.out.println("nice fruits");

8. }
9. }
51 Syeda Sumaiya Afreen
R20 CMR Technical Campus
Java anonymous inner class example using interface

1. interface Eatable{

2. void eat();
3. }

4. class TestAnnonymousInner1{
5. public static void main(String args[]){

6. Eatable e=new Eatable(){


7. public void eat(){System.out.println("nice fruits");}

8. };
9. e.eat();

10. }
11. }

JAVA APPLET
Applet is a special type of program that is embedded in the webpage to generate the dynamic
content. Itruns inside the browser and works at client side.

Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, Mac Osetc.
Drawback of Applet
o Plugin is required at client browser to execute applet.

Hierarchy of Applet

52 Syeda Sumaiya Afreen


R20 CMR Technical Campus

Applet class extends Panel. Panel class extends Container which is the subclass of Component.

Security Issues with the Applet

• Applets are loaded over the internet and they are prevented to make open network connection
to any computer, except for the host, which provided the . ...
• They are also prevented from starting other programs on the client. ...
• Applets are loaded over the net. ...
• They cant load the libraries or define the native method calls

Lifecycle of Java Applet

Lifecycle methods for Applet:


The java.applet.Applet class 4 life cycle methods and
53 Syeda Sumaiya Afreen
R20 CMR Technical Campus
java.awt.Component class provides 1 life cyclemethods for an applet.

java.applet.Applet class
For creating any applet java.applet.Applet class must be inherited. It provides 4 life cycle methods of
applet.
1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is used
to startthe Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser isminimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
The Component class provides 1 life cycle method of applet.
1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object thatcan be used for drawing oval, rectangle, arc etc.

Note: There are two ways to run an applet:


1. By html file.
2. By appletViewer tool (for testing purpose).

1. Simple example of Applet by html file:


To execute the applet by html file, create an applet and compile it. After that create an html file
and placethe applet code in html file. Now click the html file.
1. //First.java
2. import java.applet.Applet;
3. import java.awt.Graphics;
4. public class First
extends Applet{ 5.
6. public void paint(Graphics g){

54 Syeda Sumaiya Afreen


R20 CMR Technical Campus
7. g.drawString("welcome",
150,150); 8. } }

Note: class must be public because its object is created by Java Plugin software that resides on the browser.

first.html
1. <html>
2. <body>
3. <applet code="First.class" width="300" height="300">
4. </applet>
5. </body>
6. </html>

2. Simple example of Applet by appletviewer tool:


To execute the applet by appletviewer tool, create an applet that contains applet tag in comment
and compile it. After that run it by: appletviewer First.htm. Now Html file is not required but it
is for testing purpose only.
Output:

Displaying Graphics in Applet


java.awt.Graphics class provides many methods for graphics programming.

Commonly used methods of Graphics class:


1. public abstract void drawString(String str, int x, int y): is used to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle with the
specifiedwidth and height.
55 Syeda Sumaiya Afreen
R20 CMR Technical Campus
3. public abstract void fillRect(int x, int y, int width, int height): is used to fill rectangle
with thedefault color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used to draw oval
with thespecified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to fill oval
with thedefault color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to draw line
between thepoints(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserver
observer): isused draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle): isused to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color to the
specifiedcolor.
11. public abstract void setFont(Font font): is used to set the graphics current font to the
specifiedfont.

Example
1. import java.applet.Applet;
2. import
java.awt.*; 3.
4. public class GraphicsDemo
extends Applet{ 5.
6. public void paint(Graphics g){
7. g.setColor(Color.red);
8. g.drawString("Welcom
e",50, 50); 9.
g.drawLine(20,30,20,300)

56 Syeda Sumaiya Afreen


R20 CMR Technical Campus
;
10. g.drawRect(70,100,30,30);
11. g.fillRect(170,100,30,30);
12. g.drawOval(70,200,30,30);
13.
14.
g.setColor(Color.pink
); 15.
g.fillOval(170,200,30,
30);
16. g.drawArc(90,150,30,30,30,270);
17. g.fillArc(270,150,30,30,0,180);
18. } }

mpapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:

Difference between a java application and ajava applet

Java Application:
57 Syeda Sumaiya Afreen
R20 CMR Technical Campus
Java Application is just like a Java program that runs on an underlying operating system with the
support of a virtual machine. It is also known as an application program. The graphical user
interface is not necessary to execute the java applications, it can be run with or without it.
Java Applet:
An applet is a Java program that can be embedded into a web page. It runs inside
the web browser and works at client side. An applet is embedded in an HTML page using the APPLET
or OBJECT tag and hosted on a web server. Applets are used to make the web site more dynamic and
entertaining.

Difference between Application and Applet:

Java Application Java Applet

1.Applications are just like a Applets are small Java programs that
Java programs that can be are designed to be included with the
executed HTML web

2.Java Application runs Java Applet


independently without using the require a Java-enabled web browser for
web browser. execution.

3.Application program requires a Applet does not require a main function


main function for its execution. for its execution.

4.Java application programs have Applets don’t have local disk and network
the full access to the local file access.
system and network.

58 Syeda Sumaiya Afreen


R20 CMR Technical Campus
5. Applications can access all Applets can only access the browser
kinds of resources available on specific services. They don’t have access
the system. to the local system.

6.Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.

7.An application program is needed An applet program is needed to perform


to perform some task directly for small tasks or the part of it.
the user.

Passing Parameters to Applet


We can get any information from the HTML file as a parameter. For this purpose, Applet class
provides amethod named getParameter(). Syntax:
public String getParameter(String parameterName)

Example
1. import java.applet.Applet;
2. import
java.awt.Graphics; 3.
4. public class UseParam
extends Applet{ 5.
6. public void paint(Graphics g){
7. String str=getParameter("msg");
8. g.drawString(str,5
0, 50); 9. } }

UseParam.htm
1. <html>
59 Syeda Sumaiya Afreen
R20 CMR Technical Campus
2. <body>
3. <applet code="UseParam.class" width="300" height="300">
4. <param name="msg" value="Welcome to applet">
5. </applet>
6. </body>
7. </htm
l> Output:

Painting in Applet
We can perform painting operation in applet by the mouseDragged() method of
MouseMotionListener.
Example
1. import java.awt.*;
2. import java.awt.event.*;
3. import java.applet.*;
4. public class MouseDrag extends Applet implements
MouseMotionListener{ 5.
6. public void init(){
7. addMouseMotionListener(this);
8. setBackground(Col
or.red); 9. }
10.
11. public void mouseDragged(MouseEvent me){
12. Graphics g=getGraphics();
13. g.setColor(Color.white);

60 Syeda Sumaiya Afreen


R20 CMR Technical Campus
14. g.fillOval(me.getX(),me.getY(),5,5);
15. }
16. public void mouseMoved(MouseEvent me){}
17. }

MouseDrag.htm
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:

JApplet class in Applet


As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of swing.
The JAppletclass extends the Applet class.
Example
1. import java.applet.*;
2. import javax.swing.*;
3. import java.awt.event.*;
4. public class EventJApplet extends JApplet implements ActionListener{
5. JButton b;
6. JTextField tf;
7. public void

61 Syeda Sumaiya Afreen


R20 CMR Technical Campus
init(){ 8.
9. tf=new JTextField();
10. tf.setBounds(30,40,150,20);
11.
12. b=new
JButton("Click"); 13.
b.setBounds(80,150,70,
40); 14.
15. add(b);add(tf);
16. b.addActionListene
r(this); 17.
18. setLayout(null);
19. }
20.
21. public void actionPerformed(ActionEvent e){
22. tf.setText("Welc
ome");
23. }}

EventJApplet.htm
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:

62 Syeda Sumaiya Afreen


R20 CMR Technical Campus

Displaying Image in Applet


Applet is mostly used in games and animation. For this purpose image is required to be displayed.
Thejava.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:


public abstract boolean drawImage(Image img, int x, int y, ImageObserver observer): is
useddraw the specified image.

How to get the object of Image:


The java.applet.Applet class provides getImage() method that returns the object of Image. Syntax:
public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:


1. public URL getDocumentBase(): is used to return the URL of the document in which
applet isembedded.
2. public URL getCodeBase(): is used to return the base URL.

Example
1. import java.awt.*;
2. import java.applet.*;
3. public class DisplayImage
extends Applet { 4.
5. Image
picture; 6.

63 Syeda Sumaiya Afreen


R20 CMR Technical Campus
7. public void init() {
8. picture =
getImage(getDocumentBase(),"cmr.jpg");
9. }
10. public void paint(Graphics g) {
11. g.drawImage(picture,
30,30, this); 12. }
}

myapplet.html
1. <html>
2. <body>
3. <applet code="DisplayImage.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:

JAVA SWING
Java Swing is a part of Java Foundation Classes (JFC) that is used to create window-based
applications. It is built on the top of AWT (Abstract Windowing Toolkit) API and entirely written
in java.

Unlike AWT, Java Swing provides platform-independent and lightweight components.

64 Syeda Sumaiya Afreen


R20 CMR Technical Campus
The javax.swing package provides classes for java swing API such as JButton, JTextField,
JTextArea, JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing

No. Java AWT Java Swing

1) AWT components are platform- Java swing components are platform-independent.


dependent.

2) AWT components are heavyweight. Swing components are lightweight.

3) AWT doesn't support Swing supports pluggable look and feel.


pluggable look and feel.

4) AWT provides less components Swing provides more powerful components such as
than Swing. tables, lists, scrollpanes, colorchooser, tabbedpane etc.

5) AWT doesn't follows Swing follows MVC.


MVC(Model View Controller)
where model represents data, view
represents presentation and
controller acts as an interface
between model and view.

The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktopapplications.

Hierarchy of Java Swing classes

65 Syeda Sumaiya Afreen


R20 CMR Technical Campus

Commonly used Methods of Component class


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 sets size of the component.


width,int height)

public void sets the layout manager for the component.


setLayout(LayoutManager m)

public void setVisible(boolean sets the visibility of the component. It is


b) by default false.

Java Swing Examples


There are two ways to create a frame:
o By creating the object of Frame class (association)
o By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on the
JFrame objectinside the main() method.
1. import javax.swing.*;
66 Syeda Sumaiya Afreen
R20 CMR Technical Campus
2. public class FirstSwingExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame();//creating
instance of JFrame
5. b.setBounds(130,100,100, 40);//x axis,
y axis, width, height
6. f.add(b);//adding button in JFrame.
7.f.setSize(400,500);//400 width and 500 height
8.f.setLayout(null);//using no layout managers
9. f.setVisible(true);//making the
frame visible
10. } }
Output:

Example of Swing by Association inside constructor


We can also write all the codes of creating JFrame, JButton and method call inside the java
constructor.
1. import javax.swing.*;
2. public class Simple {
3. JFrame f;
4. Simple(){
5. f=new JFrame();//creating
instance of JFrame
6. JButton b=new
JButton("click");//creating instance
67 Syeda Sumaiya Afreen
R20 CMR Technical Campus
of JButton
7. b.setBounds(130,100,100, 40);
8. f.add(b);//adding button in JFrame
9. f.setSize(400,500);//400 width and 500 height
10.f.setLayout(null);//using no layout managers
11.f.setVisible(true);//making the frame visible
12.}
13 public static void
main(String[] args) {
14 new Simple(); 19. } }
Output:

Simple example of Swing by inheritance


We can also inherit the JFrame class, so there is no need to create the instance of JFrame class
explicitly.
1. import javax.swing.*;
2. public class Simple2 extends JFrame{//inheriting JFrame
3. JFrame f;
4. Simple2(){
5. JButton b=new
JButton("click");//create button
6. b.setBounds(130,100,100, 40);
7. add(b);//adding button on frame
8. setSize(400,500);
9. setLayout(null);
68 Syeda Sumaiya Afreen
R20 CMR Technical Campus
10. setVisible(true);
11. }
12. public static void main(String[] args) {
13. new
Simple2();
14. }}
Output:

JButton
The JButton class is used to create a labeled button that has platform independent implementation.
Theapplication result in some action when the button is pushed. It inherits AbstractButton class.

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and


icon.

JButton(String It creates a button with the specified


s) text.

JButton(Icon i) It creates a button with the specified


icon object.

Commonly used Methods of AbstractButton class:

69 Syeda Sumaiya Afreen


R20 CMR Technical Campus
Methods Description

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


button

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


button.

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


button.

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


the button.

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


button.

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


button.

void It is used to add the action listener to


addActionListener(ActionList this object.
ener a)

Example
1. import javax.swing.*;
2. public class ButtonExample {
3. public static void main(String[] args) {
4. JFrame f=new JFrame("Button Example");
5. JButton b=new
JButton("Click Here"); 6.
b.setBounds(50,100,95,30);
7. f.add(b);
8. f.setSize(400,400);
9. f.setLayout(null);
10. f.setVisible(t
70 Syeda Sumaiya Afreen
R20 CMR Technical Campus
rue); 11. } }
Output:

JButton Example with ActionListener


1. import java.awt.event.*;
2. import javax.swing.*;
3. public class ButtonExample {
4. public static void main(String[] args) {
5. JFrame f=new JFrame("Button Example");
6. final JTextField tf=new
JTextField();
7. tf.setBounds(50,50,
150,20);
8. JButton b=new
JButton("Click Here");
9. b.setBounds(50,100,95,30);
10. b.addActionListener(new ActionListener(){
11. public void actionPerformed(ActionEvent e){
12. tf.setText("Welcome to CMR TC.");
13. }
14. };
15.f.add(b);f.add(tf);
16.f.setSize(400,400);
17. f.setLayout(null);
18. f.setVisible(true);
19. }}
Output:
71 Syeda Sumaiya Afreen
R20 CMR Technical Campus

Example of displaying image on the button:


1. import javax.swing.*;
2. public class ButtonExample{
3. ButtonExample(){
4. JFrame f=new JFrame("Button Example");
5. JButton b=new JButton(new
ImageIcon("button.png")); 6.
b.setBounds(100,100,100, 40);
7. f.add(b);
8. f.setSize(300,400);
9. f.setLayout(null);
10. f.setVisible(true);
11. f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12. }
13. public static void main(String[] args) {
14. new
ButtonExample(); 15.
}}
Output:

JLabel
72 Syeda Sumaiya Afreen
R20 CMR Technical Campus
The object of JLabel class is a component for placing text in a container. It is used to display a
single line of read only text. The text can be changed by an application but a user cannot edit it
directly. It inherits JComponent class.

Commonly used Constructors:

Constructor Description

JLabel() Creates a JLabel instance with no image and with an empty


string for the title.

JLabel(String s) Creates a JLabel instance with the specified text.

JLabel(Icon i) Creates a JLabel instance with the specified image.

JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.

Commonly used Methods:

Methods Description

String getText() It returns the text string that a label displays.

void setText(String text) It defines the single line of text this component
will display.

void setHorizontalAlignment(int It sets the alignment of the label's contents


alignment) along the X axis.

Icon getIcon() It returns the graphic image that the label


displays.

int getHorizontalAlignment() It returns the alignment of the label's contents


along the X axis.

JLabel Example
73 Syeda Sumaiya Afreen
R20 CMR Technical Campus
1. import javax.swing.*;
2. class
LabelExample 3.
{
4. public static void
main(String args[])
5. {
6. JFrame f= new JFrame("Label Example");
7. JLabel l1,l2;
8. l1=new JLabel("First Label.");
9. l1.setBounds(50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. l2.setBounds(50,100, 100,30);
12. f.add(l1);
f.add(l2);
13.f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. } }
Output:

JLabel Example with ActionListener


1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class LabelExample extends Frame implements ActionListener{
5. JTextField tf; JLabel l; JButton b;
74 Syeda Sumaiya Afreen
R20 CMR Technical Campus
6. LabelExample(){
7. tf=new JTextField();
8. tf.setBounds(50,50, 150,20);
9. l=new JLabel();
10. l.setBounds(50,100, 250,20);
11. b=new
JButton("Find IP"); 12.
b.setBounds(50,150,
95,30);
13. b.addActionListener(this);
14. add(b);add(tf);a
dd(l);
15. setSize(400,400);
16. setLayout(null);
17. setVisible(true);
18. }
19. public void actionPerformed(ActionEvent e) {
20. try{
21. String host=tf.getText();
22. String ip=java.net.InetAddress.getByName(host).getHostAddress();
23. l.setText("IP of "+host+" is: "+ip);
24. }catch(Exception ex){System.out.println(ex);}
25. }
26. public static void main(String[] args) {
27. new
LabelExample();
28. }}
Output:

75 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inheritsJTextComponent class.

Commonly used Constructors:

Constructor Description

JTextField() Creates a new TextField

JTextField(String text) Creates a new TextField initialized with the


specified text.

JTextField(String text, int Creates a new TextField initialized with the


columns) specified text and columns.

JTextField(int columns) Creates a new empty TextField with the specified


number of columns.

Commonly used Methods:

Methods Description

void It is used to add the specified action listener to receive action


addActionListe events from this textfield.
ner
(ActionListener
l)

76 Syeda Sumaiya Afreen


R20 CMR Technical Campus

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

void setFont(Font f) It is used to set the current font.

void It is used to remove the specified action listener so that it no longer


removeActionListener receives action events from this textfield.
(ActionListener l)

JTextField Example
1. import javax.swing.*;
2. class
TextFieldExample
3. {
4. public static void
main(String args[]) 5. {
6. JFrame f= new JFrame("TextField Example");
7. JTextField t1,t2;
8. t1=new JTextField("Welcome
to CMR TC."); 9.
t1.setBounds(50,100, 200,30);
10. t2=new
JTextField("AWT Tutorial");
11. t2.setBounds(50,150,
200,30);
12. f.add(t1);
f.add(t2); 13.
f.setSize(400,
400);
14. f.setLayout(null);
15. f.setVisible(t
rue);
77 Syeda Sumaiya Afreen
R20 CMR Technical Campus
16. } }
Output:

JTextField Example with ActionListener


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class TextFieldExample implements ActionListener{
4. JTextField tf1,tf2,tf3;
5. JButton b1,b2;
6. TextFieldExample(){
7. JFrame f= new JFrame();
8. tf1=new JTextField();
9. tf1.setBounds(50,50,150,20);
10. tf2=new JTextField();
11. tf2.setBounds(50,100,150,20);
12. tf3=new JTextField();
13. tf3.setBounds(50,150,150,20);
14. tf3.setEditable(false);
15. b1=new JButton("+");
16. b1.setBounds(50,200,50,50);
17. b2=new JButton("-");
18. b2.setBounds(120,200,50,50);
19. b1.addActionListener(this);
20. b2.addActionListener(this);
21. f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1
);f.add(b2); 22. f.setSize(300,300);
78 Syeda Sumaiya Afreen
R20 CMR Technical Campus
23. f.setLayout(null);
24. f.setVisible(true);
25. }
26. public void actionPerformed(ActionEvent e) {
27. String s1=tf1.getText();
28. String s2=tf2.getText();
29. int a=Integer.parseInt(s1);
30. int b=Integer.parseInt(s2);
31. int c=0;
32. if(e.getSource()==b1){
33. c=a+b;
34. }else if(e.getSource()==b2){
35. c=a-b;
36. }
37. String result=String.valueOf(c);
38. tf3.setText(result);
39. }
40. public static void main(String[] args) {
41. new
TextFieldExample();
42. } }
Output:

79 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes

Modifier Class Description


and Type

protected JToggleButton.AccessibleJT This class implements accessibility support for the


class oggleButton JToggleButton class.

static class JToggleButton.ToggleButto The ToggleButton model


nModel
Constructors

Constructor Description

JToggleButton() It creates an initially unselected toggle button without setting


the text or image.

JToggleButton(Action a) It creates a toggle button where properties are taken from the
Action supplied.

JToggleButton(Icon icon) It creates an initially unselected toggle button with the


specified image but no text.

JToggleButton(Icon icon, It creates a toggle button with the specified image and
boolean selected) selection state, but no text.

JToggleButton(String text) It creates an unselected toggle button with the specified text.

JToggleButton(String text, It creates a toggle button with the specified text and selection
boolean selected) state.

JToggleButton(String text, Icon It creates a toggle button that has the specified text and image,
icon) and that is initially unselected.

80 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JToggleButton(String text, Icon It creates a toggle button with the specified text, image, and
icon, boolean selected) selection state.
Methods

Modifier and Method Description


Type

AccessibleCon getAccessibleCo It gets the AccessibleContext associated with this


text ntext() JToggleButton.

String getUIClassID() It returns a string that specifies the name of the l&f class that
renders this component.

protected paramString() It returns a string representation of this JToggleButton.


String

void updateUI() It resets the UI property to a value from the current look and
feel.

JToggleButton Example
1. import java.awt.FlowLayout;
2. import java.awt.event.ItemEvent;
3. import java.awt.event.ItemListener;
4. import javax.swing.JFrame;
5. import
javax.swing.JToggleButton;
6.
7. public class JToggleButtonExample extends JFrame implements ItemListener {
8. public static void main(String[] args) {
9. new JToggleButtonExample();
10. }
11. private JToggleButton button;
12. JToggleButtonExample() {

81 Syeda Sumaiya Afreen


R20 CMR Technical Campus
13. setTitle("JToggleButton with ItemListener Example");
14. setLayout(new FlowLayout());
15. setJToggleButton();
16. setAction();
17. setSize(200, 200);
18. setVisible(true);
19. setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
20. }
21. private void setJToggleButton() {
22. button = new JToggleButton("ON");
23. add(button);
24. }
25. private void setAction() {
26. button.addItemListener(this);
27. }
28. public void itemStateChanged(ItemEvent eve) {
29. if (button.isSelected())
30. button.setText("OFF");
31. else
32. button.setText("ON
"); 33. } }
Output:

JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off

82 Syeda Sumaiya Afreen


R20 CMR Technical Campus
(false). Clicking on a CheckBox changes its state from "on" to "off" or from "off" to
"on ".It inherits JToggleButton class.

JCheckBox class declaration


public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JJCheckBox() Creates an initially unselected check box


button with no text, no icon.

JChechBox(String s) Creates an initially unselected check box with


text.

JCheckBox(String text, Creates a check box with text and specifies


boolean selected) whether or not it is initially selected.

JCheckBox(Action a) Creates a check box where properties are taken


from the Action supplied.

Commonly used Methods:

Methods Description

AccessibleContext It is used to get the AccessibleContext


getAccessibleContext() associated with this JCheckBox.

protected String It returns a string representation of this


paramString() JCheckBox.

JCheckBox Example
1. import javax.swing.*;
2. public class
83 Syeda Sumaiya Afreen
R20 CMR Technical Campus
CheckBoxExample 3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new
JCheckBox("C++"); 7.
checkBox1.setBounds(100,100,
50,50);
8. JCheckBox checkBox2 = new
JCheckBox("Java", true); 9.
checkBox2.setBounds(100,150, 50,50);
10. f.add(checkBox1);
11. f.add(checkBox2);
12. f.setSize(400,400);
13. f.setLayout(null);
14. f.setVisible(true);
15. }
16. public static void main(String args[])
17. {
18. new
CheckBoxExample();
19. }}
Output:

JCheckBox Example with ItemListener


1. import javax.swing.*;

84 Syeda Sumaiya Afreen


R20 CMR Technical Campus
2. import java.awt.event.*;
3. public class
CheckBoxExample 4. {
5. CheckBoxExample(){
6. JFrame f= new JFrame("CheckBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JCheckBox checkbox1 = new JCheckBox("C++");
11. checkbox1.setBounds(150,100, 50,50);
12. JCheckBox checkbox2 = new JCheckBox("Java");
13. checkbox2.setBounds(150,150, 50,50);
14. f.add(checkbox1); f.add(checkbox2); f.add(label);
15. checkbox1.addItemListener(new ItemListener() {
16. public void itemStateChanged(ItemEvent e) {
17. label.setText("C++ Checkbox: "
18. + (e.getStateChange()==1?"checked":"unchecked"));
19. }
20. });
21. checkbox2.addItemListener(new ItemListener() {
22. public void itemStateChanged(ItemEvent e) {
23. label.setText("Java Checkbox: "
24. + (e.getStateChange()==1?"checked":"unchecked"));
25. }
26. });
27. f.setSize(400,400);
28. f.setLayout(null);
29. f.setVisible(true);
30. }
31. public static void main(String args[])

85 Syeda Sumaiya Afreen


R20 CMR Technical Campus
32. {
33. new
CheckBoxExample();
34. } }
Output:

JCheckBox Example: Food Order


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class CheckBoxExample extends JFrame implements ActionListener{
4. JLabel l;
5. JCheckBox cb1,cb2,cb3;
6. JButton b;
7. CheckBoxExample(){
8. l=new JLabel("Food
Ordering System"); 9.
l.setBounds(50,50,300,20);
10. cb1=new
JCheckBox("Pizza @ 100");
11.cb1.setBounds(100,100,150,20);
12. cb2=new
JCheckBox("Burger @ 30");
13.cb2.setBounds(100,150,150,20);

86 Syeda Sumaiya Afreen


R20 CMR Technical Campus
14. cb3=new
JCheckBox("Tea @ 10");
15.cb3.setBounds(100,200,150,20);
16. b=new
JButton("Order");
17.b.setBounds(100,250,80,30;
18. b.addActionListener(this);
19. add(l);add(cb1);add(cb2);add(cb
3);add(b);
20. setSize(400,400);
21. setLayout(null);
22. setVisible(true);
23. setDefaultCloseOperation(EXIT_ON_CLOSE);
24. }
25. public void actionPerformed(ActionEvent e){
26. float amount=0;
27. String msg="";
28. if(cb1.isSelected()){
29. amount+=100;
30. msg="Pizza: 100\n";
31. }
32. if(cb2.isSelected()){
33. amount+=30;
34. msg+="Burger: 30\n";
35. }
36. if(cb3.isSelected()){
37. amount+=10;
38. msg+="Tea: 10\n";
39. }
40. msg+=" ---------- \n";

87 Syeda Sumaiya Afreen


R20 CMR Technical Campus
41. JOptionPane.showMessageDialog(this,msg+"Total: "+amount);
42. }
43. public static void main(String[] args) {
44. new
CheckBoxExample();
45. } }
Output:

JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one option from
multiple options. It is widely used in exam systems or quiz. It should be added in ButtonGroup
to select one radio button only.

JRadioButton class declaration


public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

JRadioButton() Creates an unselected radio button with no text.

JRadioButton(String s) Creates an unselected radio button with specified


text.

JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.

88 Syeda Sumaiya Afreen


R20 CMR Technical Campus
Commonly used Methods:

Methods Description

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

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

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

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


button.

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

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


button.

void It is used to add the action listener to this


addActionListener(ActionList object.
ener a)

JRadioButton Example
1. import javax.swing.*;
2. public class RadioButtonExample {
3. JFrame f;
4. RadioButtonExample(){
5. f=new JFrame();
6. JRadioButton r1=new JRadioButton("A) Male");
7. JRadioButton r2=new
JRadioButton("B) Female");
8. r1.setBounds(75,50,100,30);
9. r2.setBounds(75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. bg.add(r1);bg.add(r2);
89 Syeda Sumaiya Afreen
R20 CMR Technical Campus
12. f.add(r1);f.ad
d(r2);
13. f.setSize(300,300);
14. f.setLayout(null);
15. f.setVisible(true);
16. }
17. public static void main(String[] args) {
18. new
RadioButtonExample();
19. } }
Output:

JRadioButton Example with ActionListener


1. import javax.swing.*;
2. import java.awt.event.*;
3. class RadioButtonExample extends JFrame implements ActionListener{
4. JRadioButton rb1,rb2;
5. JButton b;
6. RadioButtonExample(){
7. rb1=new
JRadioButton("Male"); 8.
rb1.setBounds(100,50,10
0,30);
9. rb2=new
JRadioButton("Female");
10.
90 Syeda Sumaiya Afreen
R20 CMR Technical Campus
rb2.setBounds(100,100,100,
30);
11. ButtonGroup bg=new ButtonGroup();
12. bg.add(rb1);bg.add(rb2);
13. b=new JButton("click");
14. b.setBounds(100,150,80,30);
15. b.addActionListener(this);
16. add(rb1);add(rb2);a
dd(b); 17.
setSize(300,300);
18. setLayout(null);
19. setVisible(true);
20. }
21. public void actionPerformed(ActionEvent e){
22. if(rb1.isSelected()){
23. JOptionPane.showMessageDialog(this,"You are Male.");
24. }
25. if(rb2.isSelected()){
26. JOptionPane.showMessageDialog(this,"You are Female.");

27. }
28. }
29. public static void main(String args[]){
30. new
RadioButtonExample()
; 31. }}
Output:

91 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JTabbedPane
The JTabbedPane class is used to switch between a group of components by clicking on a tab
with a giventitle or icon. It inherits JComponent class.

JTabbedPane class declaration


public class JTabbedPane extends JComponent implements Serializable, Accessible,
SwingConstants

Commonly used Constructors:

Constructor Description

JTabbedPane() Creates an empty TabbedPane with a default tab placement of


JTabbedPane.Top.

JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified tab placement.

JTabbedPane(int tabPlacement, int Creates an empty TabbedPane with a specified tab placement
tabLayoutPolicy) and tab layout policy.

JTabbedPane Example
1. import javax.swing.*;
2. public class TabbedPaneExample {
3. JFrame f;
4. TabbedPaneExample(){
5. f=new JFrame();
6. JTextArea ta=new JTextArea(200,200);
92 Syeda Sumaiya Afreen
R20 CMR Technical Campus
7. JPanel p1=new JPanel();
8. p1.add(ta);
9. JPanel p2=new JPanel();
10. JPanel p3=new JPanel();
11. JTabbedPane tp=new
JTabbedPane(); 12.
tp.setBounds(50,50,200,20
0);
13. tp.add("main",p1);
14. tp.add("visit",p2);
15. tp.add("help",p3);
16. f.add(tp);
17. f.setSize(400,400);
18. f.setLayout(null);
19. f.setVisible(true);
20. }
21. public static void main(String[] args) {
22. new
TabbedPaneExample();
23. }}
Output:

93 Syeda Sumaiya Afreen


R20 CMR Technical Campus
JScrollPane
A JscrollPane is used to make scrollable view of a component. When screen size is limited, we
use a scrollpane to display a large component or a component whose size can change
dynamically.

Constructors

Purpose
Constructor

JScrollPane() It creates a scroll pane. The Component


parameter, when present, sets the scroll
JScrollPane(Component
pane's client. The two int parameters,
)
when present, set the vertical and
JScrollPane(int, int) horizontal scrollbar policies

JScrollPane(Component, (respectively).

int, int)

Useful Methods

Modifie Method Description


r

void setColumnHeaderView(Co It sets the column header for the scroll pane.
mponent)

void setRowHeaderView(Comp It sets the row header for the scroll pane.
onent)

void setCorner(String, It sets or gets the specified corner. The int parameter
Component) specifies which corner and must be one of the following
constants defined in ScrollPaneConstants:
Compone getCorner(String)
UPPER_LEFT_CORNER, UPPER_RIGHT_CORNER,
nt

94 Syeda Sumaiya Afreen


R20 CMR Technical Campus
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER, LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.

void setViewportView(Compon Set the scroll pane's client.


ent)

JScrollPane Example
1. import java.awt.FlowLayout;
2. import
javax.swing.*; 3.
4. public class JScrollPaneExample {
5. private static final long
serialVersionUID = 1L; 6.
7. private static void
createAndShowGUI() { 8.
9. // Create and set up the window.
10. final JFrame frame = new JFrame("Scroll
Pane Example"); 11.
12. // Display the window.
13. frame.setSize(500, 500);
14. frame.setVisible(true);
15. frame.setDefaultCloseOperation(JFrame.EX
IT_ON_CLOSE);
16. // set flow layout for the frame
17. frame.getContentPane().setLayout(new FlowLayout());
18. JTextArea textArea = new JTextArea(20, 20);
19. JScrollPane scrollableTextArea = new
JScrollPane(textArea);
95 Syeda Sumaiya Afreen
R20 CMR Technical Campus
20. scrollableTextArea.setHorizontalScrollBarPolicy(JScrollPane.HO
RIZONTAL_SCROLLBAR_ALWAYS);
21. scrollableTextArea.setVerticalScrollBarPolicy(JScrollPane.VERTIC
AL_SCROLLBAR_ALWAYS);
22. frame.getContentPane().add(scrollableTextArea);
23. }
24. public static void main(String[] args) {
25. javax.swing.SwingUtilities.invokeLater(new Runnable() ){
26. public void run() {
27. createAndShowGUI();
28. }
29. });
30. }}
Output:

JList
The object of JList class represents a list of text items. The list of text items can be set up so
that the usercan choose either one item or multiple items. It inherits JComponent class.

JList class declaration


public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:

Constructor Description

96 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JList() Creates a JList with an empty, read-only, model.

JList(ary[] listData) Creates a JList that displays the elements in the


specified array.

JList(ListModel<ary> Creates a JList that displays elements from the


dataModel) specified, non-null, model.
Commonly used Methods:

Methods Description

Void It is used to add a listener to the list, to be notified


addListSelectionListener(ListSelectionListe each time a change to the selection
ner listener) occurs.

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

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

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


of objects.

JList Example
1. import javax.swing.*;
2. public class
ListExample 3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. l1.addElement("Item1");
8. l1.addElement("Item2");
9. l1.addElement("Item3");
10. l1.addElement("Item4");

97 Syeda Sumaiya Afreen


R20 CMR Technical Campus
11. JList<String> list = new
JList<>(l1);
12. list.setBounds(100,100, 75,75);
13. f.add(list);
14. f.setSize(400,400);
15. f.setLayout(null);
16. f.setVisible(true);
17. }
18. public static void main(String args[])
19. {
20. new
ListExample();
21. }}
Output:

JList Example with ActionListener


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class
ListExample 4. {
5. ListExample(){
6. JFrame f= new JFrame();
7. final JLabel label = new JLabel();
8. label.setSize(500,100);
9. JButton b=new
JButton("Show"); 10.
98 Syeda Sumaiya Afreen
R20 CMR Technical Campus
b.setBounds(200,150,80
,30);
11. final DefaultListModel<String> l1 = new DefaultListModel<>();
12. l1.addElement("C");
13. l1.addElement("C++");
14. l1.addElement("Java");
15. l1.addElement("PHP");
16. final JList<String> list1 = new
JList<>(l1); 17.
list1.setBounds(100,100,
75,75);
18. DefaultListModel<String> l2 = new DefaultListModel<>();
19. l2.addElement("Turbo C++");
20. l2.addElement("Struts");
21. l2.addElement("Spring");
22. l2.addElement("YII");
23. final JList<String> list2 = new
JList<>(l2); 24.
list2.setBounds(100,200,
75,75);
25. f.add(list1); f.add(list2); f.add(b);
f.add(label); 26. f.setSize(450,450);
27. f.setLayout(null);
28. f.setVisible(true);
29. b.addActionListener(new ActionListener() {
30. public void actionPerformed(ActionEvent e) {
31. String data = "";
32. if (list1.getSelectedIndex() != -1) {
33. data = "Programming language Selected: " + list1.getSelectedValue();
34. label.setText(data);

99 Syeda Sumaiya Afreen


R20 CMR Technical Campus
35. }
36. if(list2.getSelectedIndex() != -1){
37. data += ", FrameWork Selected: ";
38. for(Object frame :list2.getSelectedValues()){
39. data += frame + " ";
40. }
41. }
42. label.setText(data);
43. }
44. });
45. }
46. public static void main(String args[])
47. {
48. new
ListExample(); 49.
}}
Output:

JComboBox
The object of Choice class is used to show popup menu of choices. Choice selected by user is
shown on thetop of a menu. It inherits JComponent class.

JComboBox class declaration


public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,
ActionListener, Accessible

100 Syeda Sumaiya Afreen


R20 CMR Technical Campus
Commonly used Constructors:

Constructor Description

JComboBox() Creates a JComboBox with a default data model.

JComboBox(Object[] Creates a JComboBox that contains the elements in the


items) specified array.

JComboBox(Vector<?> Creates a JComboBox that contains the elements in the


items) specified Vector.

Commonly used Methods:

Methods Description

void addItem(Object anObject) It is used to add an item to the item list.

void removeItem(Object It is used to delete an item to the item list.


anObject)

void removeAllItems() It is used to remove all the items from the


list.

void setEditable(boolean b) It is used to determine whether the


JComboBox is editable.

void It is used to add the ActionListener.


addActionListener(ActionListen
er a)

void It is used to add the ItemListener.


addItemListener(ItemListener i)

JComboBox Example
1. import javax.swing.*;
2. public class ComboBoxExample {
101 Syeda Sumaiya Afreen
R20 CMR Technical Campus
3. JFrame f;
4. ComboBoxExample(){
5. f=new JFrame("ComboBox Example");
6. String country[]={"India","Aus","U.S.A","England","Newzealand"};
7. JComboBox cb=new
JComboBox(country); 8.
cb.setBounds(50, 50,90,20);
9. f.add(cb);
10. f.setLayout(n
ull); 11.
f.setSize(400,
500);
12. f.setVisible(true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. }
17. }

Output:

102 Syeda Sumaiya Afreen


R20 CMR Technical Campus
JComboBox Example with ActionListener
1. import javax.swing.*;
2. import java.awt.event.*;
3. public class ComboBoxExample {
4. JFrame f;
5. ComboBoxExample(){
6. f=new JFrame("ComboBox Example");
7. final JLabel label = new JLabel();
8. label.setHorizontalAlignment(JLabel.CENTER);
9. label.setSize(400,100);
10. JButton b=new
JButton("Show"); 11.
b.setBounds(200,100,75
,20);
12. String languages[]={"C","C++","C#","Java","PHP"};
13. final JComboBox cb=new
JComboBox(languages); 14.
cb.setBounds(50, 100,90,20);
15. f.add(cb); f.add(label); f.add(b);
16. f.setLayout(n
ull); 17.
f.setSize(350,
350);
18. f.setVisible(true);
19. b.addActionListener(new ActionListener() {
20. public void actionPerformed(ActionEvent e) {
21. String data = "Programming language Selected: "
22. + cb.getItemAt(cb.getSelectedIndex());
23. label.setText(data);
24. }

103 Syeda Sumaiya Afreen


R20 CMR Technical Campus
25.
});
26. }
27. public static void main(String[] args) {
28. new
ComboBoxExample();
29. } }
Output:

JMenuBar, JMenu and JMenuItem


The JMenuBar class is used to display menubar on the window or frame. It may have several menus.

The object of JMenu class is a pull down menu component which is displayed from the menu
bar. It inheritsthe JMenuItem class.

The object of JMenuItem class adds a simple labeled menu item. The items used in a menu must
belong tothe JMenuItem or any of its subclass.

JMenuBar class declaration


public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration


public class JMenuItem extends AbstractButton implements Accessible, MenuElement
104 Syeda Sumaiya Afreen
R20 CMR Technical Campus

JMenuItem and JMenu Example


1. import javax.swing.*;
2. class
MenuExample 3.
{
4. JMenu menu, submenu;
5. JMenuItem i1, i2, i3, i4, i5;
6. MenuExample(){
7. JFrame f= new JFrame("Menu and MenuItem Example");
8. JMenuBar mb=new JMenuBar();
9. menu=new JMenu("Menu");
10. submenu=new JMenu("Sub Menu");
11. i1=new JMenuItem("Item 1");
12. i2=new JMenuItem("Item 2");
13. i3=new JMenuItem("Item 3");
14. i4=new JMenuItem("Item 4");
15. i5=new JMenuItem("Item 5");
16. menu.add(i1); menu.add(i2); menu.add(i3);
17. submenu.add(i4); submenu.add(i5);
18. menu.add(submenu);
19. mb.add(menu);
20. f.setJMenuBar(mb);
21. f.setSize(400,400);
22. f.setLayout(null);
23. f.setVisible(true);
24. }
25. public static void main(String args[])
26. {
27. new

105 Syeda Sumaiya Afreen


R20 CMR Technical Campus
MenuExample();
28. }}
Output:

Example of creating Edit menu for Notepad:


1. import javax.swing.*;
2. import java.awt.event.*;
3. public class MenuExample implements ActionListener{
4. JFrame f;
5. JMenuBar mb;
6. JMenu file,edit,help;
7. JMenuItem cut,copy,paste,selectAll;
8. JTextArea ta;
9. MenuExample(){
10. f=new JFrame();
11. cut=new JMenuItem("cut");
12. copy=new JMenuItem("copy");
13. paste=new JMenuItem("paste");
14. selectAll=new JMenuItem("selectAll");
15. cut.addActionListener(this);
16. copy.addActionListener(this);
17. paste.addActionListener(this);
18. selectAll.addActionListener(this);
19. mb=new JMenuBar();
20. file=new JMenu("File");

106 Syeda Sumaiya Afreen


R20 CMR Technical Campus
21. edit=new JMenu("Edit");
22. help=new JMenu("Help");
23. edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
24. mb.add(file);mb.add(edit);mb.add(help);
25. ta=new JTextArea();
26. ta.setBounds(5,5,360,320);
27. f.add(mb);f.add(ta);
28. f.setJMenuBar(mb);
29. f.setLayout(n
ull); 30.
f.setSize(400,400
);
31. f.setVisible(true);
32. }
33. public void actionPerformed(ActionEvent e) {
34. if(e.getSource()==cut)
35. ta.cut();
36. if(e.getSource()==paste)
37. ta.paste();
38. if(e.getSource()==copy)
39. ta.copy();
40. if(e.getSource()==selectAll)
41. ta.selectAll();
42. }
43. public static void main(String[] args) {
44. new
MenuExample(); 45.
}}
Output:

107 Syeda Sumaiya Afreen


R20 CMR Technical Campus

JDialog
The JDialog control represents a top level window with a border and a title used to take some
form of inputfrom the user. It inherits the Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

JDialog class declaration


public class JDialog extends Dialog implements WindowConstants, Accessible, RootPaneContainer

Commonly used Constructors:

Constructor Description

JDialog() It is used to create a modeless dialog without a title and without a


specified Frame owner.

JDialog(Frame owner) It is used to create a modeless dialog with specified Frame as its
owner and an empty title.

JDialog(Frame owner, String It is used to create a dialog with the specified title, owner Frame and
title, boolean modal) modality.

JDialog Example
1. import javax.swing.*;
2. import java.awt.*;
3. import java.awt.event.*;
4. public class DialogExample {
108 Syeda Sumaiya Afreen
R20 CMR Technical Campus
5. private static JDialog d;
6. DialogExample() {
7. JFrame f= new JFrame();
8. d = new JDialog(f , "Dialog Example", true);
9. d.setLayout( new FlowLayout() );
10. JButton b = new JButton ("OK");
11. b.addActionListener ( new ActionListener()
12. {
13. public void actionPerformed( ActionEvent e )
14. {
15. DialogExample.d.setVisible(false);
16. }
17. });
18. d.add( new JLabel ("Click button to continue."));
19. d.add(b);
20. d.setSize(300,300);
21. d.setVisible(true);
22. }
23. public static void main(String args[])
24. {
25. new DialogExample();
26. }
27.
} Output:

109 Syeda Sumaiya Afreen


R20 CMR Technical Campus

110 Syeda Sumaiya Afreen

You might also like