0% found this document useful (0 votes)
93 views32 pages

Unit 5 Swing

The document discusses Java GUI event handling and Swing components. It provides an introduction to event handling concepts like events, event sources, and listeners. It describes common event classes and listener interfaces in Java and the steps to handle events. It also provides examples of handling key and mouse events. The document discusses adapter classes that provide default implementations of listener interfaces. Finally, it introduces the Swing framework, its features, hierarchy with AWT, and common Swing components like JPanel, JFrame, JLabel, JButton, and JTextField.

Uploaded by

Madeeha
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)
93 views32 pages

Unit 5 Swing

The document discusses Java GUI event handling and Swing components. It provides an introduction to event handling concepts like events, event sources, and listeners. It describes common event classes and listener interfaces in Java and the steps to handle events. It also provides examples of handling key and mouse events. The document discusses adapter classes that provide default implementations of listener interfaces. Finally, it introduces the Swing framework, its features, hierarchy with AWT, and common Swing components like JPanel, JFrame, JLabel, JButton, and JTextField.

Uploaded by

Madeeha
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/ 32

Unit-5 Swing

GUI using SWING Event Handling


Introduction to AWT and Swing
Difference Between AWT and Swing Components
Swing Components
o JFrame o JPanel o JLabel o JButton o JRadioButton o JCheckBox
o JTextField o JPasswordField o JTextArea o JScrollBar o JComboBox o JList
o JToggleButton o JTabbedPane o JSlider
o JProgressBar o JTextPane
Menus
o JMenuBar o JMenu o JMenuItem

Introduction to Event Handling


Event Delegation Model
Event Packages
o AWT Event Package
o Swing Event Package
Event Classes
o ActionEvent o ItemEvent o FocusEvent
o MouseEvent o MouseWheelEvent o TextEvent
o WindowEvent

Listener Interfaces
o ActionListener o ItemListener o FocusListener
o KeyListener o MouseListener o MoutMotionListener
o TextListener o WindowListener, etc
Adaptor Classes
o FocusAdaptor o KeyAdaptor o MouseAdaptor o MouseMotionAdaptor

Java GUI Event Handling


Any program that uses GUI (graphical user interface) such as Java application
written for windows, is event driven. Event describes the change in state of any
object. For Example : Pressing a button, Entering a character in Textbox, Clicking
or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,

 Events : An event is a change in state of an object.


 Events Source : Event source is an object that generates an event.

1
 Listeners : A listener is an object that listens to the event. A listener gets
notified when an event occurs.

How Events are handled?


A source generates an Event and send it to one or more listeners registered with
the source. Once event is received by the listener, they process the event and then
return. Events are supported by a number of Java packages, like java.util,
java.awt and java.awt.event.

Important Event Classes and Interface

Event Classes Description Listener Interface


generated when button is pressed,
ActionEvent menu-item is selected, list-item is ActionListener
double clicked
generated when mouse is dragged,
moved,clicked,pressed or released
MouseEvent MouseListener
and also when it enters or exit a
component
generated when input is received
KeyEvent KeyListener
from keyboard
generated when check-box or list
ItemEvent ItemListener
item is clicked
generated when value of textarea or
TextEvent TextListener
textfield is changed
generated when mouse wheel is
MouseWheelEvent MouseWheelListener
moved
generated when window is activated,
WindowEvent deactivated, deiconified, iconified, WindowListener
opened or closed
generated when component is
ComponentEvent ComponentEventListener
hidden, moved, resized or set visible
generated when component is added
ContainerEvent ContainerListener
or removed from container
generated when scroll bar is
AdjustmentEvent AdjustmentListener
manipulated
generated when component gains or
FocusEvent FocusListener
loses keyboard focus

2
Steps to handle events:

1. Implement appropriate interface in the class.


2. Register the component with the listener.

Example of Event Handling


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

public class Test extends Applet implements KeyListener


{
String msg="";
public void init()
{
addKeyListener(this);
}
public void keyPressed(KeyEvent k)
{
showStatus("KeyPressed");
}
public void keyReleased(KeyEvent k)
{
showStatus("KeyRealesed");
}
public void keyTyped(KeyEvent k)
{
msg = msg+k.getKeyChar();
repaint();
}
public void paint(Graphics g)
{
g.drawString(msg, 20, 40);
}
}

