0% found this document useful (0 votes)
43 views50 pages

Java Networking

This document provides information about Java applets including: - Applets run inside web browsers and generate dynamic content at the client-side. They have advantages like faster response times and security, and can run on multiple platforms. However, they require a plugin. - The applet lifecycle includes initialization, start, paint, stop, and destruction methods. The Applet class provides lifecycle methods and Component provides a paint method. - Graphics methods like drawString, drawRect, and setColor are used to display graphics in applets. Examples demonstrate setting colors, drawing shapes, lines, arcs and resizing applets.

Uploaded by

Samarth Mangave
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
43 views50 pages

Java Networking

This document provides information about Java applets including: - Applets run inside web browsers and generate dynamic content at the client-side. They have advantages like faster response times and security, and can run on multiple platforms. However, they require a plugin. - The applet lifecycle includes initialization, start, paint, stop, and destruction methods. The Applet class provides lifecycle methods and Component provides a paint method. - Graphics methods like drawString, drawRect, and setColor are used to display graphics in applets. Examples demonstrate setting colors, drawing shapes, lines, arcs and resizing applets.

Uploaded by

Samarth Mangave
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 50

Java Applet

Applet is a special type of program that is embedded in the webpage to generate the
dynamic content. It runs inside the browser and works at client side.
Advantage of Applet
There are many advantages of applet. They are as follows:
o It works at client side so less response time.
o Secured
o It can be executed by browsers running under many plateforms, including Linux,
Windows, MacOs etc.
Drawback of Applet
o Plugin is required at client browser to execute applet.
Hierarchy of Applet

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

Lifecycle of Java Applet


1. Applet is initialized.
2. Applet is started.
3. Applet is painted.
4. Applet is stopped.
5. 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.

1. public void init(): is used to initialized the Applet. It is invoked only once.
2. public void start(): is invoked after the init() method or browser is maximized. It is
used to start the Applet.
3. public void stop(): is used to stop the Applet. It is invoked when Applet is stop or
browser is minimized.
4. public void destroy(): is used to destroy the Applet. It is invoked only once.

 java.awt.Component class

The Component class provides 1 life cycle method of applet.

1. public void paint(Graphics g): is used to paint the Applet. It provides Graphics
class object that can be used for drawing oval, rectangle, arc etc.

Dambal Sir (Sangola Collge,Sangola) 1


Who is responsible to manage the life cycle of an applet?

Java Plug-in software.

How to run an Applet?

There are two ways to run an applet

1. By html file.
2. 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

Dambal Sir (Sangola Collge,Sangola) 2


Displaying 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 booleandrawImage(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, intstartAngle,
intarcAngle): is used draw a circular or elliptical arc.
9. public abstract void fillArc(int x, int y, int width, int height, intstartAngle,
intarcAngle): 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.

//Set Background Color Of an Applet Window Example


importjava.applet.Applet;
importjava.awt.Color;
importjava.awt.Graphics;
public class SetBackgroundColorExample extends Applet{

public void paint(Graphics g){

setBackground(Color.red);
}
}

//Draw Line in Applet Window Example


import java.applet.Applet;
import java.awt.Graphics;
public class DrawLineExample extends Applet
{ public void paint(Graphics g)
{
//this will draw a line between (10,10) and (50,50) coordinates.
g.drawLine(10,10,50,50);

//draw vertical line


g.drawLine(10,50,10,100);

//draw horizontal line


g.drawLine(10,10,50,10);
}
}

Dambal Sir (Sangola Collge,Sangola) 3


//Set Foreground Color Of an Applet Window Example
importjava.applet.Applet;
importjava.awt.Color;
importjava.awt.Graphics;

public class SetForegroundColorExample extends Applet{

public void paint(Graphics g){

setForeground(Color.red);
g.drawString("Foreground color set to red", 50, 50);
}
}
//Draw Smiley In Applet Example
importjava.awt.*;
importjava.applet.*;

public class Smiley extends Applet{

public void paint(Graphics g){

Font f = new Font("Helvetica", Font.BOLD,20);


g.setFont(f);
g.drawString("Keep Smiling!!!", 50, 30);
g.drawOval(60, 60, 200, 200);
g.fillOval(90, 120, 50, 20);
g.fillOval(190, 120, 50, 20);
g.drawLine(165, 125, 165, 175);
g.drawArc(110, 130, 95, 95, 0, -180);
}
}
//Resize Applet Window Example
importjava.applet.Applet;
importjava.awt.Graphics;

public class ResizeAppletWindowExample extends Applet{

public void paint(Graphics g){

resize(300,300);
g.drawString("Window has been resized to 300,300", 50, 50);
}

}
//Draw Arc in Applet Window Example
importjava.applet.Applet;
importjava.awt.Color;
importjava.awt.Graphics;

public class DrawArcExample extends Applet{

public void paint(Graphics g){

//set color to red


Dambal Sir (Sangola Collge,Sangola) 4
setForeground(Color.red);

//this will draw an arc of width 50 & height 100 at (10,10)


g.drawArc(10,10,50,100,10,45);

//draw filled arc


g.fillArc(100,10,100,100,0,90);

}
}
//Draw Oval & Circle in Applet Window Example
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;

public class DrawOvalsExample extends Applet


{ public void paint(Graphics g)
{
//set color to red
setForeground(Color.red);

//this will draw a oval of width 50 & height 100 at (10,10)


g.drawOval(10,10,50,100);

//draw filled oval


g.fillOval(100,20,50,100);
}
}

//Set Status Message in Applet Window Example


importjava.applet.Applet;
importjava.awt.Graphics;

public class SetStatusMessageExample extends Applet{

public void paint(Graphics g){

//this will be displayed inside an applet


g.drawString("Show Status Example", 50, 50);

//this will be displayed in a status bar of an applet window


showStatus("This is a status message of an applet window");
}
}
//Using Applet dimension to print center aligned text Example
importjava.applet.Applet;
importjava.awt.Dimension;
importjava.awt.Font;
importjava.awt.FontMetrics;
importjava.awt.Graphics;

public class AppletDimensionExample extends Applet{


Dambal Sir (Sangola Collge,Sangola) 5
public void paint(Graphics g){
intx,y;
String s = "Hello World";

//get applet size using getSize method


Dimension d = getSize();
Font f = new Font("Arial",Font.BOLD,24);
g.setFont(f);

//determine x and y coordinates


FontMetricsfm = g.getFontMetrics();
x = d.width/2 - fm.stringWidth(s)/2;
y = d.height/2 - fm.getHeight();

//print string at specified location using drawString method


g.drawString(s,x,y);
}
}
//Get Applet Directory URL or Code Base Example
importjava.applet.Applet;
importjava.awt.Graphics;
import java.net.URL;
/*
<applet code="GetCodeBaseExample" width=200 height=200>
</applet>
*/
public class GetCodeBaseExample extends Applet {

public void paint(Graphics g) {

URL appletDir = getCodeBase();


g.drawString(appletDir.toString(), 50, 50);

}}

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

Dambal Sir (Sangola Collge,Sangola) 6


Displaying Image in Applet

Applet is mostly used in games and animation. For this purpose image is required to be
displayed. The java.awt.Graphics class provide a method drawImage() to display the image.

Syntax of drawImage() method:

