0% found this document useful (0 votes)
0 views31 pages

OOPJ Module 5

Uploaded by

iamnarendra02
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)
0 views31 pages

OOPJ Module 5

Uploaded by

iamnarendra02
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

Jwaia uwow ij

Mohan Babu University

Department of Computer Science and Engineering


Department of Computer Science and Engineering
Subject Name: OBJECT ORIENTED PROGRAMMING Subject Code: CS T45
Subject Name: OBJECT ORIENTED PROGRAMMING IN JAVA Subject Code: 22AI104002

Prepared By :
Prepared By :
[Link], HOD /CSE
[Link] SELVA
[Link], RAJ, AP /CSE
AP/CSE

UNIT 5

GUI PROGRAMMING WITH APPLETS

APPLETS
Applets are small applications that are accessed on an Internet server, transported overthe Internet,
automatically installed, and run as part of a web document.
Applet is a special type of program that is embedded in the webpage to generate thedynamic content. It runs
inside the browser and works at client side.

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 plateforms, including Linux,Windows, Mac Os
etc.

Drawback of Applet

 Plugin is required at client browser to execute applet.

Hierarchy of Applet

John Selva Raj


Jwaia uwow ij

Mohan Babu University

As displayed in the above diagram, Applet class extends Panel. Panel class extendsContainer which is the
subclass of Component.

The Applet class is contained in the [Link] package. Applet contains several methods that give you
detailed control over the execution of your applet.
It is important to state at the outset that there are two varieties of Applets. The first are those based directly on
the Applet class, which uses the Abstract Window Toolkit (AWT) to provide the graphic user interface (or use no
GUI at all).The second type of applets are those based on the Swing class JApplet. Swing applets use the Swing
classes to provide the GUI.
All applets are subclasses (either directly or indirectly) of Applet. Applets are not stand- alone programs.
Instead, they run within either a web browser or an applet viewer.
Execution of an applet does not begin at main ( ). (Few applets even have main ( ) methods) Instead, execution
of an applet is started and controlled with an entirely different mechanism. Output to your applet’s window is
not performed by [Link]( ). Rather, in non-Swing applets, output is handled with various AWT
methods, such as drawString( ), which outputs a string to a specified X,Y location. Input is also handled
differently than in a console application.

Simple Example:

Applets differ from console-based applications in several key areas.

import [Link].*;
import [Link].*;
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link]("A Simple Applet", 20, 20);
}
}
This applet begins with two import statements. The first imports the Abstract Window Toolkit (AWT) classes.
Applets interact with the user (either directly or indirectly) through the AWT, not through the console-based I/O
classes. The AWT contains support for a window-based, graphical user interface. The second import statement
imports the applet package, which contains the class Applet. Every applet that you create must be a subclass of
Applet. The next line in the program declares the class SimpleApplet. This class must be declared as public,
because it will be accessed by code that is outside the program. Inside SimpleApplet, paint ( ) is declared. This
method is defined by the AWT and mustbe overridden by the applet. Paint ( ) is called each time that the applet
must redisplay its output. Paint ( ) is also called when the applet begins execution. The paint ( ) method has one
parameter of type Graphics. This parameter contains the graphics context, which describes the graphics
environment in which the applet is running. This context is used whenever output to the applet is required.
Inside paint ( ) is a call to drawString( ), which is a member of the Graphics class. This method outputs a
string beginning at the specified X,Y location. It has the following general form:
void drawString(String message, int x, int y) Here,
message is the string to be output beginning at x,y.
Notice that the applet does not have a main ( ) method. Unlike Java programs, applets do not begin execution at
main ( ). In fact, most applets don’t even have a main ( ) method. Instead, an applet begins execution when the
name of its class is passed to an applet viewer or to a network browser.
There are two ways in which you can run an applet:
 Executing the applet within a Java-compatible web browser.
 Using an applet viewer, such as the standard tool, appletviewer. An applet viewer executes your applet