HTML code:

<applet code="Test" width=300, height=100>


</applet>

3
//handling mouse events..
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=MouseEventEx width=300 height=200>
</applet>
*/
public class MouseEventEx extends Applet implements MouseListener
{
String status="";
int x=0,y=0;
public void init()
{
addMouseListener(this);
}
public void mousePressed(MouseEvent obj)
{
x=obj.getX();
y=obj.getY();
status="Mouse button pressed.";
repaint();
}

public void mouseReleased(MouseEvent obj)


{
x=obj.getX();
y=obj.getY();
status="Mouse button released.";
repaint();
}

4
public void mouseEntered(MouseEvent obj)
{
x=20;
y=20;
status="Mouse entered.";
repaint();
}
public void mouseExited(MouseEvent obj)
{
x=20;
y=20;
status="Mouse exited.";
repaint();
}
public void mouseClicked(MouseEvent obj)
{
x=25;
y=25;
showStatus("Mouse button clicked");
//status="Mouse entered.";
repaint();
}

public void paint(Graphics g)


{
g.setColor(Color.red);
g.drawString(status,x,y);
}
}

5
Java Adapter Classes
Java adapter classes provide the default implementation of listener interfaces. If
you inherit the adapter class, you will 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 Adapter classes with their corresponding listener
interfaces are given below.

java.awt.event Adapter classes

Adapter class Listener interface


WindowAdapter WindowListener
KeyAdapter KeyListener
MouseAdapter MouseListener
MouseMotionAdapter MouseMotionListener
FocusAdapter FocusListener
ComponentAdapter ComponentListener
ContainerAdapter ContainerListener
HierarchyBoundsAdapter HierarchyBoundsListener

//Using adapter class for MouseListener.


import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code=AdapterEx width=300 height=200>
</applet>
*/
public class AdapterEx extends Applet
{
String msg="";
public void init()
{
addMouseListener(new MyAdapter(this));
}
public void paint(Graphics g)
{
Font f=new Font("Verdana",Font.BOLD,24);
g.setFont(f);
g.setColor(Color.red);
g.drawString(msg,20,20);

6
}
}
class MyAdapter extends MouseAdapter
{
AdapterEx adapter;
public MyAdapter(AdapterEx adapter)
{
this.adapter=adapter;
}
public void mouseEntered(MouseEvent obj)
{
adapter.msg="Mouse Entered.";
adapter.setBackground(Color.blue);
adapter.repaint();
}
public void mouseExited(MouseEvent obj)
{
adapter.msg="Mouse Exited.";
adapter.setBackground(Color.cyan);
adapter.repaint();
}
}

7
Java Swing
Swing Framework contains a set of classes that provides more powerful and flexible
GUI components than those of AWT. Swing provides the look and feel of modern
Java GUI. Swing library is an official Java GUI tool kit released by Sun
Microsystems. It is used to create graphical user interface with Java.

Swing classes are defined in javax.swing package and its sub-packages.

Main Features of Swing Toolkit

1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel

Swing and JFC

JFC is an abbreviation for Java Foundation classes, which encompass a group of


features for building Graphical User Interfaces(GUI) and adding rich graphical
functionalities and interactivity to Java applications. Java Swing is a part of Java
Foundation Classes (JFC).

Features of JFC

 Swing GUI components.


 Look and Feel support.
 Java 2D.

8
AWT and Swing Hierarchy

Introduction to Swing Classes

JPanel : JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.

JFrame : JFrame is Swing's version of Frame and is descended directly from Frame
class. The component which is added to the Frame, is refered as its Content.

JWindow : This is Swing's version of Window and has descended directly from
Window class. Like Window it uses BorderLayout by default.

JLabel : JLabel has descended from JComponent, and is used to create text labels.

JButton : JButton class provides the functioning of push button. JButton allows an
icon, string or both associated with a button.

JTextField : JTextFields allow editing of a single line of text.

Creating a JFrame