1. public abstract booleandrawImage(Image img, int x, int y, ImageObserver


observer): is used draw the specified image.

How to get the object of Image:

The java.applet.Applet class provides getImage() method that returns the object of Image.
Syntax:
1. public Image getImage(URL u, String image){}

Other required methods of Applet class to display image:

1. public URL getDocumentBase(): is used to return the URL of the document in which
applet is embedded.
2. public URL getCodeBase(): is used to return the base URL.

Example of displaying image in applet:

import java.awt.*;
import java.applet.*;
public class DisplayImage extends Applet
{

Image picture;

public void init()


{
picture = getImage(getDocumentBase(),"abc.jpg");
}

public void paint(Graphics g) {


g.drawImage(picture, 30,30, this);
}
}
/*<applet code="DisplayImage.class" width="300" height="300">
</applet> */

In the above example, drawImage() method of Graphics class is used to display the
image.The 4th argument of drawImage() method of is ImageObserver object. The
Component class implements ImageObserver interface. So current class object would
also be treated as ImageObserver because Applet class indirectly extends the Component
class.

Animation in Applet

Applet is mostly used in games and animation. For this purpose image is required to be
moved.

Example of animation in applet:

import java.awt.*;
import java.applet.*;
Dambal Sir (Sangola Collge,Sangola) 7
public class AnimationExample extends Applet
{

Image picture;

public void init()


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

public void paint(Graphics g)


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

try{Thread.sleep(100);}catch(Exception e){}
}
}
}
/*<applet code="DisplayImage.class" width="300" height="300">
</applet> */

In the above example, drawImage() method of Graphics class is used to display the image.
The 4th argument of drawImage() method of is ImageObserver object. The Component
class implements ImageObserver interface. So current class object would also be treated
as ImageObserver because Applet class indirectly extends the Component class.

Dambal Sir (Sangola Collge,Sangola) 8


Java AWT
Java AWT (Abstract Window Toolkit) is an API to develop GUI or window-based
applications in java.
Java AWT components are platform-dependent i.e. components are displayed
according to the view of operating system. AWT is heavyweight i.e. its components
are using the resources of OS.
The java.awt package provides classes for AWT api such as TextField, Label,
TextArea, RadioButton, CheckBox, Choice, List etc.

Java AWT Hierarchy


The hierarchy of Java AWT classes are given below.

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.
Useful Methods of Component class
Method Description
public void add(Component c) inserts a component on this component.
public void setSize(int width,int sets the size (width and height) of the
height) component.
public void defines the layout manager for the
setLayout(LayoutManager m) component.
public void setVisible(boolean changes the visibility of the component, by
status) default false.

Dambal Sir (Sangola Collge,Sangola) 9


Java AWT Example
To create simple awt example, you need a frame. There are two ways to create a
frame in AWT.
 By extending Frame class (inheritance)
 By creating the object of Frame class (association)
AWT Example by Inheritance
Let's see a simple example of AWT where we are inheriting Frame class. Here, we
are showing Button component on the Frame.
import java.awt.*;
class First extends Frame
{
First()
{
Button b=new Button("click me");
b.setBounds(30,100,80,30);// setting button position
add(b);//adding button into frame
setSize(300,300);//frame size 300 width and 300 height
setLayout(null);//no layout manager
setVisible(true);//now frame will be visible, by default not visible
}
public static void main(String args[]){
First f=new First();
}
}
The setBounds(int xaxis, int yaxis, int width, int height) method is used in the
above example that sets the position of the awt button.
AWT Example by Association
Let's see a simple example of AWT where we are creating instance of Frame class.
Here, we are showing Button component on the Frame.
import java.awt.*;
class First2{
First2(){
Frame f=new Frame();
Button b=new Button("click me");
b.setBounds(30,50,80,30);
f.add(b);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
First2 f=new First2();
}}
Java GUI Event Handling
Any program that uses GUI (graphical user interface) such as Java
application written for windows, is event driven. Event describes the change
in state of any object. For Example : Pressing a button, Entering a
character in Textbox, Clicking or Dragging a mouse, etc.

Components of Event Handling


Event handling has three main components,
 Events : An event is a change in state of an object.
 Events Source : Event source is an object that generates an event.
 Listeners : A listener is an object that listens to the event. A listener
gets notified when an event occurs.

How Events are handled?

Dambal Sir (Sangola Collge,Sangola) 10


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

Important Event Classes and Interface

Event Classes Description Listener Interface

ActionEvent generated when button is pressed, ActionListener


menu-item is selected, list-item is
double clicked

MouseEvent generated when mouse is dragged, MouseListener


moved,clicked,pressed or released
and also when it enters or exit a
component

KeyEvent generated when input is received KeyListener


from keyboard

ItemEvent generated when check-box or list ItemListener


item is clicked

TextEvent generated when value of textarea TextListener


or textfield is changed

MouseWheelEvent generated when mouse wheel is MouseWheelListener


moved

WindowEvent generated when window is WindowListener


activated, deactivated, deiconified,
iconified, opened or closed

ComponentEvent generated when component is ComponentEventListener


hidden, moved, resized or set
visible

ContainerEvent generated when component is ContainerListener


added or removed from container

AdjustmentEvent generated when scroll bar is AdjustmentListener


manipulated

FocusEvent generated when component gains FocusListener


or loses keyboard focus

Java Event Handling Code


We can put the event handling code into one of the following places:
1. Within class
2. Other class
3. Anonymous class
Java event handling by implementing ActionListener
import java.awt.*;
import java.awt.event.*;
class AEvent extends Frame implements ActionListener{
TextField tf;
AEvent(){
Dambal Sir (Sangola Collge,Sangola) 11
//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.
2) 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");
Dambal Sir (Sangola Collge,Sangola) 12
}
}

