Java GUI, AWT, Applet, Swing

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 87

Introduction to GUI in

Java

AWT, Event Handling, Applet and


Swing
GUI-Graphical User Interface

 Why GUI?
 What is GUI?
 Difference between Console and GUI
 Example
What is GUI?

 Graphical User Interface


 GUI is a type of user interface that allows
users to interact with the screen using
graphical components(Visual indicators)
rather than text commands.
Checkbox, Choice,
 Example : Calculator in our PC. Label, List,
Scrollbar,ScrollPane,
TextArea, TextField
Two APIs

 There are two sets of Java APIs for graphics programming:


 1. AWT (Abstract Windowing Toolkit)
 2. Swing
Introduction to AWT

 Consists of 12 packages
 Mainly two packages are used more
 java.awt
 java.awt.event
 This packages also contains classes for gui use
Classes in AWT

 The java.awt package contains the core AWT graphics classes


 GUI Compenet classes such aas Button,TextFeild and Label),
 GUI Container classes such as Frame, Panel, Dailog and scfrollPanel
 Layout managers such as FLowLayout, Borderlayout and GridLayout
 Custom graphics classes such as Graphics, Color and Front.
 The java.awt.event package supports event hadling
 Event classes such as Action Event, MouseEvent,KeyEvent and WindowEvent.
 Event Listener Interfaces such as ActionListener, MouseListener, KeyListener and
WindowListener
Java AWT Hierarchy

 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.
 Container
 The Container is a component in AWT that can contain another components like buttons,
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 like button, 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.
AWT Components and Containers
Components : Container:
 Button  Panel
 Label  Dialog
 TextField  Toolkit
 TextArea  Window
 Checkbox  Frame
 CheckboxGroup  Applet
 Choice
 List
 Canvas
 Scrollbar
 MenuItem and Menu
 PopupMenu
Useful Methods of Component class
Method Description

public void add(Component c) inserts a component on this


component.
public void setSize(int width,int sets the size (width and height) of
height) the component.
public void defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean changes the visibility of the
status) component, by default false.
Java AWT Example

 To create simple awt example, you need a frame. There are two ways to
create a frame in AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)
AWT Example by Inheritance
import java.awt.*;
class First extends Frame{
First(){
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}}
AWT Example by Association
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Event Handling Model of AWT

Event object

Event handling
methods

Event source Event listener


Action Events on Buttons

ActionEvent

actionPerformed(..)

Button ActionListener
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 generates an event and sends it
to one or more listeners.
 In this scheme, the listener simply waits until it receives an event.
 Once received, the listener processes the event and then returns.
 The advantage of this design 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 a separate 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.
 This is a more efficient way to handle events than the design used by
the old Java 1.0 approach. Previously, an event was propagated up the
containment hierarchy until it was handled by a component.
 This required components to receive events that they did not process,
and it wasted valuable time.The delegation event model eliminates
this overhead.
Note
 Java also allows you to process events without using the delegation
event model.
 This can be done by extending an AWT component.
How to Attach an Event Listener to an
Event Source
o is an event source
h is an event listener of type XXX

o.addXXX(h)

where XXX is one of the following:


ActionListener
MouseListener ComponentListener
MouseMotionListener FocusListener
KeyListener TextListener
WindowListener AdjustmentListener
ItemListener
The ActionListener Interface

interface ActionListener {
public void actionPerformed(ActionEvent e);
}

 Possible event sources


 Button
 List
 TextField
 MenuItem
Example
Hello World (version 1)
import java.awt.*;
import java.awt.event.*;
public class TestButtonAction {
public static void main(String[] args){
Frame f = new Frame("TestButton");
f.setSize(200,200);
Button hw = new Button("Hello World!");
f.add(hw);

hw.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
System.exit(0);
}
});
f.setVisible(true);
}
}
Example
Hello World (version 2)
class MyFrame extends Frame implements ActionListener {
Button hw;
public MyFrame(){
super("Test Button");
setSize(200,200);
hw = new Button("Hello World!");
add(hw);
hw.addActionListener(this);
show();
}

public void actionPerformed(ActionEvent o){


System.exit(0);
}
}
Example
Hello World (version 3)
class MyFrame extends Frame {
Button hw;
public MyFrame(){
super("Test Button");
setSize(200,200);
hw = new Button("Hello World!");
add(hw);
hw.addActionListener(new MyActionListener());
show();

class MyActionListener implements ActionListener {


public void actionPerformed(ActionEvent o){
System.exit(0);
}
}
}
}
MouseListener