There are two ways to create a JFrame Window.

9
1. By instantiating JFrame class.
2. By extending JFrame class.

Creating JFrame window by Instantiating JFrame class


import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package
public class First
{
JFrame jf;
public First()
{
jf = new JFrame("MyWindow"); //Creating a JFrame with name MyWindow
JButton btn = new JButton("Say Hello");//Creating a Button named Say Hello

jf.add(btn); //adding button to frame

jf.setLayout(new FlowLayout());//setting layout using FlowLayout object


jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);//setting close
operation.
jf.setSize(400, 400); //setting size
jf.setVisible(true); //setting frame visibility
}
public static void main(String[] args)
{
new First();
}
}

Creating JFrame window by extending JFrame class


import javax.swing.*; //importing swing package
import java.awt.*; //importing awt package

10
public class Second extends JFrame
{
public Second()
{
setTitle("MyWindow"); //setting title of frame as MyWindow
JLabel lb = new JLabel("Welcome to My Second Window");//Creating a
label named Welcome to My Second Window
add(lb); //adding label to frame.
setLayout(new FlowLayout()); //setting layout using FlowLayout
object.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //setting close
operation.
setSize(400, 400); //setting size
setVisible(true); //setting frame visibility
}

public static void main(String[] args)


{
new Second();
}
}

Points To Remember

1. Import the javax.swing and java.awt package to use the classes and methods
of Swing.
2. While creating a frame (either by instantiating or extending Frame class),
following two attributes are must for visibility of the frame:

setSize(int width, int height);


setVisible(true);

11
3. When you create objects of other components like Buttons, TextFields, etc.
Then you need to add it to the frame by using the method -
add(Component's Object);
4. You can add the following method also for resizing the frame -
setResizable(true);

Java Swing Components and Containers


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

A container holds a group of components. It provides a space where a component


can be managed and displayed. Containers are of two types:

1. Top level Containers


o It inherits Component and Container of AWT.
o It cannot be contained within other containers.
o Heavyweight.
o Example: JFrame, JDialog, JApplet
2. Lightweight Containers
o It inherits JComponent class.
o It is a general purpose container.
o It can be used to organize related components together.
o Example: JPanel

JButton
JButton class provides functionality of a button. JButton class has three constuctors,

JButton(Icon ic)

JButton(String str)

JButton(String str, Icon ic)

It allows a button to be created using icon, a string or both. JButton supports ActionEvent. When a button
is pressed an ActionEvent is generated.

Example using JButton

12
import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class testswing extends JFrame
{

testswing()
{
JButton bt1 = new JButton("Yes"); //Creating a Yes Button.
JButton bt2 = new JButton("No"); //Creating a No Button.
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE) //setting close operation.
setLayout(new FlowLayout()); //setting layout using FlowLayout object
setSize(400, 400); //setting size of Jframe
add(bt1); //adding Yes button to frame.
add(bt2); //adding No button to frame.

setVisible(true);
}
public static void main(String[] args)
{
new testswing();
}
}

JTextField

JTextField is used for taking input of single line of text. It is most widely used text
component. It has three constructors,

13
JTextField(int cols)
JTextField(String str, int cols)
JTextField(String str)

cols represent the number of columns in text field.

Example using JTextField


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class MyTextField extends JFrame
{
public MyTextField()
{
JTextField jtf = new JTextField(20); //creating JTextField.
add(jtf); //adding JTextField to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new MyTextField();
}
}

14
JTextArea

JPasswordField class is used to create a multiple line text input. This text area
does not display any scrollbars by default but you should use scroll panes if need it.
It has three constructors,

JTextArea()
JTextArea(int rows, int columns)
JTextArea(String text, int rows, int columns)

Here, rows and columns specify the number of rows and columns of the text area.

Some of its method as shown below:


String getText()

It returns the text written in the text area.


void setEditable(boolean edit)

If the edit is false then the text in the text area can not be modified.

JPasswordField

JPasswordField creates a text field which display the disks (dots) instead of the
actual characters. It has four constructors,

JPasswordField()
JPasswordField(int length)
JPasswordField(String str)
JPasswordField(String str, int length)