3) 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();
} }
Java AWT Button
The button class is used to create a labeled button that has platform independent
implementation. The application result in some action when the button is pushed.
AWT Button Class declaration
1. public class Button extends Component implements Accessible
Java AWT Button Example
import java.awt.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
Button b=new Button("Click Here");
b.setBounds(50,100,80,30);
f.add(b);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Button Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class ButtonExample {
public static void main(String[] args) {
Frame f=new Frame("Button Example");
final TextField tf=new TextField();
tf.setBounds(50,50, 150,20);
Button b=new Button("Click Here");
b.setBounds(50,100,60,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Javatpoint.");
}
});
Dambal Sir (Sangola Collge,Sangola) 13
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label
The object of Label 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.
AWT Label Class Declaration
1. public class Label extends Component implements Accessible
Java Label Example
import java.awt.*;
class LabelExample{
public static void main(String args[]){
Frame f= new Frame("Label Example");
Label l1,l2;
l1=new Label("First Label.");
l1.setBounds(50,100, 100,30);
l2=new Label("Second Label.");
l2.setBounds(50,150, 100,30);
f.add(l1); f.add(l2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT Label Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class LabelExample extends Frame implements ActionListener{
TextField tf; Label l; Button b;
LabelExample(){
tf=new TextField();
tf.setBounds(50,50, 150,20);
l=new Label();
l.setBounds(50,100, 250,20);
b=new Button("Find IP");
b.setBounds(50,150,60,30);
b.addActionListener(this);
add(b);add(tf);add(l);
setSize(400,400);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
try{
String host=tf.getText();
String ip=java.net.InetAddress.getByName(host).getHostAddress();
l.setText("IP of "+host+" is: "+ip);
}catch(Exception ex){System.out.println(ex);}
}
public static void main(String[] args) {
new LabelExample();
}
}

Dambal Sir (Sangola Collge,Sangola) 14


Java AWT TextField
The object of a TextField class is a text component that allows the editing of a
single line text. It inherits TextComponent class.
AWT TextField Class Declaration
1. public class TextField extends TextComponent
Java AWT TextField Example
import java.awt.*;
class TextFieldExample{
public static void main(String args[]){
Frame f= new Frame("TextField Example");
TextField t1,t2;
t1=new TextField("Welcome to Javatpoint.");
t1.setBounds(50,100, 200,30);
t2=new TextField("AWT Tutorial");
t2.setBounds(50,150, 200,30);
f.add(t1); f.add(t2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java AWT TextField Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextFieldExample extends Frame implements ActionListener{
TextField tf1,tf2,tf3;
Button b1,b2;
TextFieldExample(){
tf1=new TextField();
tf1.setBounds(50,50,150,20);
tf2=new TextField();
tf2.setBounds(50,100,150,20);
tf3=new TextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new Button("+");
b1.setBounds(50,200,50,50);
b2=new Button("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
add(tf1);add(tf2);add(tf3);add(b1);add(b2);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
Dambal Sir (Sangola Collge,Sangola) 15
}
public static void main(String[] args) {
new TextFieldExample();
}
}
Java AWT TextArea
The object of a TextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits TextComponent class.
AWT TextArea Class Declaration
1. public class TextArea extends TextComponent
Java AWT TextArea Example
import java.awt.*;
public class TextAreaExample
{
TextAreaExample(){
Frame f= new Frame();
TextArea area=new TextArea("Welcome to javatpoint");
area.setBounds(10,30, 300,300);
f.add(area);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new TextAreaExample(); } }
Java AWT TextArea Example with ActionListener
import java.awt.*;
import java.awt.event.*;
public class TextAreaExample extends Frame implements ActionListener{
Label l1,l2;
TextArea area;
Button b;
TextAreaExample(){
l1=new Label();
l1.setBounds(50,50,100,30);
l2=new Label();
l2.setBounds(160,50,100,30);
area=new TextArea();
area.setBounds(20,100,300,300);
b=new Button("Count Words");
b.setBounds(100,400,100,30);
b.addActionListener(this);
add(l1);add(l2);add(area);add(b);
setSize(400,450);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}

Dambal Sir (Sangola Collge,Sangola) 16


Java AWT Checkbox
The Checkbox 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".
AWT Checkbox Class Declaration
1. public class Checkbox extends Component implements ItemSelectable, Acce
ssible
Java AWT Checkbox Example
import java.awt.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("Checkbox Example");
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java", true);
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1);
f.add(checkbox2);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckboxExample();
}
}
Java AWT Checkbox Example with ItemListener
import java.awt.*;
import java.awt.event.*;
public class CheckboxExample
{
CheckboxExample(){
Frame f= new Frame("CheckBox Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
Checkbox checkbox1 = new Checkbox("C++");
checkbox1.setBounds(100,100, 50,50);
Checkbox checkbox2 = new Checkbox("Java");
checkbox2.setBounds(100,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
Dambal Sir (Sangola Collge,Sangola) 17
public static void main(String args[])
{
new CheckboxExample();
}
}
Java AWT List
The object of List class represents a list of text items. By the help of list, user can
choose either one item or multiple items. It inherits Component class.
AWT List class Declaration
1. public class List extends Component implements ItemSelectable, Accessible
Java AWT List Example
import java.awt.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
List l1=new List(5);
l1.setBounds(100,100, 75,75);
l1.add("Item 1");
l1.add("Item 2");
l1.add("Item 3");
l1.add("Item 4");
l1.add("Item 5");
f.add(l1);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new ListExample();
}
}

Java AWT List Example with ActionListener


import java.awt.*;
import java.awt.event.*;
public class ListExample
{
ListExample(){
Frame f= new Frame();
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(500,100);
Button b=new Button("Show");
b.setBounds(200,150,80,30);
final List l1=new List(4, false);
l1.setBounds(100,100, 70,70);
l1.add("C");
l1.add("C++");
l1.add("Java");
l1.add("PHP");
final List l2=new List(4, true);
l2.setBounds(100,200, 70,70);
l2.add("Turbo C++");
l2.add("Spring");
l2.add("Hibernate");
l2.add("CodeIgniter");
f.add(l1); f.add(l2); f.add(label); f.add(b);
Dambal Sir (Sangola Collge,Sangola) 18
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "+l1.getItem(l1.getSelecte
dIndex());
data += ", Framework Selected:";
for(String frame:l2.getSelectedItems()){
data += frame + " ";
}
label.setText(data);
}
});
}
public static void main(String args[])
{
new ListExample();
}
}

Java AWT Scrollbar


The object of Scrollbar class is used to add horizontal and vertical scrollbar.
Scrollbar is a GUI component allows us to see invisible number of rows and
columns.
AWT Scrollbar class declaration
1. public class Scrollbar extends Component implements Adjustable, Accessibl
e
Java AWT Scrollbar Example
import java.awt.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[]){
new ScrollbarExample();
}
}
Java AWT Scrollbar Example with AdjustmentListener
import java.awt.*;
import java.awt.event.*;
class ScrollbarExample{
ScrollbarExample(){
Frame f= new Frame("Scrollbar Example");
final Label label = new Label();
label.setAlignment(Label.CENTER);
label.setSize(400,100);
final Scrollbar s=new Scrollbar();
s.setBounds(100,100, 50,100);
f.add(s);f.add(label);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
Dambal Sir (Sangola Collge,Sangola) 19
s.addAdjustmentListener(new AdjustmentListener() {
public void adjustmentValueChanged(AdjustmentEvent e) {
label.setText("Vertical Scrollbar value is:"+ s.getValue());
}
});
}
public static void main(String args[]){
new ScrollbarExample();
}
}
Java AWT Panel
The Panel is a simplest container class. It provides space in which an application
can attach any other component. It inherits the Container class.
It doesn't have title bar.
AWT Panel class declaration
1. public class Panel extends Container implements Accessible
Java AWT Panel Example
import java.awt.*;
public class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");
Panel panel=new Panel();
panel.setBounds(40,80,200,200);
panel.setBackground(Color.gray);
Button b1=new Button("Button 1");
b1.setBounds(50,100,80,30);
b1.setBackground(Color.yellow);
Button b2=new Button("Button 2");
b2.setBounds(100,100,80,30);
b2.setBackground(Color.green);
panel.add(b1); panel.add(b2);
f.add(panel);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new PanelExample();
}
}
Java AWT Dialog
The Dialog control represents a top level window with a border and a title used to
take some form of input from the user. It inherits the Window class.
Unlike Frame, it doesn't have maximize and minimize buttons.
Frame vs Dialog
Frame and Dialog both inherits Window class. Frame has maximize and minimize
buttons but Dialog doesn't have.
AWT Dialog class declaration
1. public class Dialog extends Window
Java AWT Dialog Example
import java.awt.*;
import java.awt.event.*;
public class DialogExample {
private static Dialog d;
DialogExample() {
Frame f= new Frame();
d = new Dialog(f , "Dialog Example", true);
Dambal Sir (Sangola Collge,Sangola) 20
d.setLayout( new FlowLayout() );
Button b = new Button ("OK");
b.addActionListener ( new ActionListener()
{
public void actionPerformed( ActionEvent e )
{
DialogExample.d.setVisible(false);
}
});
d.add( new Label ("Click button to continue."));
d.add(b);
d.setSize(300,300);
d.setVisible(true);
}
public static void main(String args[])
{
new DialogExample();
}
}