in a window. This is generally the fastest and easiest way totest your applet.
To execute an applet in a web browser, you need to write a short HTML text file that contains a tag that loads the
applet. Currently, Sun recommends using the APPLET tag for this purpose. Here is the HTML file that executes
SimpleApplet:
<applet code="SimpleApplet" width=200 height=60>
</applet>
The width and height statements specify the dimensions of the display area used by the applet. After you create
this file, you can execute your browser and then load this file, whichcauses SimpleApplet to be executed.

John Selva Raj


Jwaia uwow ij

Mohan Babu University


To execute SimpleApplet with an applet viewer, you may also execute the HTML file shown earlier. For example,
if the preceding HTML file is called [Link], then the following command line will run SimpleApplet:
C:\>appletviewer [Link]
However, a more convenient method exists that you can use to speed up testing. Simply include a comment at
the head of your Java source code file that contains the APPLET tag. By doing so, your code is documented with a
prototype of the necessary HTML statements, and you can test your compiled applet merely by starting the
applet viewer with your Java source code file. If you use this method, the SimpleApplet source file looks like this:
import [Link].*;
import [Link].*;
/*
<applet code="SimpleApplet" width=200 height=60>
</applet>
*/
public class SimpleApplet extends Applet {
public void paint(Graphics g) {
[Link]("A Simple Applet", 20, 20);
}
}
With this approach, you can quickly iterate through applet development by using thesethree steps:
1. Edit a Java source file.
2. Compile your program.
3. Execute the applet viewer, specifying the name of your applet’s source file. The applet
viewer will encounter the APPLET tag within the comment and execute your applet.
c:\>javac [Link]
c:\>appletviewer [Link]

Key Points:
 Applets do not need a main ( ) method.
 Applets must be run under an applet viewer or a Java-compatible browser.
 User I/O is not accomplished with Java’s stream I/O classes. Instead, applets use the
interface provided by the AWT or Swing.

The Applet class defines the methods. Applet provides all necessary support for applet execution, such as
starting and stopping. It also provides methods that load and display images, and methods that load and play
audio clips.

Method Description
void destroy( ) Called by the browser just before an applet is terminated. Your applet
will override this method if it needs to perform any cleanup prior to
its destruction.
AccessibleContext getAccessibleContext( ) Returns the accessibility context for the invoking object.
AppletContext getAppletContext( ) Returns the context associated with the applet.
String getAppletInfo( ) Returns a string that describes the applet.
AudioClip getAudioClip(URL url) Returns an AudioClip object that encapsulates the audio clip found at
the location specified by url.
AudioClip getAudioClip(URL url, String clipName) Returns an AudioClip object that encapsulates the audio clip found at
the location specified by url and having the name specified by
clipName.
URL getCodeBase( ) Returns the URL associated with the invoking applet.

URL getDocumentBase( ) Returns the URL of the HTML document that invokes
the applet.

John Selva Raj


Jwaia uwow ij

Mohan Babu University

Image getImage(URL url) Returns an Image object that encapsulates the image found at the
location specified by url.
Image getImage(URL url, String imageName) Returns an Image object that encapsulates the image found at the
location specified by url and having the name specified by
imageName.
String getParameter(String paramName) Returns the parameter associated with paramName. null is returned
if the specified parameter is not found.
String[ ] [ ] getParameterInfo( ) Returns a String table that describes the parameters recognized by
the applet. Each entry in the table must consist of three strings that
contain the name of the parameter, a description of its type and/or
range, and an explanation of its purpose.
void init() Called when an applet begins execution. It is the first method called
for any applet.
boolean isActive( ) Returns true if the applet has been started. It returns false if the
applet has been stopped.
void play(URL url) If an audio clip is found at the location specified by url, the clip is
played.
void play(URL url, String clipName) If an audio clip is found at the location specified by url with the name
specified by clipName, the clip is played.
void resize(Dimension dim) Resizes the applet according to the dimensions specified by dim.
Dimension is a class stored inside [Link]. It contains two integer
fields: width and height.
void resize(int width, int height) Resizes the applet according to the dimensions specified by width
and height.
void showStatus(String str) Displays str in the status window of the browser or applet viewer. If
the browser does not support a status window, then no action takes
place.
void start( ) Called by the browser when an applet should start (or resume)
execution. It is automatically called after init( ) when an applet first
begins.
void stop( ) Called by the browser to suspend execution of the applet. Once
stopped, an applet is restarted when the browser calls start( ).