mouseClicked(MouseEvent)
Invoked when the mouse has been clicked on a component.
mouseEntered(MouseEvent)
Invoked when the mouse enters a component.
mouseExited(MouseEvent)
Invoked when the mouse exits a component.
mousePressed(MouseEvent)
Invoked when a mouse button has been pressed on a component.
mouseReleased(MouseEvent)
Invoked when a mouse button has been released on a component.
MouseMotionListener

 mouseDragged(MouseEvent)
 Invoked when a mouse button is pressed on a component and then dragged.
 mouseMoved(MouseEvent)
 Invoked when a mouse is moved..
List of Java Listeners
Event Classes Description Listener Interface

ActionEvent generated when button is pressed, menu-item is selected, list-item is double clicked ActionListener

MouseEvent generated when mouse is dragged, moved,clicked,pressed or released and also when it enters or exit a MouseListener
component

KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEvent generated when mouse wheel is moved MouseWheelListener

WindowEvent generated when window is activated, deactivated, deiconified, iconified, opened or closed WindowListener

ComponentEvent generated when component is hidden, moved, resized or set visible ComponentEventListener

ContainerEvent generated when component is added or removed from container ContainerListener

AdjustmentEvent generated when scroll bar is manipulated AdjustmentListener

FocusEvent generated when component gains or loses keyboard focus FocusListener


Listener Interface Adapter Class Listener Methods

ActionListener none actionPerformed(ActionEvent)

ChangeListener none stateChanged(ChangeEvent)

componentHidden(ComponentEvent)
componentMoved(ComponentEvent)
ComponentListener ComponentAdapter
componentResized(ComponentEvent)
componentShown(ComponentEvent)

componentAdded(ContainerEvent)
ContainerListener ContainerAdapter
componentRemoved(ContainerEvent)

focusGained(FocusEvent)
FocusListener FocusAdapter
focusLost(FocusEvent)

ItemListener none itemStateChanged(ItemEvent)

keyPressed(KeyEvent)
KeyListener KeyAdapter keyReleased(KeyEvent)
keyTyped(KeyEvent)

menuKeyPressed(MenuKeyEvent)
MenuKeyListener none menuKeyReleased(MenuKeyEvent)
menuKeyTyped(MenuKeyEvent)

menuCanceled(MenuEvent)
MenuListener none menuDeselected(MenuEvent)
menuSelected(MenuEvent)

mouseClicked(MouseEvent)
mouseEntered(MouseEvent)
MouseListener MouseAdapter, MouseInputAdapter mouseExited(MouseEvent)
mousePressed(MouseEvent)
mouseReleased(MouseEvent)

mouseDragged(MouseEvent)
MouseMotionListener MouseMotionAdapter, MouseInputAdapter
mouseMoved(MouseEvent)

mouseWheelMoved(MouseWheelEvent)
MouseWheelListener MouseAdapter
MouseAdapter<MouseEvent>

popupMenuCanceled(PopupMenuEvent)
PopupMenuListener none popupMenuWillBecomeInvisible(PopupMenuEvent)
popupMenuWillBecomeVisible(PopupMenuEvent)

windowActivated(WindowEvent)
windowClosed(WindowEvent)
windowClosing(WindowEvent)
WindowListener WindowAdapter windowDeactivated(WindowEvent)
windowDeiconified(WindowEvent)
windowIconified(WindowEvent)
windowOpened(WindowEvent)

WindowStateListener WindowAdapter windowStateChanged(WindowEvent)


Java Adapter Class
 Java adapter classes provide the
default implementation of Adapter class Listener interface
listener interfaces. If you inherit
the adapter class, you will not be WindowAdapter WindowListener
forced to provide the
implementation of all the KeyAdapter KeyListener
methods of listener interfaces. So MouseAdapter MouseListener
it saves code.
MouseMotionAdapter MouseMotionListener
 The adapter classes are found in
java.awt.event, java.awt.dnd FocusAdapter FocusListener
and javax.swing.event packages. ComponentAdapter ComponentListener
The Adapter classes with their
corresponding listener interfaces ContainerAdapter ContainerListener
are given below.
HierarchyBoundsAdapter HierarchyBoundsListener
MouseAdapter