Write a program to create simple calculator by using AWT controls


import java.awt.*;
import java.awt.event.*;
public class calculator implements ActionListener
{
int c,n;
String s1,s2,s3,s4,s5;
Frame f;
Button
b1,b2,b3,b4,b5,b6,b7,b8,b9,b10,b11,b12,b13,b14,b15,b16,b17;
Panel p;
TextField tf;
GridLayout g;
calculator()
{
f = new Frame("My calculator");
p = new Panel();
f.setLayout(new FlowLayout());
b1 = new Button("0");
b1.addActionListener(this);
b2 = new Button("1");
b2.addActionListener(this);
b3 = new Button("2");
b3.addActionListener(this);
b4 = new Button("3");
b4.addActionListener(this);
b5 = new Button("4");
b5.addActionListener(this);
b6 = new Button("5");
b6.addActionListener(this);
b7 = new Button("6");
b7.addActionListener(this);
b8 = new Button("7");
b8.addActionListener(this);
b9 = new Button("8");
b9.addActionListener(this);
b10 = new Button("9");
b10.addActionListener(this);
b11 = new Button("+");
Dambal Sir (Sangola Collge,Sangola) 21
b11.addActionListener(this);
b12 = new Button("-");
b12.addActionListener(this);
b13 = new Button("*");
b13.addActionListener(this);
b14 = new Button("/");
b14.addActionListener(this);
b15 = new Button("%");
b15.addActionListener(this);
b16 = new Button("=");
b16.addActionListener(this);
b17 = new Button("C");
b17.addActionListener(this);
tf = new TextField(20);
f.add(tf);
g = new GridLayout(4,4,10,20);
p.setLayout(g);

p.add(b1);p.add(b2);p.add(b3);p.add(b4);p.add(b5);p.add(b6);p.a
dd(b7);p.add(b8);p.add(b9);

p.add(b10);p.add(b11);p.add(b12);p.add(b13);p.add(b14);p.add(
b15);p.add(b16);p.add(b17);
f.add(p);
f.setSize(300,300);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e)
{ if(e.getSource()==b1)
{
s3 = tf.getText();
s4 = "0";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b2)
{
s3 = tf.getText();
s4 = "1";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b3)
{
s3 = tf.getText();
s4 = "2";
s5 = s3+s4;
tf.setText(s5);
}if(e.getSource()==b4)
{
s3 = tf.getText();
s4 = "3";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b5)
{
s3 = tf.getText();
s4 = "4";
Dambal Sir (Sangola Collge,Sangola) 22
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b6)
{
s3 = tf.getText();
s4 = "5";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b7)
{
s3 = tf.getText();
s4 = "6";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b8)
{
s3 = tf.getText();
s4 = "7";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b9)
{
s3 = tf.getText();
s4 = "8";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b10)
{
s3 = tf.getText();
s4 = "9";
s5 = s3+s4;
tf.setText(s5);
}
if(e.getSource()==b11)
{
s1 = tf.getText();
tf.setText("");
c=1;

}
if(e.getSource()==b12)
{
s1 = tf.getText();
tf.setText("");
c=2;

}
if(e.getSource()==b13)
{
s1 = tf.getText();
tf.setText("");
c=3;

}
Dambal Sir (Sangola Collge,Sangola) 23
if(e.getSource()==b14)
{
s1 = tf.getText();
tf.setText("");
c=4;

}
if(e.getSource()==b15)
{
s1 = tf.getText();
tf.setText("");
c=5;

}
if(e.getSource()==b16)
{
s2 = tf.getText();
if(c==1)
{
n=
Integer.parseInt(s1)+Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==2)
{
n = Integer.parseInt(s1)-
Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
if(c==3)
{
n=
Integer.parseInt(s1)*Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
if(c==4)
{
try
{
int p=Integer.parseInt(s2);
if(p!=0)
{
n=
Integer.parseInt(s1)/Integer.parseInt(s2);
tf.setText(String.valueOf(n));
}
else
tf.setText("infinite");

}
catch(Exception i){}
}
if(c==5)
{
n=
Integer.parseInt(s1)%Integer.parseInt(s2);
tf.setText(String.valueOf(n));
Dambal Sir (Sangola Collge,Sangola) 24
}
}
if(e.getSource()==b17)
{
tf.setText("");
}
}

public static void main(String[] abc)


{
calculator v = new calculator();
}
}
List
The List represents a list of text items. The list can be configured to that user can
choose either one item or multiple items.
Following is the declaration for java.awt.List class:Class constructors
S.N. Constructor & Description
List() Creates a new scrolling list.
List(int rows) Creates a new scrolling list initialized with the specified
number of visible lines.
List(int rows, boolean multipleMode) Creates a new scrolling list
initialized to display the specified number of rows.
Method & Description
void add(String item) Adds the specified item to the end of scrolling list.
void add(String item, int index) Adds the specified item to the the
scrolling list at the position indicated by the index.
String getItem(int index) Gets the item associated with the specified index.
int getItemCount() Gets the number of items in the list.
int getRows() Gets the number of visible lines in this list.
int getSelectedIndex() Gets the index of the selected item on the list,
int[] getSelectedIndexes() Gets the selected indexes on the list.
String getSelectedItem() Gets the selected item on this scrolling list.
String[] getSelectedItems() Gets the selected items on this scrolling list.
Object[] getSelectedObjects() Gets the selected items on this scrolling list in
an array of Objects.
void remove(int position) Removes the item at the specified position from
this scrolling list.
void remove(String item) Removes the first occurrence of an item from the
list.
void removeAll() Removes all items from this list.
void select(int index) Selects the item at the specified index in the scrolling
list.
void setMultipleMode(boolean b)
Sets the flag that determines whether this list allows multiple selections.
List Example
Create the following java program using any editor of your choice in say
import java.awt.*;
import java.awt.event.*;
publicclassAwtControlDemo
{

privateFrame mainFrame;
privateLabel headerLabel;
privateLabel statusLabel;
privatePanel controlPanel;

publicAwtControlDemo()
Dambal Sir (Sangola Collge,Sangola) 25
{
prepareGUI();
}

publicstaticvoid main(String[] args){


AwtControlDemo awtControlDemo =newAwtControlDemo();
awtControlDemo.showListDemo();
}

privatevoid prepareGUI(){
mainFrame =newFrame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(newGridLayout(3,1));
mainFrame.addWindowListener(newWindowAdapter(){
publicvoid windowClosing(WindowEvent windowEvent){
System.exit(0);
}
});
headerLabel =newLabel();
headerLabel.setAlignment(Label.CENTER);
statusLabel =newLabel();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

controlPanel =newPanel();
controlPanel.setLayout(newFlowLayout());

mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}

privatevoid showListDemo(){

headerLabel.setText("Control in action: List");


finalList fruitList =newList(4,false);

fruitList.add("Apple");
fruitList.add("Grapes");
fruitList.add("Mango");
fruitList.add("Peer");

finalList vegetableList =newList(4,true);

vegetableList.add("Lady Finger");
vegetableList.add("Onion");
vegetableList.add("Potato");
vegetableList.add("Tomato");

Button showButton =newButton("Show");

showButton.addActionListener(newActionListener(){

publicvoid actionPerformed(ActionEvent e){


String data ="Fruits Selected: "
+ fruitList.getItem(fruitList.getSelectedIndex());
data +=", Vegetables selected: ";
for(String vegetable:vegetableList.getSelectedItems()){
Dambal Sir (Sangola Collge,Sangola) 26
data += vegetable +" ";
}
statusLabel.setText(data);
}
});
controlPanel.add(fruitList);
controlPanel.add(vegetableList);
controlPanel.add(showButton);
mainFrame.setVisible(true);
}
}
Menu Bar
importjava.awt.*;
importjava.awt.event.*;
importjavax.swing.*;

publicclassJavaMenuBarExample implementsRunnable, ActionListener


{
privateJFrame frame;
privateJMenuBar menuBar;
privateJMenu fileMenu;
privateJMenu editMenu;
privateJMenuItem openMenuItem;
privateJMenuItem cutMenuItem;
privateJMenuItem copyMenuItem;
privateJMenuItem pasteMenuItem;

publicstaticvoidmain(String[] args)
{
// needed on mac os x
System.setProperty("apple.laf.useScreenMenuBar", "true");
// the proper way to show a jframe (invokeLater)
SwingUtilities.invokeLater(newJavaMenuBarExample());
}
publicvoidrun()
{
frame = newJFrame("Java Menubar Example");
menuBar = newJMenuBar();
// build the File menu
fileMenu = newJMenu("File");
openMenuItem = newJMenuItem("Open");
openMenuItem.addActionListener(this);
fileMenu.add(openMenuItem);
// build the Edit menu
editMenu = newJMenu("Edit");
cutMenuItem = newJMenuItem("Cut");
copyMenuItem = newJMenuItem("Copy");
pasteMenuItem = newJMenuItem("Paste");
editMenu.add(cutMenuItem);
editMenu.add(copyMenuItem);
editMenu.add(pasteMenuItem);
// add menus to menubar
menuBar.add(fileMenu);
menuBar.add(editMenu);
// put the menubar on the frame
frame.setJMenuBar(menuBar);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setPreferredSize(newDimension(400, 300));
Dambal Sir (Sangola Collge,Sangola) 27
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}

/**
* This handles the action for the File/Open event, and demonstrates
* the implementation of an ActionListener.
* In a real-world program you'd handle this differently.
*/
publicvoidactionPerformed(ActionEvent ev)
{
SampleDialog dialog = newSampleDialog();
dialog.setModal(true);
dialog.setVisible(true);
}

/**
* This dialog is displayed when the user selects the File/Open menu item.
*/
privateclassSampleDialog extendsJDialog implementsActionListener
{
privateJButton okButton = newJButton("OK");

privateSampleDialog()
{
super(frame, "Sample Dialog", true);
JPanel panel = newJPanel(newFlowLayout());
panel.add(okButton);
getContentPane().add(panel);
okButton.addActionListener(this);
setPreferredSize(newDimension(300, 200));
pack();
setLocationRelativeTo(frame);
}
publicvoidactionPerformed(ActionEvent ev)
{
setVisible(false);
}
}
}
LayoutManagers:
The LayoutManagers are used to arrange components in a particular manner.
LayoutManager is an interface that is implemented by all the classes of layout
managers. There are following classes that represents the layout managers:
1. java.awt.BorderLayout
2. java.awt.FlowLayout
3. java.awt.GridLayout
4. java.awt.CardLayout
5. java.awt.GridBagLayout
6. javax.swing.BoxLayout
7. javax.swing.GroupLayout
8. javax.swing.ScrollPaneLayout
9. javax.swing.SpringLayout etc.
BorderLayout:
The BorderLayout is used to arrange the components in five regions: north, south,
east, west and center. Each region (area) may contain one component only. It is the
default layout of frame or window. The BorderLayout provides five constants for
each region:
Dambal Sir (Sangola Collge,Sangola) 28
1. public static final int NORTH
2. public static final int SOUTH
3. public static final int EAST
4. public static final int WEST
5. public static final int CENTER
Constructors of BorderLayout class:
 BorderLayout(): creates a border layout but with no gaps between the
components.
 JBorderLayout(int hgap, int vgap): creates a border layout with the given
horizontal and vertical gaps between the components.

Example of BorderLayout class:


import java.awt.*;
import javax.swing.*;
public class Border {
JFrame f;
Border(){
f=new JFrame();
JButton b1=new JButton("NORTH");;
JButton b2=new JButton("SOUTH");;
JButton b3=new JButton("EAST");;
JButton b4=new JButton("WEST");;
JButton b5=new JButton("CENTER");;
f.add(b1,BorderLayout.NORTH);
f.add(b2,BorderLayout.SOUTH);
f.add(b3,BorderLayout.EAST);
f.add(b4,BorderLayout.WEST);
f.add(b5,BorderLayout.CENTER);
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new Border();
}
}
GridLayout
The GridLayout is used to arrange the components in rectangular grid. One
component is displayed in each rectangle.
Constructors of GridLayout class:
1. GridLayout(): creates a grid layout with one column per component in a
row.
2. GridLayout(int rows, int columns): creates a grid layout with the given
rows and columns but no gaps between the components.
3. GridLayout(int rows, int columns, int hgap, int vgap): creates a grid
layout with the given rows and columns alongwith given horizontal and
vertical gaps.

Dambal Sir (Sangola Collge,Sangola) 29


Example of GridLayout class:
import java.awt.*;
import javax.swing.*;
public class MyGridLayout{
JFrame f;
MyGridLayout(){
f=new JFrame();
JButton b1=new JButton("1");
JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");
JButton b6=new JButton("6");
JButton b7=new JButton("7");
JButton b8=new JButton("8");
JButton b9=new JButton("9");
f.add(b1);f.add(b2);f.add(b3);f.add(b4);f.add(b5);
f.add(b6);f.add(b7);f.add(b8);f.add(b9);
f.setLayout(new GridLayout(3,3));
//setting grid layout of 3 rows and 3 columns
f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyGridLayout();
} }
FlowLayout
The FlowLayout is used to arrange the components in a line, one after another (in a
flow). It is the default layout of applet or panel.
Fields of FlowLayout class:
1. public static final int LEFT
2. public static final int RIGHT
3. public static final int CENTER
4. public static final int LEADING
5. public static final int TRAILING
Constructors of FlowLayout class:
1. FlowLayout(): creates a flow layout with centered alignment and a default 5
unit horizontal and vertical gap.
2. FlowLayout(int align): creates a flow layout with the given alignment and a
default 5 unit horizontal and vertical gap.
3. FlowLayout(int align, int hgap, int vgap): creates a flow layout with the
given alignment and the given horizontal and vertical gap.

Example of FlowLayout class:

Dambal Sir (Sangola Collge,Sangola) 30


import java.awt.*;
import javax.swing.*;

public class MyFlowLayout{


JFrame f;
MyFlowLayout(){
f=new JFrame();

JButton b1=new JButton("1");


JButton b2=new JButton("2");
JButton b3=new JButton("3");
JButton b4=new JButton("4");
JButton b5=new JButton("5");

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

f.setLayout(new FlowLayout(FlowLayout.RIGHT));
//setting flow layout of right alignment

f.setSize(300,300);
f.setVisible(true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}
BoxLayout class
The BoxLayout is used to arrange the components either vertically or horizontally.
For this purpose, BoxLayout provides four constants. They are as follows:
Note: BoxLayout class is found in javax.swing package.
Fields of BoxLayout class:
1. public static final int X_AXIS
2. public static final int Y_AXIS
3. public static final int LINE_AXIS
4. public static final int PAGE_AXIS
Constructor of BoxLayout class:
1. BoxLayout(Container c, int axis): creates a box layout that arranges the
components with the given axis.

Example of BoxLayout class with Y-AXIS:

Dambal Sir (Sangola Collge,Sangola) 31


import java.awt.*;
import javax.swing.*;
public class BoxLayoutExample1 extends Frame {
Button buttons[];
public BoxLayoutExample1 () {
buttons = new Button [5];
for (int i = 0;i<5;i++) {
buttons[i] = new Button ("Button " + (i + 1));
add (buttons[i]);
}
setLayout (new BoxLayout (this, BoxLayout.Y_AXIS));
setSize(400,400);
setVisible(true);
}
public static void main(String args[]){
BoxLayoutExample1 b=new BoxLayoutExample1();
}
}
CardLayout class
The CardLayout class manages the components in such a manner that only one
component is visible at a time. It treats each component as a card that is why it is
known as CardLayout.
Constructors of CardLayout class:
1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
2. CardLayout(int hgap, int vgap): creates a card layout with the given
horizontal and vertical gap.
Commonly used methods of CardLayout class:
 public void next(Container parent): is used to flip to the next card of the
given container.
 public void previous(Container parent): is used to flip to the previous card
of the given container.
 public void first(Container parent): is used to flip to the first card of the
given container.
 public void last(Container parent): is used to flip to the last card of the
given container.
 public void show(Container parent, String name): is used to flip to the
specified card with the given name.
Example of CardLayout class:

Dambal Sir (Sangola Collge,Sangola) 32


import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class CardLayoutExample extends JFrame implements ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
c.setLayout(card);
b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c.add("a",b1);c.add("b",b2);c.add("c",b3);
}
public void actionPerformed(ActionEvent e) {
card.next(c);
}
public static void main(String[] args) {
CardLayoutExample cl=new CardLayoutExample();
cl.setSize(400,400);
cl.setVisible(true);
cl.setDefaultCloseOperation(EXIT_ON_CLOSE); } }

Dambal Sir (Sangola Collge,Sangola) 33


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 javax.swing 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-dependent. Java swing components are
platform-independent.
2) AWT components are heavyweight. Swing components are
lightweight.
3) AWT doesn't support pluggable look and Swing supports pluggable look
feel. and feel.
4) AWT provides less components than Swing provides more powerful
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.
Main Features of Swing Toolkit
1. Platform Independent
2. Customizable
3. Extensible
4. Configurable
5. Lightweight
6. Rich Controls
7. Pluggable Look and Feel
What is JFC
The Java Foundation Classes (JFC) are a set of GUI components which simplify the
development of desktop applications.
Features of JFC
 Swing GUI components.
 Look and Feel support.
 Java 2D.