Lifecycle methods for Applet:

The [Link] class 4 life cycle methods and [Link] class provides 1life cycle methods for
an applet.

Applet Initialization and Termination

It is important to understand the order in which the various methods shown in the skeletonare called. When an
applet begins, the following methods are called, in this sequence:
1. init( )
2. start( )
3. paint( )
When an applet is terminated, the following sequence of method calls takes place:
1. stop( )
2. destroy( )
init( ) : The init( ) method is the first method to be called. This is where you shouldinitialize variables.
This method is called only once during the run time of your applet.

start( ): The start( ) method is called after init( ). It is also called to restart an appletafter it has been
stopped. Whereas init( ) is called once—the first time an applet isloaded—start( ) is called each time an
applet’s HTML document is displayed onscreen. So,if a user leaves a web page and comes back, the applet
resumes execution at start( ). paint( ): The paint( ) method is called each time your applet’s output must be
[Link] situation can occur for several reasons. For example, the window in which the applet isrunning
may be overwritten by another window and then uncovered. Or the applet windowmay be minimized and
then restored. paint( ) is also called when the applet beginsexecution. Whatever the cause, whenever the
applet must redraw its output, paint( ) iscalled. The paint( ) method has one parameter of type Graphics. This
parameter willcontain the graphics context, which describes the graphics environment in which the appletis
running. This context is used whenever output to the applet is required.

John Selva Raj


Jwaia uwow ij

Mohan Babu University

stop( ): The stop( ) method is called when a web browser leaves the HTML document containing the applet—
when it goes to another page, for example. When stop( ) is called, the applet is probably running. You should
use stop( ) to suspend threads that don’t need to run when the applet is not visible. You can restart them when
start( ) is called if the user returns to the page.
destroy( ): The destroy( ) method is called when the environment determines that your applet needs to be
removed completely from memory. At this point, you should free up any resources the applet may be using. The
stop( ) method is always called before destroy( ).

Displaying Graphics in Applet

[Link] class provides many methods for graphics programming.


Commonly used methods of Graphics class:
1. public abstract void drawString(String str, int x, int y): is used to draw thespecified string.
2. public void drawRect(int x, int y, int width, int height): draws a rectangle withthe specified width
and height.
3. public abstract void fillRect(int x, int y, int width, int height): is used to fillrectangle with the
default color and specified width and height.
4. public abstract void drawOval(int x, int y, int width, int height): is used todraw oval with the
specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is used to filloval with the default
color and specified width and height.
6. public abstract void drawLine(int x1, int y1, int x2, int y2): is used to drawline between the
points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y, ImageObserverobserver): is used
draw the specified image.
8. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle): is used
draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, int startAngle,int arcAngle): is used
to fill a circular or elliptical arc.
10. public abstract void setColor(Color c): is used to set the graphics current color tothe specified color.
11. public abstract void setFont(Font font): is used to set the graphics current fontto the specified font.

Example of Graphics in applet:

import [Link];
import [Link].*;

public class GraphicsDemo extends Applet{


public void paint(Graphics g){
[Link]([Link]);
[Link]("Welcome",50, 50);
[Link](20,30,20,300);
[Link](70,100,30,30);
[Link](170,100,30,30);
[Link](70,200,30,30);

[Link]([Link]); [Link](170,200,30,30);
[Link](90,150,30,30,30,270);
[Link](270,150,30,30,0,180);
}
}

[Link]

<html>
<body>
<applet code="[Link]" width="300" height="300">
</applet>
</body>
</html>

John Selva Raj


Jwaia uwow ij

Mohan Babu University

To set the background color of an applet’s window, use setBackground( ). To set the foreground color use
setForeground( ). These methods are defined by Component, and they have the following general forms:
void setBackground(Color newColor) void
setForeground(Color newColor)
Ex:
setBackground([Link]);
setForeground([Link]);