class MouseAdapter implements MouseListener {


public void mouseClicked(MouseEvent e){}

public void mouseEntered(MouseEvent e){}

public void mouseExited(MouseEvent e){}

public void mousePressed(MouseEvent e){}

public void mouseReleased(MouseEvent e){}


}
Example
import java.applet.*;
import java.awt.*;
import java.awt.event.*;
public class TestMouseListener {
public static void main(String[] args){
Frame f = new Frame("TestMouseListener");
f.setSize(500,500);

f.addMouseListener(new MouseAdapter(){
public void mouseClicked(MouseEvent e){
System.out.println("Mouse clicked: ("+e.getX()+","+e.getY()+")");
}
....
}
Way to close AWT Window
 We can close the AWT Window or Frame by calling dispose() or System.exit()
inside windowClosing() method. The windowClosing() method is found in
WindowListener interface and WindowAdapter class.
 The WindowAdapter class implements WindowListener interfaces. It provides
the default implementation of all the 7 methods of WindowListener interface.
To override the windowClosing() method, you can either use WindowAdapter
class or WindowListener interface.
 If you implement the WindowListener interface, you will be forced to override
all the 7 methods of WindowListener interface. So it is better to use
WindowAdapter class.
 There are many ways to override windowClosing() method:
 By anonymous class
 By inheriting WindowAdapter class
 By implementing WindowListener interface
Layout Manager
 The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
Border Layout
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:
 public static final int NORTH
 public static final int SOUTH
 public static final int EAST
 public static final int WEST
 public static final int CENTER
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between
the components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Grid Layout
The GridLayout is used to arrange the components in rectangular grid.
One component is displayed in each rectangle.

Constructors of GridLayout class :


 GridLayout(): creates a grid layout with one column per component in
a row.
 GridLayout(int rows, int columns): creates a grid layout with the
given rows and columns but no gaps between the components.
 JGridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.
Flow Layout
The FlowLayout is used to arrange the components in a line, one after
another (in a flow). It is the default layout of applet or panel.
 Fields of FlowLayout class
 public static final int LEFT
 public static final int RIGHT
 public static final int CENTER
 public static final int LEADING
 public static final int TRAILING
 Constructors of FlowLayout class
 FlowLayout(): creates a flow layout with centered alignment and a
default 5 unit horizontal and vertical gap.
 FlowLayout(int align): creates a flow layout with the given
alignment and a default 5 unit horizontal and vertical gap.
 FlowLayout(int align, int hgap, int vgap): creates a flow layout with
the given alignment and the given horizontal and vertical gap.
 f.setLayout(new FlowLayout(FlowLayout.RIGHT));
Box Layout
The BoxLayout is used to arrange the components either vertically
or horizontally. For this purpose, BoxLayout provides four constants.
They are as follows:
 Fields of BoxLayout class
 public static final int X_AXIS
 public static final int Y_AXIS
 public static final int LINE_AXIS
 public static final int PAGE_AXIS
 Constructor of BoxLayout class
 BoxLayout(Container c, int axis): creates a box layout that
arranges the components with the given axis.
Card Layout
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout class
 CardLayout(): creates a card layout with zero horizontal and vertical gap.
 CardLayout(int hgap, int vgap): creates a card layout with the given horizontal
and vertical gap.
Commonly used methods of CardLayout class
 public void next(Container parent): is used to flip to the next card of the given
container.
 public void previous(Container parent): is used to flip to the previous card of the
given container.
 public void first(Container parent): is used to flip to the first card of the given
container.
 public void last(Container parent): is used to flip to the last card of the given
container.
 public void show(Container parent, String name): is used to flip to the specified
card with the given name.
What is an applet?
 Applet is a special type of program that is embedded in the webpage
to generate the dynamic content. It runs inside the browser and works
at client side.
 An applet is a small Java program that
is embedded and ran in some other
Java interpreter program such as
a Java technology-enabled browser
Sun’s applet viewer program called
appletviewer
An Applet
Applets, web page, client , server
Advantage of Applet

 There are many advantages of applet.


They are as follows:
 It works at client side so less response time.
 Secured
 It can be executed by browsers running under many platforms, including
Linux, Windows, Mac Os etc.
 Drawback of Applet
 Plugin is required at client browser to execute applet.
Hierarchy of Applet
Why No Main()

Java Applets have an init method instead of main.


... Applets are standalone programs which require a
third party tool for its execution that is either it is
java enabled web browser or applet runner. So it
doesn't have main().
Lifecycle of Java Applet

Applet is initialized.
Applet is started.
Applet is painted.
Applet is stopped.
Applet is destroyed.
Lifecycle methods for Applet:
 The java.applet.Applet class provides 4 life cycle methods and
java.awt.Component class provides 1 life cycle methods 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.
 public void init(): is used to initialized the Applet. It is invoked only once.
 public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
 public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
 public void destroy(): is used to destroy the Applet. It is invoked only once.

java.awt.Component class
 public void paint(Graphics g): is used to paint the Applet. It provides Graphics class
object that can be used for drawing oval, rectangle, arc etc.
First Applet
 There are two ways to run an applet
 By html file.
 By appletViewer tool (for testing purpose).
//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome",150,150);
}

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

<html>
<body>
<applet code="First.class" width="300" height="300">
</applet>
</body>
</html>
Simple example of Applet by appletviewer tool:

//First.java
import java.applet.Applet;
import java.awt.Graphics;
public class First extends Applet{

public void paint(Graphics g){


g.drawString("welcome to applet",150,150);
}

}
/*
<applet code="First.class" width="300" height="300">
</applet>
*/
AWT Example
Sample Graphics methods
Applet Security

 For security reasons, applets that are loaded over


the network have several restrictions.
 an applet cannot ordinarily read or write files on
the computer that it's executing on.
 an applet cannot make network connections
except to the host that it came from.
Graphics example
import java.applet.Applet;
import java.awt.*;

public class GraphicsDemo extends Applet{

public void paint(Graphics g){


g.setColor(Color.red);
g.drawString("Welcome",50, 50);
g.drawLine(20,30,20,300);
g.drawRect(70,100,30,30);
g.fillRect(170,100,30,30);
g.drawOval(70,200,30,30);

g.setColor(Color.pink);
g.fillOval(170,200,30,30);
g.drawArc(90,150,30,30,30,270);
g.fillArc(270,150,30,30,0,180);

}
}
/*<applet code="GraphicsDemo.class" width="300" height="300"> */
Display image in Applet
 Applet is mostly used in games and animation. For this purpose image is required
to be displayed. The java.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 used draw the specified image.
 This method draws the image referred by Image object img, at the coordinates xand y in
an applet's window. We also need to pass an object of ImageObserver interface. We can
do by passing this reference of our Applet class, because it implements ImageObserver
interface.
 getCodeBase() method of Applet class.
 public URL getCodeBase()
 This method gives us the location of the directory in which our applet code file is
located. This location is returned to us in terms of an object of URL class. Using this
object of URL class, we can get and load any image file present in the same directory
using the next two methods.
 getImage() method of Applet class.
 public Image getImage(URL url, String name)
 This method gets the image file in the form of Image object. This image file named name
is present in the directory location specified by url. This directory also contains the
applet code.
Animation in Applet
 import java.awt.*;
 import java.applet.*;
 public class AnimationExample extends Applet {

 Image picture;

 public void init() {


 picture =getImage(getDocumentBase(),"bike_1.gif");
 }

 public void paint(Graphics g) {


 for(int i=0;i<500;i++){
 g.drawImage(picture, i,30, this);

 try{Thread.sleep(100);}catch(Exception e){}
 }
 }
 }
Event Handling in Applet

 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.
 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.
Event Classes Description Listener Interface
 Steps to handle events: ActionEvent generated when button is pressed, menu-item is selected, list-item is ActionListener
double clicked

 Implement appropriate interface in the class. MouseEvent generated when mouse is dragged, moved,clicked,pressed or released MouseListener
and also when it enters or exit a component

 Register the component with the listener.


KeyEvent generated when input is received from keyboard KeyListener

ItemEvent generated when check-box or list item is clicked ItemListener

TextEvent generated when value of textarea or textfield is changed TextListener

MouseWheelEve generated when mouse wheel is moved MouseWheelListener


nt
WindowEvent generated when window is activated, deactivated, deiconified, WindowListener
iconified, opened or closed

ComponentEven generated when component is hidden, moved, resized or set visible ComponentEventListener
t

ContainerEvent generated when component is added or removed from container ContainerListener

AdjustmentEven generated when scroll bar is manipulated AdjustmentListener


t
FocusEvent generated when component gains or loses keyboard focus FocusListener
Event Handling in Applet

 An event in a java program is generated upon clicking a button, typing in a


textfield, checking a checkbox or radio box, selecting an item in a drop down
list etc. In this article we will understand how such events are handled, when
generated from within an applet window.
 In order to handle such events, we need to register our program to listen such
events when they are generated by our program, during its execution.
 How do we register our program to listen events generated by it?
 To listen events, we must implement interfaces related to the kind of event that is
generated by our program. For example, if our program has a button in it and in
order to listen a button click event, we must implement ActionListener interface
and implement its method actionPerformed(), which gives us the name of the
button that was clicked, that lead to a button click event.
Example of event handling
Event Handling Example in Applet

 In the forthcoming code, we have created an applet named Applet2 by extending the Applet
class, besides this we have also implemented -
 ActionListener interface and have implemented its actionPerformed() method to listen to
button click events or when an Enter key is pressed in a textfield within our program.
 ItemListener interface and have implemented its itemStateChanged() method to listen to
checking/unchecking of checkboxes or radio boxes in our program.
 Program Analysis

In our code two kinds of events could be generated -Whenever we press the Enter key while
entering the information in textfield, an ActionEvent is generated
and actionPerformed() method is called, which calls repaint() method, which in turns calls
the paint() method defined in our Applet class, to display the name or city you've entered.
 Whenever a checkbox is checked or unchecked an ItemEvent is generated
and itemStateChanged() method is called, which calls repaint() method. which in turn calls
the paint() method defined in our applet class, to show the gender you've selected in the
applet.
Parameter Passing in Applet
 To pass the parameters to the Applet we need to use the param attribute of
<applet> tag in html code.
 To retrieve a parameter's value, we need to use the getParameter() method of
Applet class in java code.
 public String getParameter(String name)
 Method takes a String argument name, which represents the name of the parameter
which was specified with the param attribute in the <applet> tag.
 Method returns the value of the name parameter(if it was defined) else null is returned.
 <applet code="Applet" width="400" height="200"> <param name="Name"
value="Roger"> <param name="Age" value="26"> </applet>
 Sample HTML code for param attribute

 Example of Parameter Passing


 In the example, we are going to pass a few parameters like Name, Age, Sport,
Food, Fruit, Destination to the applet using param attribute in <applet>
 Next, we will retrieve the values of these parameters using getParameter()
method of Applet class.
Passing a parameter to an applet to set
a message on its status bar.
 showStatus() method of Applet class is called to set a message on the status
bar of the applet window.
 In the example, we are passing a parameter to the applet and setting the
message on the status bar of the applet window with the value of this
parameter.
 showStatus() method of Applet class is called to set a message on the status
bar of the applet window.
Swing Applets
 So far, we have created the applets based on AWT(Abstract Window Toolkit) by
extending the Applet class of the awt package. We can even create applets based
on the Swing package. In order to create such applets, we must extend JApplet
class of the swing package. JApplet extends Applet class, hence all the features of
Applet class are available in JApplet as well, including JApplet's own Swing based
features. Swing applets provides an easier to use user interface than AWT applets.
 When we create an AWT applet, we implement the paint(Graphics g) method to
draw in it but when we create a Swing applet, we implement
paintComponent(Graphics g) method to draw in it.
 For an applet class that extends Swing's JApplet class, the way elements like
textfield, buttons, checksboxes etc are added to this applet is performed by using
a default layout manager, i.e. BorderLayout
 JApplet is a top-level container class and you should never draw on it directly,
instead you should draw on the component class like JPanel and then add this
JPanel to the JApplet, as shown in the upcoming code.
 JApplet is a top-level container class and you should never draw on it directly,
instead you should draw on the component class like JPanel and then add this
JPanel to the JApplet, as shown in the upcoming code.
Examples of JApplet

setLayout(new BorderLayout());

add(north, BorderLayout.NORTH); //Adds button named north in the NORTH direction


add(south, BorderLayout.SOUTH); //Adds button named south in the SOUTH direction
add(east, BorderLayout.EAST); //Adds button named east in the EAST direction
add(west, BorderLayout.WEST); //Adds button named west in the WEST direction
Applet Communication

 java.applet.AppletContext class provides the facility of communication


between applets. We provide the name of applet through the HTML file. It
provides getApplet() method that returns the object of Applet. Syntax:

 public Applet getApplet(String name){}


Applet Assignment

 Write an applet program for scientific calculator.


 Write an applet program for parameter passing and showing status in status
bar.
 Write a program to demonstrate applet life cycle.
 Write an applet program for displaying digital clock.
 Write an applet program for displaying analog clock.
 Write an applet program for drawing a sketch on screen using mouse.
JAVA Swing
Introduction
 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.
AWT Vs. Swing

No. Java AWT Java Swing


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

2) AWT components are heavyweight. Swing components


are lightweight.
3) AWT doesn't support pluggable look and feel. Swing supports pluggable
look and feel.
4) AWT provides less components than Swing. Swing provides more
powerful componentssuch as
tables, lists, scrollpanes,
colorchooser, tabbedpane etc.