Swing and JFC
JFC is an abbreviation for Java Foundation classes, which encompass a
group of features for building Graphical User Interfaces(GUI) and adding
rich graphical functionalities and interactivity to Java applications. Java
Swing is a part of Java Foundation Classes (JFC).
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 sets size of the component.
height)
public void sets the layout manager for the component.
setLayout(LayoutManager m)
public void setVisible(boolean b) sets the visibility of the component. It is by
default false.
Dambal Sir (Sangola Collge,Sangola) 34
Hierarchy of Java Swing classes

Introduction to Swing Classes

JPanel : JPanel is Swing's version of AWT class Panel and uses the same default
layout, FlowLayout. JPanel is descended directly from JComponent.
JFrame : JFrame is Swing's version of Frame and is descended directly
from Frame class. The component which is added to the Frame, is
refered as its Content.
JWindow : This is Swing's version of Window and has descended directly
from Window class. Like Window it uses BorderLayout by default.
JLabel : JLabel has descended from JComponent, and is used to create text labels.
JButton : JButton class provides the functioning of push button. JButton allows
an icon, string or both associated with a button.

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

Java Swing Examples


There are two ways to create a frame:
 By creating the object of Frame class (association)
 By extending Frame class (inheritance)
We can write the code of swing inside the main(), constructor or any other method.