Here, the length specifies the length of the password string and the str specifies the string.

The following method returns the password text entered in the password field .
String getPassword()

// Example of JTextArea and JPasswordField


import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
/*
<applet code=JPasswordFieldEx width=300 height=200>
</applet>
*/

15
public class JPasswordFieldEx extends JApplet implements
ActionListener
{
JLabel l1,l2,l3,l4;
JTextArea text;
JPasswordField pass;
public void init()
{
Container pane=getContentPane();
pane.setLayout(new FlowLayout());
text=new JTextArea(3,15);
pass=new JPasswordField(10);
l1=new JLabel("Address");
l2=new JLabel("Password");
l3=new JLabel();
l4=new JLabel();
pane.add(l1);
pane.add(text);
pane.add(l2);
pane.add(pass);
pane.add(l3);
pane.add(l4);
pass.addActionListener(this);
}
public void actionPerformed(ActionEvent obj)
{
JPasswordField p=(JPasswordField)obj.getSource();
String password=new String(p.getPassword());
l4.setText("Your Password is : "+password);
l3.setText("Address : "+text.getText());
}
}

16
JCheckBox
JCheckBox class is used to create checkboxes in frame. Following is constructor for JCheckBox,

JCheckBox(String str)

Example using JCheckBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JCheckBox jcb = new JCheckBox("yes"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("no"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
jcb = new JCheckBox("maybe"); //creating JCheckBox.
add(jcb); //adding JCheckBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

17
JRadioButton
Radio button is a group of related button in which only one can be selected. JRadioButton class is used to
create a radio button in Frames. Following is the constructor for JRadioButton,

JRadioButton(String str)

Example using JRadioButton


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JRadioButton jcb = new JRadioButton("A"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("B"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("C"); //creating JRadioButton.
add(jcb); //adding JRadioButton to frame.
jcb = new JRadioButton("none");
add(jcb);
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

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

Example using JComboBox


import javax.swing.*;
import java.awt.event.*;
import java.awt.*;
public class Test extends JFrame
{
String name[] = {"Abhi","Adam","Alex","Ashkay"}; //list of name.
public Test()
{
JComboBox jc = new JComboBox(name); //initialzing combo box with list
of name.
add(jc); //adding JComboBox to frame.
setLayout(new FlowLayout());
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setSize(400, 400);
setVisible(true);
}
public static void main(String[] args)
{
new Test();
}
}

19
A program to change background color of a frame (Using Action Event)
import java.awt.*; //importing awt package
import javax.swing.*; //importing swing package
import java.awt.event.*; //importing event package

//For an event to occur upon clicking the button, ActionListener interface


should be implemented
class StColor extends JFrame implements ActionListener{

JFrame frame;
JPanel panel;
JButton b1,b2,b3,b4,b5;

StColor(){

frame = new JFrame("COLORS");


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

panel = new JPanel(); //Creating a panel which is a container and will


hold all the buttons
panel.setSize(100, 50);

b1 = new JButton("BLUE"); //Creating a button named BLUE


b1.addActionListener(this); //Registering the button with the listener

b2 = new JButton("RED"); //Creating a button named RED


b2.addActionListener(this); //Registering the button with the listener

b3 = new JButton("CYAN");//Creating a button named CYAN


b3.addActionListener(this);//Registering the button with the listener

b4 = new JButton("PINK"); //Creating a button named PINK


b4.addActionListener(this); //Registering the button with the listener

20
b5 = new JButton("MAGENTA"); //Creating a button named MAGENTA
b5.addActionListener(this); //Registering the button with the listener

//Adding buttons to the Panel


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

frame.getContentPane().add(panel); //adding panel to the frame


frame.setSize(500,300);
frame.setVisible(true);
frame.setLayout(new FlowLayout());

}
//The below method is called whenever a button is clicked
@Override
public void actionPerformed(ActionEvent e) {

//This method returns an object of the button on which the Event-


Pressing of button initially occurred
Object see = e.getSource();

if(see ==(b1)){ //Checking if the object returned is of button1


frame.getContentPane().setBackground(java.awt.Color.blue);
//changing the panel color to blue
}
if(see == b2){ //Checking if the object returned is of button2
frame.getContentPane().setBackground(java.awt.Color.red);
//changing the panel color to red
}
if(see == b3){ //Checking if the object returned is of button3
frame.getContentPane().setBackground(java.awt.Color.cyan);//changing
the panel color to cyan
}
if(see == b4){ //Checking if the object returned is of button4
frame.getContentPane().setBackground(java.awt.Color.pink);
//changing the panel color to pink
}
if(see == b5){ //Checking if the object returned is of button5
frame.getContentPane().setBackground(java.awt.Color.magenta);
//changing the panel color to magenta
}
}
}

class Test {
public static void main(String[] args) {
StColor o = new StColor();
}
}

21
Ouput:

Java 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
inherits the JMenuItem class.

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

JMenuBar class declaration

1. public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration

1. public class JMenu extends JMenuItem implements MenuElement, Accessible

JMenuItem class declaration

1. public class JMenuItem extends AbstractButton implements Accessible, MenuElement

22
Java 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 MenuExample();
28. }}

Output:

23
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");
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(null);
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. }
46. }