5) AWT doesn't follows MVC(Model View Controller) Swing follows MVC.


where model represents data, view represents
presentation and controller acts as an interface
between model and view.
Why Light-Weight?

 Swing components depend less on the target platform and use less of the
native GUI resource. Hence the Swing components that don't rely on native
GUI are referred to as lightweight components.
 AWT components are referred to as heavyweight components.
What is JFC

 The Java Foundation Classes (JFC) are a set of GUI components which simplify
the development of desktop applications.
 JFC is an extension of the original Java Abstract Windowing Toolkit (AWT).
 Using JFC and Swing, an additional set of program components, a programmer
can write programs that are independent of the windowing system within a
particular operating system.
Hierarchy of Java Swing classes
Swing Components
 Containers
 Contain and manage other components.
 Top Level/Internal
 Examples: JFrame (Top Level), JScrollPane, JPanel.

 Basic controls
 Atomic components
 Used for showing ouput and/or getting some input
 Inherits JComponent
 Examples: JButton, JLabel, JTextArea, JTable, Jlist

 Usually every Swing class extends the corresponding AWT class


 For backward-compatibility reasons
My First Swing Program
import javax.swing.*;
import java.awt.BorderLayout;

public class First {


public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");

// operation to do when the window is closed.


frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
JFrame (top level container)
 javax.swing.JFrame:
 Top-level window with a title and a border.
 Usually used as a program's main window
 Can be made up of several layers
 Widgets are added to the Content Pane layer.
 Use getContentPane() to obtain it
 Other layers are used for customizing the window's appearance
Internal Containers
 Not Top level containers
 Can contain other non-top level components
 Examples:
– JScrollPane: Provides a scrollable view of its
components

– JSplitPane: Separates two components

– JTabbedPane: User chooses which


component to see
Layout
 Each container has a layout manager
 Determines the size, location of contained widgets.