Simple Java Swing Example


Let's see a simple swing example where we are creating one button and adding it on
the JFrame object inside the main() method.
File: FirstSwingExample.java
import javax.swing.*;
public class FirstSwingExample {
public static void main(String[] args) {
JFrame f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);//x axis, y axis, width, height
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
} }
Example of Swing by Association inside constructor
We can also write all the codes of creating JFrame, JButton and method call inside
the java constructor.
File: Simple.java
import javax.swing.*;
public class Simple {
JFrame f;
Simple(){

Dambal Sir (Sangola Collge,Sangola) 35


f=new JFrame();//creating instance of JFrame
JButton b=new JButton("click");//creating instance of JButton
b.setBounds(130,100,100, 40);
f.add(b);//adding button in JFrame
f.setSize(400,500);//400 width and 500 height
f.setLayout(null);//using no layout managers
f.setVisible(true);//making the frame visible
}
public static void main(String[] args) {
new Simple();
}
}
The setBounds(int xaxis, int yaxis, int width, int height)is used in the above
example that sets the position of the button.
Simple example of Swing by inheritance
We can also inherit the JFrame class, so there is no need to create the instance of
JFrame class explicitly.
File: Simple2.java
import javax.swing.*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click");//create button
b.setBounds(130,100,100, 40);
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) {
new Simple2();
}}

Dambal Sir (Sangola Collge,Sangola) 36


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.

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

import java.awt.event.*;
import javax.swing.*;
public class ButtonExample {
public static void main(String[] args) {
JFrame f=new JFrame("Button Example");
final JTextField tf=new JTextField();
tf.setBounds(50,50, 150,20);
JButton b=new JButton("Click Here");
b.setBounds(50,100,95,30);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e){
tf.setText("Welcome to Sangola.");
}
});
f.add(b);f.add(tf);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
}
Java JTextField
The object of a JTextField class is a text component that allows the editing of a
single line text. It inherits JTextComponent class.
public class JTextField extends JTextComponent implements SwingConstant
s
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, int Creates a new TextField initialized with the
columns) specified text and columns.
Dambal Sir (Sangola Collge,Sangola) 37
JTextField(int columns) Creates a new empty TextField with the specified
number of columns.
Commonly used Methods:
Methods Description
void addActionListener(ActionListener It is used to add the specified action
listener to receive action 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 It is used to remove the specified action
removeActionListener(ActionListener l) listener so that it no longer receives action
events from this textfield.

import javax.swing.*;
import java.awt.event.*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
tf1.setBounds(50,50,150,20);
tf2=new JTextField();
tf2.setBounds(50,100,150,20);
tf3=new JTextField();
tf3.setBounds(50,150,150,20);
tf3.setEditable(false);
b1=new JButton("+");
b1.setBounds(50,200,50,50);
b2=new JButton("-");
b2.setBounds(120,200,50,50);
b1.addActionListener(this);
b2.addActionListener(this);
f.add(tf1);f.add(tf2);f.add(tf3);f.add(b1);f.add(b2);
f.setSize(300,300);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
String s1=tf1.getText();
String s2=tf2.getText();
int a=Integer.parseInt(s1);
int b=Integer.parseInt(s2);
int c=0;
if(e.getSource()==b1){
c=a+b;
}else if(e.getSource()==b2){
c=a-b;
}
String result=String.valueOf(c);
tf3.setText(result);
}
public static void main(String[] args) {
new TextFieldExample();
}}