Delegation Event Model in Java


The Delegation Event model is defined to handle events in GUI programming languages. The GUI stands for
Graphical User Interface, where a user graphically/visually interacts with the system.

The GUI programming is inherently event-driven; whenever a user initiates an activity such as a mouse
activity, clicks, scrolling, etc., each is known as an event that is mapped to a code to respond to functionality
to the user. This is known as event handling.

In this section, we will discuss event processing and how to implement the delegation event model in Java.
We will also discuss the different components of an Event Model.

Event Processing in Java

Java support event processing since Java 1.0. It provides support for AWT ( Abstract Window Toolkit), which
is an API used to develop the Desktop application. In Java 1.0, the AWT was based on inheritance. To catch
and process GUI events for a program, it should hold subclass GUI components and override action() or
handleEvent() methods. The below image demonstrates the event processing.

Basically, an Event Model is based on the following three components:

o Events
o Events Sources
o Events Listeners

John Selva Raj


Jwaia uwow ij

Mohan Babu University

Events

The Events are the objects that define state change in a source. An event can be generated as a reaction of a
user while interacting with GUI elements. Some of the event generation activities are moving the mouse
pointer, clicking on a button, pressing the keyboard key, selecting an item from the list, and so on. We can
also consider many other user operations as events.

The Events may also occur that may be not related to user interaction, such as a timer expires, counter
exceeded, system failures, or a task is completed, etc. We can define events for any of the applied actions.

Event Sources

A source is an object that causes and generates an event. It generates an event when the internal state of the
object is changed. The sources are allowed to generate several different types of events.

A source must register a listener to receive notifications for a specific event. Each event contains its
registration method. Below is an example:

1. public void addTypeListener (TypeListener e1)

From the above syntax, the Type is the name of the event, and e1 is a reference to the event listener. For
example, for a keyboard event listener, the method will be called as addKeyListener(). For the mouse event
listener, the method will be called as addMouseMotionListener(). When an event is triggered using the
respected source, all the events will be notified to registered listeners and receive the event object. This
process is known as event multicasting. In few cases, the event notification will only be sent to listeners that
register to receive them.

Some listeners allow only one listener to register. Below is an example:

1. public void addTypeListener(TypeListener e2) throws [Link]

From the above syntax, the Type is the name of the event, and e2 is the event listener's reference. When the
specified event occurs, it will be notified to the registered listener. This process is known
as unicasting events.

A source should contain a method that unregisters a specific type of event from the listener if not needed.
Below is an example of the method that will remove the event from the listener.

public void removeTypeListener(TypeListener e2?)

From the above syntax, the Type is an event name, and e2 is the reference of the listener. For example, to remove the
keyboard listener, the removeKeyListener() method will be called.

The source provides the methods to add or remove listeners that generate the events. For example, the Component class
contains the methods to operate on the different types of events, such as adding or removing them from the listener.

Event Listeners
An event listener is an object that is invoked when an event triggers. The listeners require two things; first, it
must be registered with a source; however, it can be registered with several resources to receive notification
about the events. Second, it must implement the methods to receive and process the received notifications.

John Selva Raj


Jwaia uwow ij

Mohan Babu University

The methods that deal with the events are defined in a set of interfaces. These interfaces can be found in the
[Link] package.

For example, the MouseMotionListener interface provides two methods when the mouse is dragged and
moved. Any object can receive and process these events if it implements the MouseMotionListener interface.

The Delegation Model


The Delegation Model is available in Java since Java 1.1. it provides a new delegation-based event model
using AWT to resolve the event problems. It provides a convenient mechanism to support complex Java
programs.

Design Goals
The design goals of the event delegation model are as following:

o It is easy to learn and implement


o It supports a clean separation between application and GUI code.
o It provides robust event handling program code which is less error-prone (strong compile-time checking)
o It is Flexible, can enable different types of application models for event flow and propagation.
o It enables run-time discovery of both the component-generated events as well as observable events.
o It provides support for the backward binary compatibility with the previous model.

Event and Listener (Java Event Handling)

Changing the state of an object is known as an event. For example, click on button, dragging mouse etc. The
[Link] package provides many event classes and Listener interfaces for event handling.

Event classes and Listener interfaces:

Event Classes Listener Interfaces


ActionEvent ActionListener

MouseEvent MouseListener and MouseMotionListener

MouseWheelEvent MouseWheelListener

KeyEvent KeyListener

ItemEvent ItemListener

TextEvent TextListener

AdjustmentEvent AdjustmentListener

John Selva Raj


Jwaia uwow ij

Mohan Babu University

WindowEvent WindowListener

ComponentEvent ComponentListener

ContainerEvent ContainerListener

FocusEvent FocusListener

Steps to perform Event Handling

Following steps are required to perform event handling:

1. Implement the Listener interface and overrides its methods


2. Register the component with the Listener

For registering the component with the Listener, many classes provide the registrationmethods. For
example:

o Button
o public void addActionListener(ActionListener a){}
o MenuItem
o public void addActionListener(ActionListener a){}
o TextField
o public void addActionListener(ActionListener a){}
o public void addTextListener(TextListener a){}
o TextArea
o public void addTextListener(TextListener a){}
o Checkbox
o public void addItemListener(ItemListener a){}
o Choice
o public void addItemListener(ItemListener a){}
o List
o public void addActionListener(ActionListener a){}
o public void addItemListener(ItemListener a){}

EventHandling Codes:

We can put the event handling code into one of the following places:
1. Same class
2. Other class
3. Annonymous class

Java event handling by implementing ActionListener


import [Link].*;
import [Link].*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){

//create components
tf=new TextField();
[Link](60,50,170,20);

John Selva Raj


Jwaia uwow ij

Mohan Babu University

Button b=new Button("click me");


[Link](100,120,80,30);

//register listener
[Link](this);//passing current instance

//add components and set size, layout and visibility


add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
[Link]("Welcome");
}
public static void main(String args[]){
new AEvent();
}
}
public void setBounds(int xaxis, int yaxis, int width, int height); have been used in the above example
that sets the position of the component it may be button, textfield etc.

Java MouseListener Interface


The Java MouseListener is notified whenever you change the state of mouse. It is notified against
MouseEvent. The MouseListener interface is found in [Link] package. It has five methods.

Methods of MouseListener interface


The signature of 5 methods found in MouseListener interface are given below:

1. public abstract void mouseClicked(MouseEvent e);


2. public abstract void mouseEntered(MouseEvent e);
3. public abstract void mouseExited(MouseEvent e);

John Selva Raj


Jwaia uwow ij

Mohan Babu University

4. public abstract void mousePressed(MouseEvent e);


5. public abstract void mouseReleased(MouseEvent e);

Java MouseListener Example


import [Link].*;
import [Link].*;
public class MouseListenerExample extends Frame implements MouseListener{
Label l;
MouseListenerExample(){
addMouseListener(this);

l=new Label();
[Link](20,50,100,20);
add(l);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void mouseClicked(MouseEvent e) {
[Link]("Mouse Clicked");
}
public void mouseEntered(MouseEvent e) {
[Link]("Mouse Entered");
}
public void mouseExited(MouseEvent e) {
[Link]("Mouse Exited");
}
public void mousePressed(MouseEvent e) {
[Link]("Mouse Pressed");
}
public void mouseReleased(MouseEvent e) {
[Link]("Mouse Released");
}
public static void main(String[] args) {
new MouseListenerExample();
}
}

Output:

John Selva Raj


Jwaia uwow ij

Mohan Babu University

Java KeyListener Interface


The Java KeyListener is notified whenever you change the state of key. It is notified against KeyEvent.
The KeyListener interface is found in [Link] package, and it has three methods.

Interface declaration
Following is the declaration for [Link] interface:

1. public interface KeyListener extends EventListener

Methods of KeyListener interface


The signature of 3 methods found in KeyListener interface are given below:

Sr. no. Method name Description

1. public abstract void keyPressed (KeyEvent e); It is invoked when a key has been pressed.

2. public abstract void keyReleased (KeyEvent e); It is invoked when a key has been released.

3. public abstract void keyTyped (KeyEvent e); It is invoked when a key has been typed.

Java KeyListener Example


In the following example, we are implementing the methods of the KeyListener interface.

[Link]

// importing awt libraries


import [Link].*;
import [Link].*;
// class which inherits Frame class and implements KeyListener interface
public class KeyListenerExample extends Frame implements KeyListener {
// creating object of Label class and TextArea class
Label l;
TextArea area;
// class constructor
KeyListenerExample() {
// creating the label
l = new Label();
// setting the location of the label in frame
[Link] (20, 50, 100, 20);
// creating the text area
area = new TextArea();
// setting the location of text area
[Link] (20, 80, 300, 300);
// adding the KeyListener to the text area
[Link](this);
// adding the label and text area to the frame
add(l);
add(area);
// setting the size, layout and visibility of frame
John Selva Raj
Jwaia uwow ij

Mohan Babu University

setSize (400, 400);


setLayout (null);
setVisible (true);
}
// overriding the keyPressed() method of KeyListener interface where we set the text of the label when k
ey is pressed
public void keyPressed (KeyEvent e) {
[Link] ("Key Pressed");
}
// overriding the keyReleased() method of KeyListener interface where we set the text of the label when
key is released
public void keyReleased (KeyEvent e) {
[Link] ("Key Released");
}
// overriding the keyTyped() method of KeyListener interface where we set the text of the label when a k
ey is typed
public void keyTyped (KeyEvent e) {
[Link] ("Key Typed");
}
// main method
public static void main(String[] args) {
new KeyListenerExample();
} }

Output:

John Selva Raj


Jwaia uwow ij

Mohan Babu University

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.

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

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

The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.

Difference between AWT and Swing


There are many differences between java awt and swing that are given below.
No. Java AWT Java Swing
1) AWT components are platform- Java swing components are platform-
dependent. independent.

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

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

4) AWT provides less Swing provides more powerful

John Selva Raj


Mohan Babu University

components than Swing. components such as tables, lists, scrollpanes,


colorchooser, tabbedpane etc.

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


Controller) where model represents data,
view represents presentation and controller
acts as an

interface between model and view.

MVC ARCHITECTURE:
The model is the piece that represents the state and low-level behavior of the component. It
manages the state and conducts all transformations on that state. The model has no specific
knowledge of either its controllers or its views. The system itself maintains links between
model and views and notifies the views when the model changes state.

The view is the piece that manages the visual display of the state represented by the model. A
model can have more than one view, but that is typically not the case in the Swing set.

The controller is the piece that manages user interaction with the model. It provides the
mechanism by which changes are made to the state of the model.

Using the keyboard key example, the model corresponds to the key's mechanism, and the
view and controller correspond to the key's façade.

The following figure illustrates how to break a JFC user interface component into a model,
view, and controller. Note that the view and controller are combined into one piece, a
common adaptation of the basic MVC pattern. They form the user interface for the
component

John Selva Raj


Mohan Babu University

Hierarchy of Java Swing classes


The hierarchy of java swing API is given below.

John Selva Raj


Mohan Babu University

Commonly used Methods of Component class


The methods of Component class are widely used in java swing that are given below.
Method Description
public void add(Component c) add a component on another component.

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

public void setLayout(LayoutManagerm) sets the layout manager for the component.

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


false.

CONTAINERS:
Containers are an integral part of SWING GUI components. A container provides a space
where a component can be located. A Container in AWT is a component itself and it
provides the capability to add a component to itself. Following are certain noticable points to
be considered.

 Sub classes of Container are called as Container. For example, JPanel, JFrame and
JWindow.

 Container can add only a Component to itself.

 A default layout is present in each container which can be overridden


using setLayout method.

SWING Containers
Following is the list of commonly used containers while designed GUI using SWING.

[Link]. Container & Description

Panel
1

JPanel is the simplest container. It provides space in which any other

John Selva Raj


component can be placed, including other panels.

Frame
2
A JFrame is a top-level window with a title and a border.

Window
3
A JWindow object is a top-level window with no borders and no menubar.

SWING COMPONENTS:
Java 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.

JButton class declaration

Let's see the declaration for [Link] class.

1. public class JButton extends AbstractButton implements Accessible

Commonly used Constructors:

Constructor Description

JButton() It creates a button with no text and icon.

JButton(String s) It creates a button with the specified text.

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

Commonly used Methods of 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.

Java JButton Example


1. import [Link].*;
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. [Link](50,100,95,30);
7. [Link](b);
8. [Link](400,400);
9. [Link](null);
10. [Link](true);
11. }
12. }

Java JCheckBox
The JCheckBox class is used to create a checkbox. It is used to turn an option on (true) or off (false).
Clicking on a CheckBox changes its state from "on" to "off" or from "off" to "on ".It inherits JToggleButton
class.

JCheckBox class declaration


Let's see the declaration for [Link] class.

1. public class JCheckBox extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description
JJCheckBox() Creates an initially unselected check box button with no text, no

icon.

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

JCheckBox(String text, Creates a check box with text and specifies whether or not it is
boolean selected)
initially selected.

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

supplied.

Commonly used Methods:


Methods Description

AccessibleContext getAccessibleContext() It is used to get the AccessibleContext

associated with this JCheckBox.

protected String paramString() It returns a string representation of

this JCheckBox.

Java JCheckBox Example


1. import [Link].*;
2. public class CheckBoxExample
3. {
4. CheckBoxExample(){
5. JFrame f= new JFrame("CheckBox Example");
6. JCheckBox checkBox1 = new JCheckBox("C++");
7. [Link](100,100, 50,50);
8. JCheckBox checkBox2 = new JCheckBox("Java", true);9.
[Link](100,150, 50,50);
10. [Link](checkBox1);
11. [Link](checkBox2);
12. [Link](400,400);
13. [Link](null);
14. [Link](true);
15. }
16. public static void main(String args[])
17. {
18. new CheckBoxExample();
19. }}

Java JRadioButton
The JRadioButton class is used to create a radio button. It is used to choose one optionfrom multiple options.
It is widely used in exam systems or quiz.

It should be added in ButtonGroup to select one radio button only.

JRadioButton class declaration


Let's see the declaration for [Link] class.

1. public class JRadioButton extends JToggleButton implements Accessible

Commonly used Constructors:

Constructor Description

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

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

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

Commonly used Methods:


Methods Description

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

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

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

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

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

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

void addActionListener(ActionListenera) It is used to add the action listener to this object.

Java JRadioButton Example


1. import [Link].*;
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.
[Link](75,50,100,30);
9. [Link](75,100,100,30);
10. ButtonGroup bg=new ButtonGroup();
11. [Link](r1);[Link](r2);
12. [Link](r1);[Link](r2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. public static void main(String[] args) {
18. new RadioButtonExample();
19. }
20. }
Java 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. It inherits
JComponent class.

JLabel class declaration


Let's see the declaration for [Link] class.

1. public class JLabel extends JComponent implements SwingConstants, Accessible

Commonly used Constructors:

Constructor Description

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

string for the title.

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

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

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

Commonly used Methods:


Methods Description

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

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

void setHorizontalAlignment(int It sets the alignment of the label's contents along the X axis.
alignment)
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.

Java JLabel Example


1. import [Link].*;
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. [Link](50,50, 100,30);
10. l2=new JLabel("Second Label.");
11. [Link](50,100, 100,30);
12. [Link](l1); [Link](l2);
13. [Link](300,300);
14. [Link](null);
15. [Link](true);
16. }
17. }

Java JTextField

The object of a JTextField class is a text component that allows the editing of a singleline text. It inherits
JTextComponent class.

JTextField class declaration

Let's see the declaration for [Link] class.

1. public class JTextField extends JTextComponent implements SwingConstants

Commonly used Constructors:

Constructor Description
JTextField() Creates a new TextField

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

JTextField(String text, Creates a new TextField initialized with the specified text and
int columns)
columns.

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

columns.

Commonly used Methods:


Methods Description

void addActionListener(ActionListene It is used to add the specified action listener to receiveaction


r l)
events from this textfield.

Action getAction() It returns the currently set Action for this ActionEvent

source, or null if no Action is set.

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

void removeActionListener(ActionLis It is used to remove the specified action listener so thatit no


tener l)
longer receives action events from this textfield.

Java JTextField Example


1. import [Link].*;
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 Javatpoint.");
9. [Link](50,100, 200,30);
10. t2=new JTextField("AWT Tutorial");
11. [Link](50,150, 200,30);
12. [Link](t1); [Link](t2);
13. [Link](400,400);
14. [Link](null);
15. [Link](true);
16. }
17. }

Java JTextArea

The object of a JTextArea class is a multi line region that displays text. It allows theediting of multiple
line text. It inherits JTextComponent class

JTextArea class declaration

Let's see the declaration for [Link] class.

1. public class JTextArea extends JTextComponent

Commonly used Constructors:

Constructor Description

JTextArea() Creates a text area that displays no text initially.

JTextArea(String s) Creates a text area that displays specified text initially.

JTextArea(int row, Creates a text area with the specified number of rows
int column)
and columns that displays no text initially.

JTextArea(String s,int Creates a text area with the specified number of rows
row, int column)
and columns that displays specified text.
Commonly used Methods:

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.

Java JTextArea Example


1. import [Link].*;
2. public class TextAreaExample3.
{
4. TextAreaExample(){
5. JFrame f= new JFrame();
6. JTextArea area=new JTextArea("Welcome to javatpoint");7.
[Link](10,30, 200,200);
8. [Link](area);
9. [Link](300,300);
10. [Link](null);
11. [Link](true);
12. }
13. public static void main(String args[])
14. {
15. new TextAreaExample();16.
}}
Java JList
The object of JList class represents a list of text items. The list of text items can be setup so that the user
can choose either one item or multiple items. It inherits JComponent class.

JList class declaration


Let's see the declaration for [Link] class.

1. public class JList extends JComponent implements Scrollable, Accessible

Commonly used Constructors:


Constructor Description

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

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

JList(ListModel<ary> Creates a JList that displays elements from the specified, non-null,
dataModel)
model.

Commonly used Methods:


Methods Description

Void addListSelectionListener(ListSelecti It is used to add a listener to the list, to be notifiedeach time


onListener listener)
a change to the selection occurs.

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

ListModel getModel() It is used to return the data model that holds a list of

items displayed by the JList component.

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

array of objects.
Java JList Example
1. import [Link].*;
2. public class ListExample
3. {
4. ListExample(){
5. JFrame f= new JFrame();
6. DefaultListModel<String> l1 = new DefaultListModel<>();
7. [Link]("Item1");
8. [Link]("Item2");
9. [Link]("Item3");
10. [Link]("Item4");
11. JList<String> list = new JList<>(l1);
12. [Link](100,100, 75,75);
13. [Link](list);
14. [Link](400,400);
15. [Link](null);
16. [Link](true);
17. }
18. public static void main(String args[])
19. {
20. new ListExample();
21. }}

Java JComboBox

The object of Choice class is used to show popup menu of choices. Choice selected byuser is shown on
the top of a menu. It inherits JComponent class.

JComboBox class declaration

Let's see the declaration for [Link] class.

1. public class JComboBox extends JComponent implements ItemSelectable, ListDataListener,


ActionListener, Accessible

Commonly used Constructors:

Constructor Description
Mohan Babu University

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

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

the specified array.

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

the specified Vector.

Commonly used Methods:

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

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

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

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

is editable.

void addActionListener(ActionListener It is used to add the ActionListener.


a)

void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example


1. import [Link].*;
2. public class ComboBoxExample {
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. [Link](50, 50,90,20);
9. [Link](cb);
10. [Link](null);
11. [Link](400,500);
12. [Link](true);
13. }
14. public static void main(String[] args) {
15. new ComboBoxExample();
16. } }
John Selva Raj
Mohan Babu University

John Selva Raj

You might also like