24
Output:

Java JScrollBar
The object of JScrollbar class is used to add horizontal and vertical scrollbar. It is an implementation of a
scrollbar. It inherits JComponent class.

JScrollBar class declaration


Let's see the declaration for javax.swing.JScrollBar class.

1. public class JScrollBar extends JComponent implements Adjustable, Accessible

Commonly used Constructors:

Constructor Description
JScrollBar() Creates a vertical scrollbar with the initial values.
Creates a scrollbar with the specified orientation and the
JScrollBar(int orientation)
initial values.
JScrollBar(int orientation, int value, int Creates a scrollbar with the specified orientation, value,
extent, int min, int max) extent, minimum, and maximum.

Java JScrollBar Example


1. import javax.swing.*;
2. class ScrollBarExample
3. {

25
4. ScrollBarExample(){
5. JFrame f= new JFrame("Scrollbar Example");
6. JScrollBar s=new JScrollBar();
7. s.setBounds(100,100, 50,100);
8. f.add(s);
9. f.setSize(400,400);
10. f.setLayout(null);
11. f.setVisible(true);
12. }
13. public static void main(String args[])
14. {
15. new ScrollBarExample();
16. }}

Java Abstract Window Toolkit(AWT)


AWT contains large number of classes and methods that allows you to create and
manage graphical user interface ( GUI ) applications, such as windows, buttons,
scroll bars,etc. The AWT was designed to provide a common set of tools for GUI
design that could work on a variety of platforms. The tools provided by the AWT are
implemented using each platform's native GUI toolkit, hence preserving the look
and feel of each platform. This is an advantage of using AWT.But the disadvantage
of such an approach is that GUI designed on one platform may look different when
displayed on another platform.

AWT is the foundation upon which Swing is made i.e Swing is a set of GUI interfaces
that extends the AWT. But now a days AWT is merely used because most GUI Java
programs are implemented using Swing because of its rich implementation of GUI
controls and light-weighted nature.

26
Java AWT Hierarchy

Component class

Component class is at the top of AWT hierarchy. Component is an abstract class


that encapsulates all the attributes of visual component. A component object is
responsible for remembering the current foreground and background colors and the
currently selected text font.

Container

Container is a component in AWT that contains another component like button,


text field, tables etc. Container is a subclass of component class. Container class
keeps track of components that are added to another component.

Panel

Panel class is a concrete subclass of Container. Panel does not contain title bar,
menu bar or border. It is container that is used for holding components.

27
Window class

Window class creates a top level window. Window does not have borders and
menubar.

Frame

Frame is a subclass of Window and have resizing canvas. It is a container that


contain several different components like button, title bar, textfield, label etc. In
Java, most of the AWT applications are created using Frame window. Frame class
has two different constructors,

Frame() throws HeadlessException

Frame(String title) throws HeadlessException

Creating a Frame

There are two ways to create a Frame. They are,

1. By Instantiating Frame class


2. By extending Frame class

