JAVA UNIT - V
JAVA UNIT - V
UNIT – V
The java.awt package provides classes for AWT Api such as TextField, Label, TextArea,
RadioButton, CheckBox, Choice, List etc.
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
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:
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,
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.
Method Description
public void setSize(int sets the size (width and height) of the
width,int height) component.
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:
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 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 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
Note: CheckboxGroup enables you to create radio buttons in AWT. There is no special control for
creating radio buttons in AWT.
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:
The object of Menu class is a pull down menu component which is displayed on the menu bar.
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");
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:
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[])
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
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.
Output:
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.
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.
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.
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
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
protected layoutInfo It is used to hold the layout information for the gridbag.
GridBagLayoutInfo
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.
Useful Methods
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{
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.
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.
ActionEvent ActionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener
We can put the event handling code into one of the following places:
1. Within class
2. Other class
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);
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:
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.
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);
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 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.
1. class Java_Outer_class{
2. //code
3. class Java_Inner_class{
4. //code
5. }
6. }
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
2) Nested classes are used to develop more readable and maintainable code because itlogically
There are two types of nested classes non-static and static nested classes.The non-static nested classes
are also known as inner classes.
Type Description
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:
2. Interface
4. class TestAnonymousInner{
5. public static void main(String args[]){
8. };
9. p.eat();
Output:
nice fruits
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.
1. import java.io.PrintStream;
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[]){
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
Applet class extends Panel. Panel class extends Container which is the subclass of Component.
• 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
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: 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>
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)
mpapplet.html
1. <html>
2. <body>
3. <applet code="GraphicsDemo.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:
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.
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
4.Java application programs have Applets don’t have local disk and network
the full access to the local file access.
system and network.
6.Applications can executes the Applets cannot execute programs from the
programs from the local system. local machine.
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);
MouseDrag.htm
1. <html>
2. <body>
3. <applet code="MouseDrag.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:
EventJApplet.htm
1. <html>
2. <body>
3. <applet code="EventJApplet.class" width="300" height="300">
4. </applet>
5. </body>
6. </htm
l> Output:
Example
1. import java.awt.*;
2. import java.applet.*;
3. public class DisplayImage
extends Applet { 4.
5. Image
picture; 6.
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.
4) AWT provides less components Swing provides more powerful components such as
than Swing. tables, lists, scrollpanes, colorchooser, tabbedpane etc.
The Java Foundation Classes (JFC) are a set of GUI components which simplify the development of
desktopapplications.
Method Description
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.
Constructor Description
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:
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.
Constructor Description
JLabel(String s, Icon i, int Creates a JLabel instance with the specified text, image, and
horizontalAlignment) horizontal alignment.
Methods Description
void setText(String text) It defines the single line of text this component
will display.
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:
JTextField
The object of a JTextField class is a text component that allows the editing of a single line text. It
inheritsJTextComponent class.
Constructor Description
Methods Description
Action getAction() It returns the currently set Action for this ActionEvent source, or
null if no Action is set.
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:
JToggleButton
JToggleButton is used to create toggle button, it is two-states button to switch on or off.
Nested Classes
Constructor Description
JToggleButton(Action a) It creates a toggle button where properties are taken from the
Action supplied.
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.
JToggleButton(String text, Icon It creates a toggle button with the specified text, image, and
icon, boolean selected) selection state.
Methods
String getUIClassID() It returns a string that specifies the name of the l&f class that
renders this component.
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() {
JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off
Constructor Description
Methods Description
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:
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.
Constructor Description
JRadioButton(String s, boolean Creates a radio button with the specified text and
selected) selected status.
Methods Description
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:
27. }
28. }
29. public static void main(String args[]){
30. new
RadioButtonExample()
; 31. }}
Output:
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.
Constructor Description
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:
Constructors
Purpose
Constructor
JScrollPane(Component, (respectively).
int, int)
Useful Methods
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
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.
Constructor Description
Methods Description
ListModel getModel() It is used to return the data model that holds a list of
items displayed by the JList component.
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");
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.
Constructor Description
Methods Description
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:
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.
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.
Constructor Description
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: