[go: up one dir, main page]

0% found this document useful (0 votes)
11 views59 pages

Unit 2

The document provides an overview of applet fundamentals in Java, detailing the Applet class, its lifecycle, and methods for creating and running applets. It explains the differences between AWT and Swing applets, the lifecycle methods of an applet, and how to pass parameters to applets. Additionally, it includes examples of applet code and instructions for running applets using HTML and the applet viewer tool.

Uploaded by

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

Unit 2

The document provides an overview of applet fundamentals in Java, detailing the Applet class, its lifecycle, and methods for creating and running applets. It explains the differences between AWT and Swing applets, the lifecycle methods of an applet, and how to pass parameters to applets. Additionally, it includes examples of applet code and instructions for running applets using HTML and the applet viewer tool.

Uploaded by

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

UNIT-II

2.1 APPLET FUNDAMENTALS


The Applet class is contained in the java.applet
package.Appletcontains several methods that give you detailed control over
the execution of your applet. In addition,java.appletalso defines three
interfaces:AppletContext,AudioClip, and
AppletStub .
Two Types of Applets

It is important to state at the outset that there are two varieties of


applets. The first are those based directly on the Appletclass described in
this chapter. These applets use the Abstract Window Toolkit (AWT) to provide
the graphic user interface (or use no GUI at all). This style of applet has been
available since Java was first created.
The second type of applets are those based on the Swing class
JApplet . Swing applets use the Swing classes to provide the GUI. Swing
offers a richer and often easier-to-use user interface than does the AWT.
Thus, Swing-based applets are now the most popular. However, traditional
AWT-based applets are still used, especially when only a very simple user
interface is required. Thus, both AWT- and Swing-based applets are valid.
Because JApplet inherits Applet, all the features of Applet are also available
in JApplet ,and most of the information in this chapter applies to both types
of applets. Therefore, even if you are interested in only Swing applets, the
information in this chapter is still relevant and necessary. Understand,
however, that when creating Swing-based applets, some additional
constraints apply and these are described later in this book, when Swing is
covered.
Applet Basics

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. The illustrations shown in this chapter were
created with the standard applet viewer, called appletviewer , provided by
the JDK. But you can use any applet viewer or browser you like. Execution of
an applet does not begin at main( ) . Actually, few applets even have main( )
methods. Instead, execution of an applet is started and controlled with an
entirely different mechanism, which will be explained shortly. Output to your
applet’s window is not performed by System.out.println( ) . 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. To use
an applet, it is specified in an HTML file. One way to do this is by using the
APPLETtag. (The OBJECT tag can also be used, but Sun currently
recommends the APPLET tag and this is the tag used by examples in this
book.) The applet will be executed by a Java-enabled web browser when it
encounters the APPLET tag within the HTML file. To view and test an applet
more conveniently, simply include a comment at the head of your Java
source code file that contains the APPLET tag. This way, your code is
documented with the necessary HTML statements needed by your applet,
and you can test the compiled applet by starting the applet viewer with your
Java source code file specified as the target. Here is an example of such a
comment:
/*
<applet code="MyApplet" width=200 height=60>
</applet>
*/
This comment contains an APPLET tag that will run an applet called
MyApplet in a window that is 200 pixels wide and 60 pixels high. Because the
inclusion of an APPLET command makes testing applets easier, all of the
applets shown in this book will contain the appropriate APPLET tag
embedded in a comment.
2.2 THE APPLET CLASS
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. Applet extends the AWT class
Panel . In turn, Panel extends Container , which extends Component . These
classes provide support for Java’s window-based, graphical interface. Thus,
Applet provides all of the necessary support for window-based activities.
Called by the browser just before an applet is
terminated. Your applet will override this method if
void destroy( )
it needs to per form 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
Returns an AudioClip object that encapsulates the
url
audio clip found at the location specified by url
)
audioClip AudioClip object that encapsulates the audio clip
getAudioClip(URL found at the location specified by url and having the
name specified by clipName.
url , String clipName )

Returns the URL associated with the invoking


applet.
Returns the URL of the HTML document that invokes
the applet.
Returns an
Returns an
URL getCodeBase( )
Image
object that encapsulates the image found at the
URL
location specified by url. Image getImage(URL
getDocumentBase( )
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.
Returns a Locale object that is used by various
Locale getLocale( )
locale-
sensitive classes and methods
String
Returns the parameter associated with paramName.
getParameter(String
Null is returned if the specified parameter is not
paramName
found
)
String[ ] [ ] Returns a String table that describes the
getParameterInfo( ) parameters
recognized by the applet. Each entr y 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.

Called when an applet begins execution. It is the


void init( )
first
method called for any applet
Returns true if the applet has been started. It
boolean isActive( ) returns
false

the applet has been


if Returns an AudioClip object that encapsulates the
stopped.
audio clip found at the location specified by
static final AudioClip
url. This method is similar to getAudioClip( )
newAudioClip(URL
except that it is static and can be executed without
url
the need for an Applet object.
)

void play(URL
url
If an audio clip is found at the location specified by
, String
url with the name specified by clipName,
clipName
the clip is played
)

void resize(Dimension Resizes the applet according to the dimensions


dim specified
) By dim.Dimension is a class stored inside java.awt
.It contains two integer fields: width and height

void resize(int
width
, int Resizes the applet according to the dimensions
height specified by width and height
)

Makes stubObj the stub for the applet. This method


is
final void
used by the run-time system and is not usually
setStub(AppletStub
called by
stubObj
your applet. A stub
)
is a small piece of code that provides
the linkage between your applet and the browser.

2.3 APPLET LIFECYCLE


 Applet is initialized.

 Applet is started.

 Applet is painted.

 Applet is stopped.

 Applet is destroyed.
Lifecycle methods for Applet:

The java.applet.Applet class 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

The Component class provides 1 life cycle method of applet.


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.

how to run an Applet?


There are two ways to run an applet

 By html file.
 By appletViewer tool (for testing purpose).
Simple example of Applet by html file:

To execute the applet by html file, create an applet and compile it. After
that create an html file and place the applet code in html file. Now click the
html file.
//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:
To execute the applet by appletviewer tool, create an applet that contains
applet tag in comment and compile it. After that run it by: appletviewer
First.java. Now Html file is not required but it is for testing purpose only.
//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>

*/
To execute the applet by appletviewer tool, write in command prompt:
c:\>javac First.java
c:\>appletviewer First.java

2.4 STEPS FOR DEVELOPING APPLET PROGRAMS


An applet is a Java program that runs in a Java-compatible browser
such as Internetexplorer. This feature allows users to display graphics and to
run programs over the Internet. An applet allows web documents to be both
animated and interactive.
Step 1: Import applet package and awt package: To create an applet,
our program must import the Applet class. This class is found in the
java.applet package. The Applet class contains code that works with a
browser to create a display area. We also need to import the java.awt
package. "awt” stands for “Abstract Window Toolkit”. The java.awt package
includes classes like Graphics.
Step 2: Extend the Applet class: Then, a class must be defined that
inherits from the class ‘Applet’. It contains the methods to paint the screen.
The inherited class must be declared public.
Step 3: Override the paint method to draw text or graphics: The paint
method needs the Graphics object as its parameter.
public void paint(Graphics g) { … }
The Graphics class object holds information about painting. We can invoke
methods like drawLine(), drawCircle() and etc using this object.
Syntax: The program looks something like this.
import java.applet.*;
import java.awt.*;
public class MyApplet extends Applet
{
public void paint(Graphics g)
{
g.drawString("Welcome to Apoorva”,50,50);
}}
Step 4: Compiling the Program: After writing the program, we compile it
using the command "javac MyApplet.java". This command will compile our
code so that we now have MyApplet.class file.
Step 5: Adding applet to HTML document: To run the applet we need to
create the HTML document. The BODY section of the HTML document allows
APPLET tag. The HTML file looks something like this:
<HTML>
<BODY>
<APPLET codebase="MyAppPath" code="MyApp.class" width=200
height=200> </APPLET>
</BODY>
</HTML>
Step 6: Running an applet: The applet can be run in two ways
1. Using appletviewer: To run the appletviewer, type appletviewer
filename.html
2. Using web browser: Open the web browser, type in the full address of
html file

2.5 PASSING VALUES THROUGH PARAMETERS


Steps to accomplish this task -:
 To pass the parameters to the Applet we need to use the param
attribute of <applet> tag.
 To retrieve a parameter's value, we need to use the getParameter()
method of Applet class.
Signature of the getParamter() method

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.
Passing parameters to an applet.

In the upcoming code, 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.
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet8" width="400" height="200">
<param name="Name" value="Roger">
<param name="Age" value="26">
<param name="Sport" value="Tennis">
<param name="Food" value="Pasta">
<param name="Fruit" value="Apple">
<param name="Destination" value="California">
</applet>
*/
public class Applet8 extends Applet
{
String name;
String age;
String sport;
String food;
String fruit;
String destination;
public void init()
{
name = getParameter("Name");
age = getParameter("Age");
food = getParameter("Food");
fruit = getParameter("Fruit");
destination = getParameter("Destination");
sport = getParameter("Sport");
}
public void paint(Graphics g)
{
g.drawString("Reading parameters passed to this applet -", 20, 20);
g.drawString("Name -" + name, 20, 40);
g.drawString("Age -" + age, 20, 60);
g.drawString("Favorite fruit -" + fruit, 20, 80);
g.drawString("Favorite food -" + food, 20, 100);
g.drawString("Favorite destination -" + name, 20, 120);
g.drawString("Favorite sport -" + sport, 20, 140);
} }
In order to run our applet using the appletviewer, type the following
command at the command prompt-
appletviewer Applet8.java
Where Applet8.java is the name of java file that contains the code of
an applet. Right after running the applet program using appletviewer a new
applet window is displayed to us
Output

Passing a parameter to an applet to set a message on its status bar.

In the upcoming code, 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.
import java.awt.*;
import java.applet.*;
/*
<applet code="Applet11" width="400" height="300">
<param name="StatusBar" value="Have a good day">

*/
public class Applet11 extends Applet
{
String statusBar;
public void init()
{
statusBar= getParameter("StatusBar");
}
public void paint(Graphics g)
{
g.drawString("Reading the applet parameter to set status bar message - ",
20, 20);
//Setting a message at the status bar of our applet.
showStatus(statusBar);
g.drawString("Setting the status bar message -" + statusBar, 20, 100);
}
}
In order to run our applet using appletviewer, type the following command
at the command prompt-
appletviewer Applet11.java
Where Applet11.java is the name of java file that contains the code of
an applet. We have passed a parameter to an applet, named
StatusBar with the value Have a good day.

2.6 GRAPHICS IN APPLET


java.awt.Graphics class provides many methods for graphics
programming.
Commonly used methods of Graphics class:

1. public abstract void drawString(String str, int x, int y): is used


to draw the specified string.
2. public void drawRect(int x, int y, int width, int height): draws a
rectangle with the specified width and height.
3. public abstract void fillRect(int x, int y, int width, int height): is
used to fill rectangle with the default color and specified width and
height.
4. public abstract void drawOval(int x, int y, int width, int
height): is used to draw oval with the specified width and height.
5. public abstract void fillOval(int x, int y, int width, int height): is
used to fill oval 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 draw line between the points(x1, y1) and (x2, y2).
7. public abstract boolean drawImage(Image img, int x, int y,
ImageObserver observer): 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 to the specified color.
11. public abstract void setFont(Font font): is used to set the
graphics current font to the specified font.
Example of Graphics in applet:

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);
} }
myapplet.html
<html>
<body>
<applet code="GraphicsDemo.class" width="300" height="300">
</applet>
</body>
</html>

2.7 GUI application


Swing in Java is a Graphical User Interface (GUI) toolkit that includes
the GUI components. Swing provides a rich set of widgets and packages to
make sophisticated GUI components for Java applications. Swing is a part of
Java Foundation Classes(JFC), which is an API for Java GUI programing that
provide GUI.
The Java Swing library is built on top of the Java Abstract Widget
Toolkit (AWT), an older, platform dependent GUI toolkit. You can use the
Java simple GUI programming components like button, textbox, etc. from the
library and do not have to create the components from scratch.
Java Swing class Hierarchy Diagram

All components in Java Swing are JComponent which can be added to


container classes.
Container Class

Container classes are classes that can have other components on it. So
for creating a Java Swing GUI, we need at least one container object. There
are 3 types of Java Swing containers.
 Panel: It is a pure container and is not a window in itself. The sole
purpose of a Panel is to organize the components on to a window.
 Frame: It is a fully functioning window with its title and icons.
 Dialog: It can be thought of like a pop-up window that pops out when
a message has to be displayed. It is not a fully functioning window like
the Frame.
GUI in Java

GUI (Graphical User Interface) in Java is an easy-to-use visual


experience builder for Java applications. It is mainly made of graphical
components like buttons, labels, windows, etc. through which the user can
interact with an application. GUI plays an important role to build easy
interfaces for Java applications.
Java GUI Example

Now in this Java GUI Tutorial, let’s understand how to create a GUI in Java
with Swings in Java examples.
Example:How to make a GUI in Java.
Step 1) Copy the following code into an editor
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button = new JButton("Press");
frame.getContentPane().add(button); // Adds Button to content pane of
frame
frame.setVisible(true);
}
}
Step 2) Save, Compile, and Run the code.
Step 3) Now let’s Add a Button to our frame. Copy following code into an
editor from given Java UI Example
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Press");
frame.getContentPane().add(button1);
frame.setVisible(true);
}
}
Step 4) Execute the code. You will get a big button

Step 5) How about adding two buttons? Copy the following code into an
editor.
import javax.swing.*;
class gui{
public static void main(String args[]){
JFrame frame = new JFrame("My First GUI");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,300);
JButton button1 = new JButton("Button 1");
JButton button2 = new JButton("Button 2");
frame.getContentPane().add(button1);
frame.getContentPane().add(button2);
frame.setVisible(true);
}}
Step 6) Save , Compile , and Run the program.
Step 7) Unexpected output =? Buttons are getting overlapped.
Step 8) How about creating a chat frame like below?
Try to code yourself before looking at the program below.
//Usually you will require both swing and awt packages
// even if you are working with just swings.
import javax.swing.*;
import java.awt.*;
class gui {
public static void main(String args[]) {
//Creating the Frame
JFrame frame = new JFrame("Chat Frame");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(400, 400);
//Creating the MenuBar and adding components
JMenuBar mb = new JMenuBar();
JMenu m1 = new JMenu("FILE");
JMenu m2 = new JMenu("Help");
mb.add(m1);
mb.add(m2);
JMenuItem m11 = new JMenuItem("Open");
JMenuItem m22 = new JMenuItem("Save as");
m1.add(m11);
m1.add(m22);
//Creating the panel at bottom and adding components
JPanel panel = new JPanel(); // the panel is not visible in output
JLabel label = new JLabel("Enter Text");
JTextField tf = new JTextField(10); // accepts upto 10 characters
JButton send = new JButton("Send");
JButton reset = new JButton("Reset");
panel.add(label); // Components Added using Flow Layout
panel.add(tf);
panel.add(send);
panel.add(reset);
// Text Area at the Center
JTextArea ta = new JTextArea();
//Adding Components to the frame.
frame.getContentPane().add(BorderLayout.SOUTH, panel);
frame.getContentPane().add(BorderLayout.NORTH, mb);
frame.getContentPane().add(BorderLayout.CENTER, ta);
frame.setVisible(true);
}}

2.8 DIALOG BOXES


Java class named JOptionPane that produce dialog boxes. A dialog box
is a GUI object in which you can place messages that you want to display on
the screen. The showMessageDialog() method that is part of the JOptionPane
class. The showMessageDialog() method is followed by a set of parentheses.
The showMessageDialog() are two arguments. The first argument is null. its
means the message box should be shown in the center of the screen. After
the comma, second argument is the string that should be output.Here is the
java code for the program Dialog Box in Java Example :
import javax.swing.JOptionPane;
public class DialogBoxinJavaExample
{
public static void main(String[] args)
{
JOptionPane.showMessageDialog(null, " Dialog Box in Java Example ");
}
}
import javax.swing.*;
class TestSimpleFrame
{
public static void main(String[] args)
{
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SimpleFrame extends JFrame
{
private static final int WIDTH = 300;
private static final int HEIGHT = 200;
public SimpleFrame()
{
setTitle("Simple Frame");
setSize(WIDTH, HEIGHT);
} }

2.9 CREATING WINDOWS


A graphical user interface starts with a top-level container which
provides a home for the other components of the interface, and dictates the
overall feel of the application. we introduce the JFrame class, which is used
to create a simple top-level window for a Java application.
Java comes with a set of code libraries designed to help programmers
quickly create applications. They provide access to classes that perform
specific functions, to save you the bother of having to write them yourself.
The two import statements above let the compiler know that the application
needs access to some of the pre-built functionality contained within the
"AWT" and "Swing" code libraries.
AWT stands for “Abstract Window Toolkit.” It contains classes that
programmers can use to make graphical components such as buttons, labels
and frames. Swing is built on top of AWT, and provides an additional set of
more sophisticated graphical interface components. With just two lines of
code, we gain access to these graphical components, and can use them in
our Java application.
import javax.swing.*;
class TestSimpleFrame
{
public static void main(String[] args)
{
SimpleFrame frame = new SimpleFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
class SimpleFrame extends JFrame
{
private static final int WIDTH = 300;
private static final int HEIGHT = 200;
public SimpleFrame()
{
setTitle("Simple Frame");
setSize(WIDTH, HEIGHT);
}
}
2.10 LAYOUTMANAGERS
The LayoutManagers are used to arrange components in a particular manner. The Java
LayoutManagers facilitates us to control the positioning and size of the components in GUI
forms. LayoutManager is an interface that is implemented by all the classes of layout managers.
There are the following classes that represent 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.
Java BorderLayout:The BorderLayout is used to arrange the components in five
regions: north, south, east, west, and center. Each region (area) may contain one component only.
It is the default layout of a 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.
 BorderLayout(int hgap, int vgap): creates a border layout with the
given horizontal and vertical gaps between the components.
Example of BorderLayout class: Using BorderLayout() constructor

FileName: Border.java
import java.awt.*;
import javax.swing.*;
public class Border
{
JFrame f;
Border()
{
f = new JFrame();
// creating buttons

JButton b1 = new JButton("NORTH");; // the button will be labeled as NO


RTH JButton b2 = new JButton("SOUTH");; // the button will be labeled as
SOUTH
JButton b3 = new JButton("EAST");; // the button will be labeled as EAST
JButton b4 = new JButton("WEST");; // the button will be labeled as WES
T
JButton b5 = new JButton("CENTER");; // the button will be labeled as CENT
ER f.add(b1, BorderLayout.NORTH); // b1 will be placed in the North
Direction f.add(b2, BorderLayout.SOUTH); // b2 will be placed in the So
uth Direction f.add(b3, BorderLayout.EAST); // b2 will be placed in the E
ast Direction
f.add(b4, BorderLayout.WEST); // b2 will be placed in the West Directio
n
f.add(b5, BorderLayout.CENTER); // b2 will be placed in the Center
f.setSize(300, 300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
} }
The Layout managers enable us to control the way in which visual
components are arranged in the GUI forms by determining the size and
position of components within the containers.
Types of LayoutManager

There are 6 layout managers in Java

FlowLayout: It arranges the components in a container like the words on a


page. It fills the top line from left to right and top to bottom. The components
are arranged in the order as they are added i.e. first components appears at
top left, if the container is not wide enough to display all the components, it
is wrapped around the line. Vertical and horizontal gap between components
can be controlled. The components can be left, center or right aligned.
BorderLayout: It arranges all the components along the edges or the
middle of the container i.e. top, bottom, right and left edges of the area. The
components added to the top or bottom gets its preferred height, but its
width will be the width of the container and also the components added to
the left or right gets its preferred width, but its height will be the remaining
height of the container. The components added to the center gets neither its
preferred height or width. It covers the remaining area of the container.
GridLayout: It arranges all the components in a grid of equally sized cells,
adding them from the left to right and top to bottom. Only one component
can be placed in a cell and each region of the grid will have the same size.
When the container is resized, all cells are automatically resized. The order
of placing the components in a cell is determined as they were added.
GridBagLayout: It is a powerful layout which arranges all the components
in a grid of cells and maintains the aspect ration of the object whenever the
container is resized. In this layout, cells may be different in size. It assigns a
consistent horizontal and vertical gap among components. It allows us to
specify a default alignment for components within the columns or rows.
BoxLayout: It arranges multiple components in either vertically or
horizontally, but not both. The components are arranged from left to right or
top to bottom. If the components are aligned horizontally, the height of all
components will be the same and equal to the largest sized components. If
the components are aligned vertically, the width of all components will be
the same and equal to the largest width components.
CardLayout: It arranges two or more components having the same size. The
components are arranged in a deck, where all the cards of the same size and
the only top card are visible at any time. The first component added in the
container will be kept at the top of the deck. The default gap at the left,
right, top and bottom edges are zero and the card components are displayed
either horizontally or vertically.
Example
import java.awt.*;
import javax.swing.*;
public class LayoutManagerTest extends JFrame {
JPanel flowLayoutPanel1, flowLayoutPanel2, gridLayoutPanel1,
gridLayoutPanel2, gridLayoutPanel3;
JButton one, two, three, four, five, six;
JLabel bottom, lbl1, lbl2, lbl3;
public LayoutManagerTest() {
setTitle("LayoutManager Test");
setLayout(new BorderLayout()); // Set BorderLayout for JFrame
flowLayoutPanel1 = new JPanel();
one = new JButton("One");
two = new JButton("Two");
three = new JButton("Three");
flowLayoutPanel1.setLayout(new FlowLayout(FlowLayout.CENTER)); // Set
FlowLayout Manager
flowLayoutPanel1.add(one);
flowLayoutPanel1.add(two);
flowLayoutPanel1.add(three);
flowLayoutPanel2 = new JPanel();
bottom = new JLabel("This is South");
flowLayoutPanel2.setLayout (new FlowLayout(FlowLayout.CENTER)); // Set
FlowLayout Manager
flowLayoutPanel2.add(bottom);
gridLayoutPanel1 = new JPanel();
gridLayoutPanel2 = new JPanel();
gridLayoutPanel3 = new JPanel();
lbl1 = new JLabel("One");
lbl2 = new JLabel("Two");
lbl3 = new JLabel("Three");
four = new JButton("Four");
five = new JButton("Five");
six = new JButton("Six");
gridLayoutPanel2.setLayout(new GridLayout(1, 3, 5, 5)); // Set GridLayout
Manager
gridLayoutPanel2.add(lbl1);
gridLayoutPanel2.add(lbl2);
gridLayoutPanel2.add(lbl3);
gridLayoutPanel3.setLayout(new GridLayout(3, 1, 5, 5)); // Set
GridLayout Manager
gridLayoutPanel3.add(four);
gridLayoutPanel3.add(five);
gridLayoutPanel3.add(six);
gridLayoutPanel1.setLayout(new GridLayout(2, 1)); // Set GridLayout
Manager
gridLayoutPanel1.add(gridLayoutPanel2);
gridLayoutPanel1.add(gridLayoutPanel3);
add(flowLayoutPanel1, BorderLayout.NORTH);
add(flowLayoutPanel2, BorderLayout.SOUTH);
add(gridLayoutPanel1, BorderLayout.CENTER);
setSize(400, 325);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLocationRelativeTo(null);
setVisible(true);
}
public static void main(String args[]) {
new LayoutManagerTest();
}}
2.11 AWT Components classes
A component is an object with a graphical representation that can be
displayed on the screen and that can interact with the user. The Component
class is the abstract parent of the nonmenu-related AWT components.
Button (java.awt.Button)

To create a Button object, simply create an instance of the Button


class by calling one of the constructors. The most commonly used
constructor of the Button class takes a String argument, that gives the
Button object a text title. The two constructors are:
Button() // Constructs a Button with no label.
Button(String label) // Constructs a Button with the specified label.
When a user presses on a Button object an event is generated. The
label of the button that is pressed can be obtained.

Checkboxes (java.awt.Checkbox)

Checkboxes ave two states, on and off. The state of the button is
returned as the Object argument, when a Checkbox event occurs. To find
out the state of a checkbox object we can use getState() that returns a true
or false value. We can also get the label of the checkbox using getLabel()
that returns a String object.
Radio Buttons (java.awt.CheckboxGroup)

Is a group of checkboxes, where only one of the items in the group can
be selected at any one time.
Choice Buttons (java.awt.Choice)

Like a radio button, where we make a selection, however it requires


less space and allows us to add items to the menu dynamically using the
addItem() method.
Labels (java.awt.Label)
Allow us to add a text description to a point on the applet or
application.
TextFields (java.awt.TextField)

Are areas where the user can enter text. They are useful for displaying
and receiving text messages. We can make this textfield read-only or
editable. We can use the setEditable(false) to set a textfield read-only.
There are numerous ways that we can construct a Textfield object:
TextField text1 = new TextField(); // no properties
TextField text2 = new TextField("Some text"); // a textfield with a
// predefined String
TextField text3 = new TextField(40); // a textfield with a
// predefined size
TextField text4 = new TextField("Some text", 50); // combination of the two
An Example Component Application

To show these components in action we can write a short piece of code that
displays these components, but they do not have any events behind them -
they work visually but do not have any true program function. “A
Component Applet” shows an example applet that details all the previous
components.
You can see this applet running here - ComponentApplet.html and the code
segment is here - ComponentApplet.java
// The Component Applet that displays several components
import java.applet.Applet;
import java.awt.*;
public class ComponentApplet extends Applet
{ public void init()
{ Button b = new Button("Test Button");
this.add(b);
Checkbox cb = new Checkbox("Test Checkbox");
this.add(cb);
CheckboxGroup cbg = new CheckboxGroup();
this.add(new Checkbox("CB Item 1", cbg, false));
this.add(new Checkbox("CB Item 2", cbg, false));
this.add(new Checkbox("CB Item 3", cbg, true));
Choice choice = new Choice();
choice.addItem("Choice Item 1");
choice.addItem("Choice Item 2");
choice.addItem("Choice Item 3");
this.add(choice);
Label l = new Label("Test Label");
this.add(l);
TextField t = new TextField("Test TextField",30);
this.add(t);
}}

2.12 SWING COMPONENT CLASS


Swing in Java is a lightweight GUI toolkit which has a wide variety of widgets
for building optimized window based applications. It is a part of the JFC( Java
Foundation Classes). It is build on top of the AWT API and entirely written
in java. It is platform independent unlike AWT and has lightweight
components.It becomes easier to build applications since we already have
GUI components like button, checkbox etc. This is helpful because we do not
have to start from the scratch.
Container Class

Any class which has other components in it is called as a container


class. For building GUI applications at least one container class is necessary.
Following are the three types of container classes:
 Panel – It is used to organize components on to a window
 Frame – A fully functioning window with icons and titles
 Dialog – It is like a pop up window but not fully functional like the
frame
Difference Between AWT and Swing

AWT SWING
Platform Dependent Platform Independent
Does not follow MVC Follows MVC
Lesser Components More powerful components
Does not support pluggable look and Supports pluggable look and feel
feel
Heavyweight Lightweight

Java Swing Class Hierarchy

All the components in swing like JButton, JComboBox, JList, JLabel are
inherited from the JComponent class which can be added to the container
classes. Containers are the windows like frame and dialog boxes. Basic swing
components are the building blocks of any gui application. Methods like
setLayout override the default layout in each container. Containers like
JFrame and JDialog can only add a component to itself. Following are a few
components with examples to understand how we can use them.
JButton Class

It is used to create a labelled button. Using the ActionListener it will


result in some action when the button is pushed. It inherits the
AbstractButton class and is platform independent.
Example:

import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JButton b = new JButton("click me");
b.setBounds(40,90,85,20);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
}Output:

JTextField Class

It inherits the JTextComponent class and it is used to allow editing of


single line text.
Example:
import javax.swing.*;
public class example{
public static void main(String args[]) {
JFrame a = new JFrame("example");
JTextField b = new JTextField("edureka");
b.setBounds(50,100,200,30);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}}
Output:

JScrollBar Class

It is used to add scroll bar, both horizontal and vertical.


Example:
import javax.swing.*;
class example{
example(){
JFrame a = new JFrame("example");
JScrollBar b = new JScrollBar();
b.setBounds(90,90,40,90);
a.add(b);
a.setSize(300,300);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[]){
new example();
}}
Output:

JPanel Class

It inherits the JComponent class and provides space for an application


which can attach any other component.
import java.awt.*;
import javax.swing.*;
public class Example{
Example(){
JFrame a = new JFrame("example");
JPanel p = new JPanel();
p.setBounds(40,70,200,200);
JButton b = new JButton("click me");
b.setBounds(60,50,80,40);
p.add(b);
a.add(p);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
Output:

JMenu Class

It inherits the JMenuItem class, and is a pull down menu component


which is displayed from the menu bar.
import javax.swing.*;
class Example{
JMenu menu;
JMenuItem a1,a2;
Example()
{
JFrame a = new JFrame("Example");
menu = new JMenu("options");
JMenuBar m1 = new JMenuBar();
a1 = new JMenuItem("example");
a2 = new JMenuItem("example1");
menu.add(a1);
menu.add(a2);
m1.add(menu);
a.setJMenuBar(m1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}

Output:

JList Class
It inherits JComponent class, the object of JList class represents a list of
text items.
import javax.swing.*;
public class Example
{
Example( ){

JFrame a = new JFrame("example");


DefaultListModel<String> l = new DefaultListModel<>();
l.addElement("first item");
l.addElement("second item");
JList<String> b = new JList<>(l);
b.setBounds(100,100,75,75);
a.add(b);
a.setSize(400,400);
a.setVisible(true);
a.setLayout(null);
}
public static void main(String args[])
{
new Example();
}
}
Output:

JLabel Class

It is used for placing text in a container. It also inherits JComponent


class.
import javax.swing.*;
public class Example{
public static void main(String args[])
{
JFrame a = new JFrame("example");
JLabel b1;
b1 = new JLabel("edureka");
b1.setBounds(40,40,90,20);
a.add(b1);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
}
Output:

JComboBox Class

It inherits the JComponent class and is used to show pop up menu of


choices.
import javax.swing.*;
public class Example{
JFrame a;
Example(){
a = new JFrame("example");
string courses[] = { "core java","advance java", "java servlet"};
JComboBox c = new JComboBox(courses);
c.setBounds(40,40,90,20);
a.add(c);
a.setSize(400,400);
a.setLayout(null);
a.setVisible(true);
}
public static void main(String args[])
{
new Example();
}
}
Output:

2.13 BORDERS
Any Swing component can have a decorative border. JComponent
includes a method called setBorder() ; all you have to do is call it, passing it
an appropriate implementation of the Border interface. Swing provides many
useful Border implementations in the javax.swing.border package. You could
create an instance of one of these classes and pass it to a component’s
setBorder() method, but there’s an even simpler technique.
The BorderFactory class creates any kind of border for you using static
“factory” methods. Creating and setting a component’s border, then, is
simple:
JLabel labelTwo = new JLabel("I have an etched border.");
labelTwo.setBorder(BorderFactory.createEtchedBorder());
BorderFactory is convenient, but it does not offer every option of every
border type. For example, if you want to create a raised EtchedBorder
instead of the default lowered border, you’ll need to use EtchedBorder’s
constructor, like this:
JLabel labelTwo = new JLabel("I have a raised etched border.");
labelTwo.setBorder( new EtchedBorder(EtchedBorder.RAISED) );
The Border implementation classes are listed and briefly described here:
BevelBorder:This border draws raised or lowered beveled edges, giving an
illusion of depth.
SoftBevelBorder:This border is similar to BevelBorder, but thinner.
EmptyBorder:Doesn’t do any drawing, but does take up space. You can use
it to give a component a little breathing room in a crowded user interface.
EtchedBorder:A lowered etched border gives the appearance of a rectangle
that has been chiseled into a piece of stone. A raised etched border looks
like it is standing out from the surface of the screen.
LineBorder:Draws a simple rectangle around a component. You can specify
the color and width of the line in LineBorder’s constructor.
MatteBorder:A souped-up version of LineBorder. You can create a
MatteBorder with a certain color and specify the size of the border on the
left, top, right, and bottom of the component. MatteBorder also allows you to
pass in an Icon that will be used to draw the border. This could be an image
(ImageIcon) or any other implementation of the Icon interface.
TitledBorder:A regular border with a title. TitledBorder doesn’t actually
draw a border; it just draws a title in conjunction with another border object.
You can specify the locations of the title, its justification, and its font. This
border type is particularly useful for grouping different sets of controls in a
complicated interface.
CompoundBorder:A border that contains two other borders. This is
especially handy if you want to enclose a component in an EmptyBorder and
then put something decorative around it, such as an EtchedBorder or a
MatteBorder.

2.14 EVENT HANDLING WITH AWT COMPONENTS


Changing the state of an object is known as an event. For example,
click on button, dragging mouse etc. The java.awt.event package provides
many event classes and Listener interfaces for event handling.
Java Event classes and Listener interfaces
Event Classes Listener Interfaces
ActionEvent ActionListener
MouseListener and
MouseEvent
MouseMotionListener
MouseWheelEvent MouseWheelListener
KeyEvent KeyListener
ItemEvent ItemListener
TextEvent TextListener
AdjustmentEvent AdjustmentListener
WindowEvent WindowListener
ComponentEvent ComponentListener
ContainerEvent ContainerListener
FocusEvent FocusListener

Steps to perform Event Handling


Following steps are required to perform event handling:
Register the component with the Listener

Registration Methods

For registering the component with the Listener, many classes provide the
registration methods. For example:
Button:public void addActionListener(ActionListener a){ }

MenuItem

public void addActionListener(ActionListener a){ }


TextField

public void addActionListener(ActionListener a){ }


public void addTextListener(TextListener a){}
TextArea

public void addTextListener(TextListener a){ }


Checkbox

public void addItemListener(ItemListener a) { }


Choice

public void addItemListener(ItemListener a){ }


List

public void addActionListener(ActionListener a){ }


public void addItemListener(ItemListener a){ }
Java Event Handling Code

We can put the event handling code into one of the following places:
 Within class
 Other class
 Anonymous class

Java event handling by implementing ActionListener

import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
b.addActionListener(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){
tf.setText("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 event handling by outer class

import java.awt.*;
import java.awt.event.*;
class AEvent2 extends Frame{
TextField tf;
AEvent2(){
//create components
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(100,120,80,30);
//register listener
Outer o=new Outer(this);
b.addActionListener(o);//passing outer class instance
//add components and set size, layout and visibility

add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent2();
}
}
import java.awt.event.*;
class Outer implements ActionListener{
AEvent2 obj;
Outer(AEvent2 obj){
this.obj=obj;
}
public void actionPerformed(ActionEvent e){
obj.tf.setText("welcome");
}
}
Java event handling by anonymous class

import java.awt.*;
import java.awt.event.*;
class AEvent3 extends Frame{
TextField tf;
AEvent3(){
tf=new TextField();
tf.setBounds(60,50,170,20);
Button b=new Button("click me");
b.setBounds(50,120,80,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(){
tf.setText("hello");
}
});
add(b);add(tf);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public static void main(String args[]){
new AEvent3();
} }

2.15 FILECHOOSER
The object of JFileChooser class represents a dialog window from which
the user can select file. It inherits JComponent class and .JFileChooser class
declaration
Let's see the declaration for javax.swing.JFileChooser class.
public class JFileChooser extends JComponent implements Accessible
Commonly used Constructors:

Constructor Description
Constructs a JFileChooser pointing to the
JFileChooser()
user's default directory.
JFileChooser(File Constructs a JFileChooser using the given
currentDirectory) File as the path.
JFileChooser(String Constructs a JFileChooser using the given
currentDirectoryPath) path.
Example:
import javax.swing.*;
import java.awt.event.*;
import java.io.*;
public class FileChooserExample extends JFrame implements ActionListener{

JMenuBar mb;
JMenu file;
JMenuItem open;
JTextArea ta;
FileChooserExample(){
open=new JMenuItem("Open File");
open.addActionListener(this);
file=new JMenu("File");
file.add(open);
mb=new JMenuBar();
mb.setBounds(0,0,800,20);
mb.add(file);
ta=new JTextArea(800,800);
ta.setBounds(0,20,800,800);
add(mb);
add(ta);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==open){
JFileChooser fc=new JFileChooser();
int i=fc.showOpenDialog(this);
if(i==JFileChooser.APPROVE_OPTION){
File f=fc.getSelectedFile();
String filepath=f.getPath();
try{
BufferedReader br=new BufferedReader(new FileReader(filepath));
String s1="",s2="";
while((s1=br.readLine())!=null){
s2+=s1+"\n";
}
ta.setText(s2);
br.close();
}catch (Exception ex) {ex.printStackTrace(); }
} } }
public static void main(String[] args) {
FileChooserExample om=new FileChooserExample();
om.setSize(500,500);
om.setLayout(null);
om.setVisible(true);
om.setDefaultCloseOperation(EXIT_ON_CLOSE);
} }

2.16 COLOR CHOOSER


The JColorChooser class is used to create a color chooser dialog box so
that user can select any color. It inherits JComponent class.
JColorChooser class declaration

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


public class JColorChooser extends JComponent implements Accessible
Commonly used Constructors:

 JColorChooser():It is used to create a color chooser panel with white


color initially.
 JColorChooser(color initialcolor):It is used to create a color chooser
panel with the specified color initially.
Commonly used Methods:

 void addChooserPanel(AbstractColorChooserPanel panel):It is used to


add a color chooser panel to the color chooser.
 static Color showDialog(Component c, String title, Color initialColor):It
is used to show the color chooser dialog box.
JColorChooser Example with ActionListener
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class ColorChooserExample extends JFrame implements ActionListene
r{
JFrame f;
JButton b;
JTextArea ta;
ColorChooserExample(){
f=new JFrame("Color Chooser Example.");
b=new JButton("Pad Color");
b.setBounds(200,250,100,30);
ta=new JTextArea();
ta.setBounds(10,10,300,200);
b.addActionListener(this);
f.add(b);f.add(ta);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
Color c=JColorChooser.showDialog(this,"Choose",Color.CYAN);
ta.setBackground(c);
}
public static void main(String[] args) {
new ColorChooserExample();
} }
Output:
2.17 TREE
The JTree class is used to display the tree structured data or
hierarchical data. JTree is a complex component. It has a 'root node' at the
top most which is a parent for all nodes in the tree. It inherits JComponent
class.f Java
JTree class declaration

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


public class JTree extends JComponent implements Scrollable, Accessible
Commonly used Constructors:

Constructor Description
JTree() Creates a JTree with a sample model.
JTree(Object[] Creates a JTree with every element of the specified array
value) as the child of a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root,
root) which displays the root node.
Java JTree Example
import javax.swing.*;
import javax.swing.tree.DefaultMutableTreeNode;
public class TreeExample {
JFrame f;
TreeExample(){
f=new JFrame();
DefaultMutableTreeNode style=new DefaultMutableTreeNode("Style");
DefaultMutableTreeNode color=new DefaultMutableTreeNode("color");
DefaultMutableTreeNode font=new DefaultMutableTreeNode("font");
style.add(color);
style.add(font);
DefaultMutableTreeNode red=new DefaultMutableTreeNode("red");
DefaultMutableTreeNode blue=new DefaultMutableTreeNode("blue");
DefaultMutableTreeNode black=new DefaultMutableTreeNode("black");
DefaultMutableTreeNode green=new DefaultMutableTreeNode("green");
color.add(red); color.add(blue); color.add(black); color.add(green);
JTree jt=new JTree(style);
f.add(jt);
f.setSize(200,200);
f.setVisible(true);
}
public static void main(String[] args) {
new TreeExample();
}}
Output:
2.18 TABLE
The JTable class is used to display data in tabular form. It is composed
of rows and columns.
JTable class declaration

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


Commonly used Constructors:

Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] Creates a table with the specified
columns) data.
Java JTable Example
import javax.swing.*;
public class TableExample {
JFrame f;
TableExample(){
f=new JFrame();
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
JTable jt=new JTable(data,column);
jt.setBounds(30,40,200,300);
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300,400);
f.setVisible(true);
}
public static void main(String[] args) {
new TableExample();
}
}
Output:

2.19 TABBEDPANELS
The JTabbedPanel class is used to switch between a group of
components by clicking on a tab with a given title or icon. It inherits
JComponent class.
JTabbedPanel class declaration

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


public class JTabbedPane extends JComponent implements Serializable, Acce
ssible, SwingConstants
Commonly used Constructors:

Constructor Description
JTabbedPane() Creates an empty TabbedPane with a
default tab placement of JTabbedPane.Top.
JTabbedPane(int Creates an empty TabbedPane with a
tabPlacement) specified tab placement.
JTabbedPane(int Creates an empty TabbedPane with a
tabPlacement, int specified tab placement and tab layout
tabLayoutPolicy) policy.
Java JTabbedPane Example

import javax.swing.*;
public class TabbedPaneExample {
JFrame f;
TabbedPaneExample(){
f=new JFrame();
JTextArea ta=new JTextArea(200,200);
JPanel p1=new JPanel();
p1.add(ta);
JPanel p2=new JPanel();
JPanel p3=new JPanel();
JTabbedPane tp=new JTabbedPane();
tp.setBounds(50,50,200,200);
tp.add("main",p1);
tp.add("visit",p2);
tp.add("help",p3);
f.add(tp);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String[] args) {
new TabbedPaneExample();
}}

Output:
2.20 PROGRESSIVE BAR
The JProgressBar class is used to display the progress of the task. It inherits JComponent
class.
JProgressBar class declaration

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


public class JProgressBar extends JComponent implements SwingConstants, Accessible
Commonly used Constructors:

Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string text.
JProgressBar(int min, int It is used to create a horizontal progress bar with the specified
max) minimum and maximum value.
JProgressBar(int orient) It is used to create a progress bar with the specified orientation, it
can be either Vertical or Horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int orient, It is used to create a progress bar with the specified orientation,
int min, int max) minimum and maximum value.

Commonly used Methods:


Method Description
It is used to determine whether string should be
void setStringPainted(boolean b)
displayed.
void setString(String s) It is used to set value to the progress string.
void setOrientation(int orientation) It is used to set the orientation, it may be either vertical
or horizontal by using SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
void setValue(int value) It is used to set the current value on the progress bar.

Java JProgressBar Example


import javax.swing.*;
public class ProgressBarExample extends JFrame{
JProgressBar jb;
int i=0,num=0;
ProgressBarExample(){
jb=new JProgressBar(0,2000);
jb.setBounds(40,40,160,30);
jb.setValue(0);
jb.setStringPainted(true);
add(jb);
setSize(250,150);
setLayout(null); }
public void iterate(){
while(i<=2000){
jb.setValue(i);
i=i+20;
try{Thread.sleep(150);}catch(Exception e){}
} }
public static void main(String[] args) {
ProgressBarExample m=new ProgressBarExample();
m.setVisible(true);
m.iterate();
} }
Output:
2.21 SLIDER
The Java JSlider class is used to create the slider. By using JSlider, a user can select a
value from a specific range.
Commonly used Constructors of JSlider class

Constructor Description
JSlider() creates a slider with the initial value of 50 and
range of 0 to 100.
JSlider(int orientation) creates a slider with the specified orientation
set by either JSlider.HORIZONTAL or
JSlider.VERTICAL with the range 0 to 100 and
initial value 50.
JSlider(int min, int max) creates a horizontal slider using the given min
and max.
JSlider(int min, int max, creates a horizontal slider using the given min,
int value) max and value.
JSlider(int orientation, int creates a slider using the given orientation, min,
min, int max, int value) max and value.
Commonly used Methods of JSlider class
Method Description
public void It is used to set the minor tick
setMinorTickSpacing(int n) spacing to the slider.
public void It is used to set the major tick
setMajorTickSpacing(int n) spacing to the slider.
public void setPaintTicks(boolean It is used to determine whether tick
b) marks are painted.
public void setPaintLabels(boolean It is used to determine whether
b) labels are painted.
public void setPaintTracks(boolean It is used to determine whether track
b) is painted.
Java JSlider Example
import javax.swing.*;
public class SliderExample1 extends JFrame{
public SliderExample1() {
JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 50, 25);
JPanel panel=new JPanel();
panel.add(slider);
add(panel); }
public static void main(String s[]) {
SliderExample1 frame=new SliderExample1();
frame.pack();
frame.setVisible(true); } }
Output:

You might also like