Dambal Sir (Sangola Collge,Sangola) 38


Java JTextArea
The object of a JTextArea class is a multi line region that displays text. It allows the
editing of multiple line text. It inherits JTextComponent class
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, int Creates a text area with the specified number of rows
column) and columns that displays no text initially.
JTextArea(String s, int row, Creates a text area with the specified number of rows
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 It is used to insert the specified text on the specified
position) position.
void append(String s) It is used to append the given text to the end of the
document.
import javax.swing.*;
import java.awt.event.*;
public class TextAreaExample implements ActionListener{
JLabel l1,l2;
JTextArea area;
JButton b;
TextAreaExample() {
JFrame f= new JFrame();
l1=new JLabel();
l1.setBounds(50,25,100,30);
l2=new JLabel();
l2.setBounds(160,25,100,30);
area=new JTextArea();
area.setBounds(20,75,250,200);
b=new JButton("Count Words");
b.setBounds(100,300,120,30);
b.addActionListener(this);
f.add(l1);f.add(l2);f.add(area);f.add(b);
f.setSize(450,450);
f.setLayout(null);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e){
String text=area.getText();
String words[]=text.split("\\s");
l1.setText("Words: "+words.length);
l2.setText("Characters: "+text.length());
}
public static void main(String[] args) {
new TextAreaExample();
}
}

Dambal Sir (Sangola Collge,Sangola) 39


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.
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
boolean selected) whether or not it is initially selected.
JCheckBox(Action a) Creates a check box where properties are taken
from the Action supplied.

Commonly used Methods:


Methods Description
AccessibleContext It is used to get the AccessibleContext
getAccessibleContext() associated with this JCheckBox.
protected String paramString() It returns a string representation of this
JCheckBox.

import javax.swing.*;
import java.awt.event.*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
checkbox1.setBounds(150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
checkbox2.setBounds(150,150, 50,50);
f.add(checkbox1); f.add(checkbox2); f.add(label);
checkbox1.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("C++ Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
checkbox2.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent e) {
label.setText("Java Checkbox: "
+ (e.getStateChange()==1?"checked":"unchecked"));
}
});
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}
Dambal Sir (Sangola Collge,Sangola) 40
Java JRadioButton

The JRadioButton class is used to create a radio button. It is used to choose one
option from multiple options. It is widely used in exam systems or quiz.
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
selected) and 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(ActionListener It is used to add the action listener to this
a) object.
Example.
import javax.swing.*;
import java.awt.event.*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){
rb1=new JRadioButton("Male");
rb1.setBounds(100,50,100,30);
rb2=new JRadioButton("Female");
rb2.setBounds(100,100,100,30);
ButtonGroup bg=new ButtonGroup();
bg.add(rb1);bg.add(rb2);
b=new JButton("click");
b.setBounds(100,150,80,30);
b.addActionListener(this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if(rb1.isSelected()){
JOptionPane.showMessageDialog(this,"You are Male.");
}
if(rb2.isSelected()){
JOptionPane.showMessageDialog(this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}
Dambal Sir (Sangola Collge,Sangola) 41
Java JComboBox

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

public class JComboBox extends JComponent implements ItemSelectable, Li


stDataListener, ActionListener, Accessible
Commonly used Constructors:
Constructor Description
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<?> Creates a JComboBox that contains the elements in
items) 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 It is used to add the ActionListener.
addActionListener(ActionListener a)
void addItemListener(ItemListener i) It is used to add the ItemListener.

Java JComboBox Example with ActionListener

import javax.swing.*;
import java.awt.event.*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
final JLabel label = new JLabel();
label.setHorizontalAlignment(JLabel.CENTER);
label.setSize(400,100);
JButton b=new JButton("Show");
b.setBounds(200,100,75,20);
String languages[]={"C","C++","C#","Java","PHP"};
final JComboBox cb=new JComboBox(languages);
cb.setBounds(50, 100,90,20);
f.add(cb); f.add(label); f.add(b);
f.setLayout(null);
f.setSize(350,350);
f.setVisible(true);
b.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String data = "Programming language Selected: "
+ cb.getItemAt(cb.getSelectedIndex());
label.setText(data);
}
});
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

Dambal Sir (Sangola Collge,Sangola) 42


Java JTable