Creating Frame Window by Instantiating Frame class


import java.awt.*;
public class Testawt
{
Testawt()
{
Frame fm=new Frame(); //Creating a frame
Label lb = new Label("welcome to java graphics"); //Creating a
label
fm.add(lb); //adding label to the frame
fm.setSize(300, 300); //setting frame size.
fm.setVisible(true); //set frame visibilty true
}
public static void main(String args[])
{

28
Testawt ta = new Testawt();
}

Creating Frame window by extending Frame class


package testawt;
import java.awt.*;
import java.awt.event.*;
public class Testawt extends Frame
{
public Testawt()
{
Button btn=new Button("Hello World");
add(btn); //adding a new Button.
setSize(400, 500); //setting size.
setTitle("StudyTonight"); //setting title.
setLayout(new FlowLayout()); //set default layout for frame.
setVisible(true); //set frame visibilty true.
}
public static void main (String[] args)
{
Testawt ta = new Testawt(); //creating a frame.
}
}

29
Points to Remember:

1. While creating a frame (either by instantiating or extending Frame class),


Following two attributes are must for visibility of the frame:
o setSize(int width, int height);
o setVisible(true);
2. When you create other components like Buttons, TextFields, etc. Then you
need to add it to the frame by using the method - add(Component's
Object);
3. You can add the following method also for resizing the frame -
setResizable(true);

Difference between AWT and Swing

There are many differences between java awt and swing that are given below.

No. Java AWT Java Swing


Java swing components are platform-
1) AWT components are platform-dependent.
independent.
2) AWT components are heavyweight. Swing components are lightweight.
Swing supports pluggable look and
3) AWT doesn't support pluggable look and feel.
feel.
Swing provides more powerful
components such as tables, lists,
4) AWT provides less components than Swing.
scrollpanes, colorchooser, tabbedpane
etc.
AWT doesn't follows MVC(Model View Controller)
5) where model represents data, view represents presentation Swing follows MVC.
and controller acts as an interface between model and view.

30
//Example of AWT Controls
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
/*
<applet code="AWTControlsEx" width=300 height=500>
</applet>
*/
public class AWTControlsEx extends Applet implements ActionListener
{
Label Lname,Lpass,Lcity,Laddr,Lgender,Lmarital,Lselect,l1,l2,l3;
TextField name,pass;
TextArea addr;
Checkbox male,female,married;
CheckboxGroup gender;
Choice city;
List sel1,sel2;
Button click;
public void init()
{
Lname=new Label("Name : ");
Lpass=new Label("Password:");
Laddr=new Label("Address :");
Lcity=new Label("City :");
Lgender=new Label("Gender :");
name=new TextField(10);
pass=new TextField(10);
pass.setEchoChar('*');
addr=new TextArea("",3,20,TextArea.SCROLLBARS_BOTH);
city=new Choice();
city.add("Bhacha");
city.add("Rajkot");
city.add("Mumbai");
gender=new CheckboxGroup();
male=new Checkbox("Male",gender,true);
female=new Checkbox("Female",gender,false);
l1=new Label();
Lmarital=new Label("Marital Status :");
married=new Checkbox("Married");
click=new Button("Click Me");
l2=new Label();
Lselect=new Label("Selection is :");
sel1=new List(10);
l3=new Label();
sel2=new List();
setLayout(new GridLayout(12,2));
add(Lname);
add(name);
add(Lpass);add(pass);

31
add(Laddr);add(addr);
add(Lcity);add(city);
add(Lgender);add(male);
add(l1);add(female);
add(Lmarital);add(married);
add(click);add(l2);
add(Lselect);add(sel1);
add(l3);add(sel2);
click.addActionListener(this);
}
public void actionPerformed(ActionEvent obj)
{
sel1.add("Name : "+name.getText());
sel1.add("Password : "+pass.getText());
sel1.add("Address : "+addr.getText());
sel2.add("City : "+city.getSelectedItem());
sel2.add("Gender : "+gender.getSelectedCheckbox().getLabel());
String s=married.getState()? "Married":"Unmarried";
sel2.add("Marital Status : "+s);
}}

32

You might also like