 Setting the current layout of a container:


void setLayout(LayoutManager lm)

 LayoutManager implementing classes:


– BorderLayout
– BoxLayout
– FlowLayout
– GridLayout
Layouts
Swing Components
Swing Components
First Swing Program Revisited

import javax.swing.*; Create a frame


import java.awt.BorderLayout;

public class First {


public static void main(String[] args) {
JFrame frame = new JFrame("My First Frame");Choose the border
layout
// operation to do when the window is closed.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(new JLabel("I Love Swing"),
BorderLayout.CENTER);
frame.pack();
frame.setVisible(true); Create a text
} label
Specify CENTER Add the label to
}
as the layout the content pane
position 81
JButton
 The JButton class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed. It inherits
AbstractButton class.

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 addActionListener(ActionListener a) It is used to add the action listener to this object.


JLabel
 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.

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 alignment) It sets the alignment of the label's contents 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.
JTextField
 he object of a JTextField class is a text component that allows the editing of a single line
text.
 JTextField class declaration
 public class JTextField extends JTextComponent
JTextArea
 The object of a JTextArea class is a multi line region that displays text. It allows the editing
of multiple line text.

Methods Description

void setRows(int rows) It is used to set specified number of rows.

void setColumns(int cols) It is used to set specified number of


columns.
void setFont(Font f) It is used to set the specified font.
void insert(String s, int position) It is used to insert the specified text on the
specified position.
void append(String s) It is used to append the given text to the
end of the document.
JColorChooser
 The JColorChooser class is used to create a color chooser dialog box so that user can select
any color. It inherits JComponent class.

Constructor Description

JColorChooser() It is used to create a


color chooser panel
with white color
initially.
JColorChooser(color It is used to create a
initialcolor) color chooser panel Method Description
with the specified void It is used to add a
color initially. addChooserPanel(Abst color chooser panel to
ractColorChooserPanel the color chooser.
panel)
static Color It is used to show the
showDialog(Componen color chooser dialog
t c, String title, Color box.
initialColor)
JTable
 The JTable class is used to display data in tabular form. It is composed of rows and columns.

Constructor Description

JTable() Creates a table with empty cells.


JTable(Object[][] rows, Object[] columns) Creates a table with the specified data.

You might also like