The JTable class is used to display data in tabular form. It is composed of rows and
columns.
Commonly used Constructors:
Constructor Description
JTable() Creates a table with empty cells.
JTable(Object[][] rows, Object[] columns) Creates a table with the specified 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();
}
}
Java JTable Example with ListSelectionListener
import javax.swing.*;
import javax.swing.event.*;
public class TableExample {
public static void main(String[] a) {
JFrame f = new JFrame("Table Example");
String data[][]={ {"101","Amit","670000"},
{"102","Jai","780000"},
{"101","Sachin","700000"}};
String column[]={"ID","NAME","SALARY"};
final JTable jt=new JTable(data,column);
jt.setCellSelectionEnabled(true);
ListSelectionModel select= jt.getSelectionModel();
select.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
select.addListSelectionListener(new ListSelectionListener() {
public void valueChanged(ListSelectionEvent e) {
String Data = null;
int[] row = jt.getSelectedRows();
int[] columns = jt.getSelectedColumns();
for (int i = 0; i < row.length; i++) {
for (int j = 0; j < columns.length; j++) {
Data = (String) jt.getValueAt(row[i], columns[j]);
}}
System.out.println("Table element selected is: " + Data);
}
});
JScrollPane sp=new JScrollPane(jt);
f.add(sp);
f.setSize(300, 200);
f.setVisible(true);
Dambal Sir (Sangola Collge,Sangola) 43
}
}
If you select an element in column NAME, name of the element will be displayed on
the console:
Java JOptionPane
The JOptionPane class is used to provide standard dialog boxes such as message
dialog box, confirm dialog box and input dialog box. These dialog boxes are used to
display information or get input from the user. The JOptionPane class inherits
JComponent class.
Common Constructors of JOptionPane class
Constructor Description
JOptionPane() It is used to create a JOptionPane with a test
message.
JOptionPane(Object message) It is used to create an instance of JOptionPane to
display a message.
JOptionPane(Object message, It is used to create an instance of JOptionPane to
int messageType display a message with specified message type and
default options.

Common Methods of JOptionPane class

Methods Description
JDialog createDialog(String title) It is used to create and return a
new parentless JDialog with the
specified title.
static void showMessageDialog(Component It is used to create an information-
parentComponent, Object message) message dialog titled "Message".
static void showMessageDialog(Component It is used to create a message
parentComponent, Object message, String dialog with given title and
title, int messageType) messageType.
static int showConfirmDialog(Component It is used to create a dialog with
parentComponent, Object message) the options Yes, No and Cancel;
with the title, Select an Option.
static String showInputDialog(Component It is used to show a question-
parentComponent, Object message) message dialog requesting input
from the user parented to
parentComponent.
void setInputValue(Object newValue) It is used to set the input value
that was selected or input by the
user.

Java JOptionPane Example: showMessageDialog()

import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Hello, Welcome to Sangola.");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Java JOptionPane Example: showMessageDialog()

import javax.swing.*;
Dambal Sir (Sangola Collge,Sangola) 44
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
JOptionPane.showMessageDialog(f,"Successfully Updated.","Alert",JOptionPa
ne.WARNING_MESSAGE);
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Java JOptionPane Example: showInputDialog()

import javax.swing.*;
public class OptionPaneExample {
JFrame f;
OptionPaneExample(){
f=new JFrame();
String name=JOptionPane.showInputDialog(f,"Enter Name");
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Java JOptionPane Example: showConfirmDialog()

import javax.swing.*;
import java.awt.event.*;
public class OptionPaneExample extends WindowAdapter{
JFrame f;
OptionPaneExample(){
f=new JFrame();
f.addWindowListener(this);
f.setSize(300, 300);
f.setLayout(null);
f.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
f.setVisible(true);
}
public void windowClosing(WindowEvent e) {
int a=JOptionPane.showConfirmDialog(f,"Are you sure?");
if(a==JOptionPane.YES_OPTION){
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
public static void main(String[] args) {
new OptionPaneExample();
}
}

Java JMenuBar, JMenu and JMenuItem

The JMenuBar class is used to display menubar on the window or frame. It may
have several menus.The object of JMenu class is a pull down menu component
which is displayed from the menu bar. It inherits the JMenuItem class.The object
of JMenuItem class adds a simple labeled menu item. The items used in a menu
must belong to the JMenuItem or any of its subclass.
JMenuBar class declaration
Dambal Sir (Sangola Collge,Sangola) 45
public class JMenuBar extends JComponent implements MenuElement, Accessible

JMenu class declaration


public class JMenu extends JMenuItem implements MenuElement, Accessible
JMenuItem class declaration
public class JMenuItem extends AbstractButton implements Accessible, MenuElem
ent

Java JMenuItem and JMenu Example


import javax.swing.*;
class MenuExample
{
JMenu menu, submenu;
JMenuItem i1, i2, i3, i4, i5;
MenuExample(){
JFrame f= new JFrame("Menu and MenuItem Example");
JMenuBar mb=new JMenuBar();
menu=new JMenu("Menu");
submenu=new JMenu("Sub Menu");
i1=new JMenuItem("Item 1");
i2=new JMenuItem("Item 2");
i3=new JMenuItem("Item 3");
i4=new JMenuItem("Item 4");
i5=new JMenuItem("Item 5");
menu.add(i1); menu.add(i2); menu.add(i3);
submenu.add(i4); submenu.add(i5);
menu.add(submenu);
mb.add(menu);
f.setJMenuBar(mb);
f.setSize(400,400);
f.setLayout(null);
f.setVisible(true);
}
public static void main(String args[])
{
new MenuExample(); }}

Example of creating Edit menu for Notepad:

import javax.swing.*;
import java.awt.event.*;
public class MenuExample implements ActionListener{
JFrame f;
JMenuBar mb;
JMenu file,edit,help;
JMenuItem cut,copy,paste,selectAll;
JTextArea ta;
MenuExample(){
f=new JFrame();
cut=new JMenuItem("cut");
copy=new JMenuItem("copy");
paste=new JMenuItem("paste");
selectAll=new JMenuItem("selectAll");
cut.addActionListener(this);
copy.addActionListener(this);
paste.addActionListener(this);
selectAll.addActionListener(this);
mb=new JMenuBar();
file=new JMenu("File");
Dambal Sir (Sangola Collge,Sangola) 46
edit=new JMenu("Edit");
help=new JMenu("Help");
edit.add(cut);edit.add(copy);edit.add(paste);edit.add(selectAll);
mb.add(file);mb.add(edit);mb.add(help);
ta=new JTextArea();
ta.setBounds(5,5,360,320);
f.add(mb);f.add(ta);
f.setJMenuBar(mb);
f.setLayout(null);
f.setSize(400,400);
f.setVisible(true);
}
public void actionPerformed(ActionEvent e) {
if(e.getSource()==cut)
ta.cut();
if(e.getSource()==paste)
ta.paste();
if(e.getSource()==copy)
ta.copy();
if(e.getSource()==selectAll)
ta.selectAll();
}
public static void main(String[] args) {
new MenuExample();
}}

Java JProgressBar

The JProgressBar class is used to display the progress of the task. It inherits
JComponent class.
Commonly used Constructors:
Constructor Description
JProgressBar() It is used to create a horizontal progress bar but no string
text.
JProgressBar(int It is used to create a horizontal progress bar with the
min, int max) specified minimum and maximum value.
JProgressBar(int It is used to create a progress bar with the specified
orient) orientation, it can be either Vertical or Horizontal by using
SwingConstants.VERTICAL and
SwingConstants.HORIZONTAL constants.
JProgressBar(int It is used to create a progress bar with the specified
orient, int min, int orientation, minimum and maximum value.
max)
Commonly used Methods:
Method Description
void setStringPainted(boolean It is used to determine whether string should be
b) displayed.
void setString(String s) It is used to set value to the progress string.
void setOrientation(int It is used to set the orientation, it may be either
orientation) 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;
Dambal Sir (Sangola Collge,Sangola) 47
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();
}
}
Java JTree
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.
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 as
value) the child of a new root node.
JTree(TreeNode Creates a JTree with the specified TreeNode as its root, which
root) 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);
}
Dambal Sir (Sangola Collge,Sangola) 48
public static void main(String[] args)
{
new TreeExample();
}}

Java JTabbedPane

The JTabbedPane 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.
Commonly used Constructors:
Constructor Description
JTabbedPane() Creates an empty TabbedPane with a default tab
placement of JTabbedPane.Top.
JTabbedPane(int tabPlacement) Creates an empty TabbedPane with a specified
tab placement.
JTabbedPane(int tabPlacement, Creates an empty TabbedPane with a specified
int tabLayoutPolicy) tab placement and tab layout 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();
}}
Java JFileChooser
The object of JFileChooser class represents a dialog window from which the user
can select file. It inherits JComponent class.

Commonly used Constructors:


Constructor Description
JFileChooser() Constructs a JFileChooser pointing to the
user's default directory.
JFileChooser(File Constructs a JFileChooser using the given File
currentDirectory) as the path.
JFileChooser(String Constructs a JFileChooser using the given
currentDirectoryPath) path.

Dambal Sir (Sangola Collge,Sangola) 49


Java JFileChooser 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);
} }

Dambal Sir (Sangola Collge,Sangola) 50

You might also like