0% found this document useful (0 votes)
1 views65 pages

Java Notes (3) in PDF Form

Contains all five units

Uploaded by

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

Java Notes (3) in PDF Form

Contains all five units

Uploaded by

rjeevitha
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

generator's sequence

Returns the next pseudorandom Gaussian double value with


nextGaussian() mean 0.0 and standard deviation 1.0 from this random number
generator's sequence.

Returns a uniformly distributed pseudorandom int value


nextInt()
generated from this random number generator's sequence

Returns the next uniformly distributed pseudorandom long


nextLong()
value from the random number generator's sequence.

Sets the seed of this random number generator using a single


setSeed()
long seed.

Example:

import [Link];
public class JavaRandomExample1 {
public static void main(String[] args) {
//create random object
Random random= new Random();
//returns unlimited stream of pseudorandom long values
[Link]("Longs value : "+[Link]());
// Returns the next pseudorandom boolean value
boolean val = [Link]();
[Link]("Random boolean value : "+val);
byte[] bytes = new byte[10];
//generates random bytes and put them in an array
[Link](bytes);
[Link]("Random bytes = ( ");
for(int i = 0; i< [Link]; i++)
{
[Link]("%d ", bytes[i]);
}
[Link](")");
}
}

209
Output:

Longs value : [Link]$Head@50cbc42f


Random boolean value : false
Random bytes = ( -127 74 73 -22 -49 -38 -103 15 -27 -64 )

Formatter

 With the release of JDK 5, Java added a capability long desired by


programmers.
 Java has offered a rich and varied API, but it had not always offered an
easy way to create formatted text output, especially for numericvalues.

 Classes such as NumberFormat, DateFormat, and MessageFormat


provided by earlier versions of Java do have useful formatting
capabilities, but they were not especially convenient to use.

 At the core of Java’s support for creating formatted output is the


Formatter class. It provides format conversions that let you display
numbers, strings, and time and date in virtually any format you like. It
operates in a manner similar to the C/C++ printf( ) function, which
means that if you are familiar with C/C++, then learning to use
Formatter will be very easy. It also further streamlines the conversion of
C/C++ code to Java. If you are not familiar with C/C++, it is still quite
easy to format data.

Constructors

The Formatter class defines many constructors, which enable you to construct
a Formatter in a variety of ways. Here is a sampling:

Formatter( )
Formatter(Appendable buf)
Formatter(Appendable buf, Locale loc)
Formatter(String filename)
throws FileNotFoundException
Formatter(String filename, String charset)
throws FileNotFoundException, UnsupportedEncodingException
Formatter(File outF)
throws FileNotFoundException
Formatter(OutputStream outStrm)

210
Formatting Numbers

 To format an integer in decimal format, use %d. To format a floating-


point value in decimal format, use %f.
 To format a floating-point value in scientific notation, use %e. Numbers

 represented in scientific notation take this general form:

 [Link]+/–yy

 The %g format specifier causes Formatter to use either %f or %e,


whichever is shorter.

 The following program demonstrates the effect of the %g format specifier:

Example:
// Demonstrate the %g format specifier.
import [Link].*;
class FormatDemo2 {
public static void main(String args[]) {
Formatter fmt = new Formatter();
for(double i=1000; i < 1.0e+10; i *= 100) {
[Link]("%g ", i);
[Link](fmt);
}
}
}

It produces the following output:


1000.000000
1000.000000 100000.000000
1000.000000 100000.000000 1.000000e+07
1000.000000 100000.000000 1.000000e+07 1.000000e+09

Scanner

 Scanner is the complement of Formatter. Added by JDK 5, Scanner


reads formatted input and converts it into its binary form.

 Although it has always been possible to read formatted input, it required


more effort than most programmers would prefer. Because of the
addition
 of Scanner, it is now easy to read all types of numeric values, strings,
and other types of data,

211
 whether it comes from a disk file, the keyboard, or another source.
 Scanner can be used to read input from the console, a file, a string, or
any source that implements the Readable interface or
ReadableByteChannel.

Examples

import [Link].*;
class AvgNums {
public static void main(String args[]) {
Scanner conin = new Scanner([Link]);
int count = 0;
double sum = 0.0;
[Link]("Enter numbers to average.");
// Read and sum numbers.
while([Link]()) {
if([Link]()) {
sum += [Link]();
count++;
}
else {
String str = [Link]();
if([Link]("done")) break;
else {
[Link]("Data format error.");
return;
}
}
}
[Link]("Average is " + sum / count);
}
}

OUTUT

Enter numbers to average.


1.2
2
3.4
4
done
Average is 2.65

212
UNIT-V
AWT
Limitations of AWT:
 The AWT defines a basic set of controls, windows, and dialog boxes that
support a usable, but limited graphical interface. One reason for the
limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents or
peers.
 This means that the look and feel of a component is defined by the
platform, not by java. Because the AWT components use native code
resources, they are referred to as heavy weight.
 The use of native peers led to several problems.
 First, because of variations between operating systems, a component
might look, or even act, differently on different platforms.
This variability threatened java’s philosophy: write once, run anywhere.
 Second, the look and feel of each component was fixed and could not be
changed.
 Third, the use of heavyweight components caused some frustrating
restrictions.
Due to these limitations Swing came and was integrated to java.
 Swing is built on the AWT.
 Two key Swing features are:
 Swing components are light weight,
 Swing supports a pluggable look and feel.

MVC architecture:

In general, a visual component is a composite of three distinct aspects:


• The way that the component looks when rendered on the screen
• The way that the component reacts to the user
• The state information associated with the component

Over the years, one component architecture has proven itself to be


exceptionally effective: Model-View-Controller, or MVC for short.

The MVC architecture is successful because each piece of the design


corresponds to an aspect of a component.

MVC
 The model corresponds to the state information associated with the
component. For example, in the case of a check box, the model contains
a field that indicates if the box is checked or unchecked.

213
 The view determines how the component is displayed on the screen,
including any aspects of the view that are affected by the current state of
the model.
 The controller determines how the component reacts to the user.

For example, when the user clicks a check box, the controller reacts by
changing the model to reflect the user’s choice (checked or unchecked). This
then results in the view being updated. By separating a component into a
model, a view, and a controller, the specific implementation of each can be
changed without affecting the other two. For instance, different view
implementations can render the same component in different ways without
affecting the model or the controller.

Awt (Abstract Window Tool Kit):

 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 [Link] package provides classes for AWT api such as TextField,
Label, TextArea, RadioButton, CheckBox, Choice, List etc.

Hierarchy of Java AWT classes:

214
Components & Containers of AWT:

215
The AWT defines windows according to a class hierarchy that adds
functionality and specificity with each level.

Container

The Container class is a subclass of Component. It has additional methods


that allow other Component objects to be nested within it. Other Container
objects can be stored inside of a Container (since they are themselves
instances of Component).

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.

Component
At the top of the AWT hierarchy is the Component class. Component is an
abstract class that encapsulates all of the attributes of a visual component. All
user interface elements that are displayed on the screen and that interact with
the user are subclasses of Component.

It defines over a hundred public methods that are responsible for managing
events, such as mouse and keyboard input, positioning and sizing the window,
and repainting.

Methods of Component ( FRAME / PANEL / WINDOW )


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

216
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.

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.

Frame

 Frame encapsulates what is commonly thought of as a “window.” It is a


subclass ofWindow and has a title bar, menu bar, borders, and resizing
corners.

 The Frame is the container that contain title bar and can have menu
bars. It can have other components like button, textfield etc.

 If you create a Frame object from within an applet, it will contain a


warning message, such as “Java Applet Window,” to the user that an
applet window has been created. This message warns users that the
window they see was started by an applet and not by software running
on their computer.
Panel

 The Panel is the container that doesn't contain title bar and menu bars.
It can have other components like button, textfield etc.

 The Panel class is a concrete subclass of Container. It doesn’t add any


new methods; it simply implements Container.

 A Panel may be thought of as a recursively nestable, concrete screen


component. Panel is the superclass for Applet. When screen output is
directed to an applet, it is drawn on the surface of a Panel object.

 A Panel is a window that does not contain a title bar, menu bar, or
border. This is why you don’t see these items when an applet is run
inside a browser. When you run an applet using an applet viewer, the
applet viewer provides the title and border.

217
Frame Windows in awt:

Frame’s constructors:

Frame f= new Frame( );


Frame f =new Frame(String title);

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)

extending Frame class creating the object of Frame class


(inheritance) (association)

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


class Frame1 extends Frame{
Frame1() class First2
{ {
Button b=new Button("click me"); First2()
{
[Link](30,100,80,30); Frame f=new Frame();

// setting button position in Button b=new Button("click me");


//setBounds(x,y,width,height)
[Link](30,50,80,30);
add(b);//adding button into frame
[Link](b);
setSize(300,300);//frame size 300 [Link](300,300);
width and 300 height [Link](null);
[Link](true);
setLayout(null);//no layout manager }
class FrameEx
setVisible(true);//now frame will be {
visible, by default not visible public static void main(String args[])
{
} First2 f=new First2();
class FrameEx
{ }} }
public static void main(String args[])
{
Frame1 f=new Frame1(); }}}

218
AWT Panel Example:

import [Link].*;
class PanelExample {
PanelExample()
{
Frame f= new Frame("Panel Example");

Panel panel=new Panel();


[Link](40,80,200,200); //setBounds(x,y,width,height)

[Link]([Link]);

Button b1=new Button("Button 1");


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

Button b2=new Button("Button 2");


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

[Link](b1); [Link](b2);

[Link](panel);
[Link](400,400);
[Link](null);//when we use setBounds() only layout must null
[Link](true);
}
}

public class pannelEx {


public static void main(String args[])
{
PanelExample pe= new PanelExample();
}
}

Output:

219
Swing

 Swing did not exist in the early days of Java.

 The AWT defines a basic set of controls, windows, and dialog boxes that
support a usable, but limited graphical [Link] reason for the
limited nature of the AWT is that it translates its various visual
components into their corresponding, platform-specific equivalents, or
peers.

 This means that the look and feel of a component is defined by the
platform, not by Java. Because the AWT components use native code
resources, they are referred to as heavyweight.

 This potential variability threatened the overarching philosophy of Java:


write once, run anywhere. the look and feel of each component was fixed
(because it is defined by the platform) and could not be (easily) changed.

 To Overcome above problem Swing was Introduced in 1997, Swing was


included as part of the Java Foundation Classes (JFC).

 Swing was initially available for use with Java 1.1 as a separate
library.

 However, beginning with Java 1.2, Swing (and the rest of the JFC) was
fully integrated into Java.

 although Swing eliminates a number of the limitations inherent in the


AWT, Swing does not replace it.

 Instead, Swing is built on the foundation of the AWT.

The hierarchy of java swing API is given below.

220
Components and Containers of swings :

Swing Components:
In general, Swing components are derived from the JComponent class.

All of Swing’s components are represented by classes defined within the


package [Link].

The following table shows the class names for Swing components (including
those used as containers).

221
JComponent provides the functionality that is common to all components. For
example, JComponent supports the pluggable look and feel. JComponent
inherits the AWT classes Container and Component.
Thus, a Swing component is built on and compatible with an AWT component.

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
setLayout(LayoutManager m) component.
sets the visibility of the component. It is
public void setVisible(boolean b)
by default false.

Swing Containers:

The first are top-level containers:

 JFrame, JApplet, JWindow, and JDialog. These containers do not


inherit JComponent. They do, however,inherit the AWT classes
Component and Container.

222
 Swing defines two types of containers. The one most commonly used for
applications is JFrame. The one used for applets is JApplet.

The second type of containers supported by Swing are lightweight


containers.
 Lightweight containers do inherit JComponent. An example of a
lightweight container is JPanel, which is a general-purpose container.

 Thus, you can use lightweight containers such as JPanel to create


subgroups of related controls that are contained within an outer
container.

JFrame Window in Swing:

The [Link] class is a type of container which inherits the


[Link] class. JFrame works like the main window where components
like labels, buttons, textfields are added to create a GUI.

Unlike Frame, JFrame has the option to hide or close the window with the help
of setDefaultCloseOperation(int) method.

Constructors
Constructor Description
It constructs a new frame that is initially
JFrame()
invisible.
It creates a Frame in the specified
JFrame(GraphicsConfiguration gc) GraphicsConfiguration of a screen device
and a blank title.
It creates a new, initially invisible Frame
JFrame(String title)
with the specified title.
It creates a JFrame with the specified title
JFrame(String title,
and the specified GraphicsConfiguration of
GraphicsConfiguration gc)
a screen device.

There are two ways to create a frame:

 By creating the object of Frame class (association)


 By extending Frame class (inheritance)

223
Java Swing Example Swing by Association inside
import [Link].*; constructor
public class FirstSwingExample { import [Link].*;
public static void main(String[] args) {
public class Simple {
JFrame f=new JFrame();//creating JFrame f;
instance of JFrame Simple(){
f=new JFrame();//creating instance
JButton b=new of JFrame
JButton("click");//creating instance
of JButton JButton b=new
[Link](130,100,100, 40);//x JButton("click");//creating instance
axis, y axis, width, height of JButton
[Link](130,100,100, 40); );//x
[Link](b);//adding button in JFrame axis, y axis, width, height

[Link](400,500);//400 width and


500 height [Link](b);//adding button in JFrame
[Link](null);//using no layout
managers [Link](400,500);//400 width and
[Link](true);//making the frame 500 height
visible [Link](null);//using no layout
} managers
} [Link](true);//making the frame
visible
}

public static void main(String[] args) {


new Simple();
}
}

Swing by inheritance
import [Link].*;
public class Simple2 extends JFrame{//inheriting JFrame
JFrame f;
Simple2(){
JButton b=new JButton("click"); //create button
[Link](130,100,100, 40); );//x axis, y axis, width, height
add(b);//adding button on frame
setSize(400,500);
setLayout(null);
setVisible(true);
}
public static void main(String[] args) { new Simple2(); }}

224
Output for all above 3 Programs:

Understanding Layout Managers

layout manager automatically arranges your controls within a window by using


some type of algorithm.

 Each Container object has a layout manager associated with it.


 A layout manager is an instance of any class that implements the
LayoutManager interface.
 The layout manager is set by the setLayout( ) method. If no call to
setLayout( ) is made, then the default layout manager is used.

Whenever a container is resized (or sized for the first time), the layout manager
is used to position each of the components within it.

The setLayout( ) method has the following general form:

void setLayout(LayoutManager layoutObj)

Here, layoutObj is a reference to the desired layout manager.

If you wish to disable the layout manager and position components


manually, pass null for layoutObj. If you do this, you will need to determine the
shape and position of each component manually, using the setBounds( )
method defined by Component.

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. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]

225
 [Link]

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.

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.

The first form creates the default layout, which centers components and leaves
five pixels of
space between each component. The second form lets you specify how each line
is aligned.
Valid values for how are as follows:

[Link]
[Link]
[Link]
[Link]
[Link]

Example for FlowLayout created in Swing:

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

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");

[Link](b1);[Link](b2);[Link](b3);[Link](b4);[Link](b5);

[Link](new FlowLayout([Link]));

226
//setting flow layout of right alignment

[Link](300,300);
[Link](true);
}
public static void main(String[] args) {
new MyFlowLayout();
}
}

Output:

 [Link]

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:

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

227
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 for BorderLayout // Demonstrate BorderLayout by


created in Swing: using applet.
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;
import [Link].*;
public class Border { /*
JFrame f; <applet
Border(){ code="BorderLayoutDemo"
f=new JFrame(); width=400 height=200>
</applet>
JButton b1=new */
JButton("NORTH");; public class BorderLayoutDemo
JButton b2=new extends Applet {
JButton("SOUTH");;
JButton b3=new JButton("EAST");; public void init()
JButton b4=new JButton("WEST");; {
JButton b5=new setLayout(new BorderLayout());
JButton("CENTER");; add(new Button("This is across the
top."),
[Link](b1,[Link]); [Link]);
[Link](b2,[Link]);
[Link](b3,[Link]); add(new Label("The footer message
[Link](b4,[Link]); might go here."),
[Link](b5,[Link]); [Link]);

[Link](300,300); add(new Button("Right"),


[Link](true); [Link]);
}
public static void main(String[] args) add(new Button("Left"),
{ [Link]);
new Border();
} String msg = "java is pure Object
} Oriented Programing ";

add(new TextArea(msg),
[Link]);
}}

228
Output: Output:

 [Link]

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.

Example for GridLayout created // Demonstrate GridLayout by


in Swing: using applet.
import [Link].*; // Demonstrate GridLayout
import [Link].*; import [Link].*;
import [Link].*;
public class MyGridLayout{ /*
JFrame f; <applet code="GridLayoutDemo"
MyGridLayout(){ width=300 height=200>
f=new JFrame(); </applet>
*/
JButton b1=new JButton("1"); public class GridLayoutDemo extends

229
JButton b2=new JButton("2"); Applet {
JButton b3=new JButton("3"); static final int n = 4;
JButton b4=new JButton("4"); public void init() {
JButton b5=new JButton("5"); setLayout(new GridLayout(n, n));
JButton b6=new JButton("6"); setFont(new Font("SansSerif",
JButton b7=new JButton("7"); [Link], 24));
JButton b8=new JButton("8"); for(int i = 0; i < n; i++) {
JButton b9=new JButton("9"); for(int j = 0; j < n; j++) {
int k = i * n + j;
[Link](b1);[Link](b2);[Link](b3); if(k > 0)
[Link](b4);[Link](b5); add(new Button("" + k));
[Link](b6);[Link](b7);[Link](b8);[Link](b9); }
}
[Link](new GridLayout(3,3)); }
//setting grid layout of 3 rows and 3
columns }

[Link](300,300); Output:
[Link](true);
}
public static void main(String[] args) {
new MyGridLayout();
}
}
Output:

230
 [Link]

The Java GridBagLayout class is used to align components vertically,


horizontally or along their baseline.

The components may not be of same size. Each GridBagLayout object


maintains a dynamic, rectangular grid of cells. Each component occupies one
or more cells known as its display area. Each component associates an
instance of GridBagConstraints. With the help of constraints object we arrange
component's display area on the grid. The GridBagLayout manages each
component's minimum and preferred sizes in order to determine component's
size.

The key to successfully using GridBagLayout is the proper setting of the


constraints,which are stored in a GridBagConstraints object.
GridBagConstraints defines several fields that you can set to govern the size,
placement, and spacing of a component.

Example for GridBagLayout created in Swing:

import [Link];
import [Link];
import [Link];

import [Link].*;
public class GridBagLayoutExample extends JFrame{
public static void main(String[] args) {
GridBagLayoutExample a = new GridBagLayoutExample();
}
public GridBagLayoutExample() {
GridBagLayoutgrid = new GridBagLayout();
GridBagConstraints gbc = new GridBagConstraints();
setLayout(grid);
setTitle("GridBag Layout Example");
GridBagLayout layout = new GridBagLayout();
[Link](layout);
[Link] = [Link];
[Link] = 0;
[Link] = 0;
[Link](new Button("Button One"), gbc);
[Link] = 1;
[Link] = 0;

231
[Link](new Button("Button two"), gbc);
[Link] = [Link];
[Link] = 20;
[Link] = 0;
[Link] = 1;
[Link](new Button("Button Three"), gbc);
[Link] = 1;
[Link] = 1;
[Link](new Button("Button Four"), gbc);
[Link] = 0;
[Link] = 2;
[Link] = [Link];
[Link] = 2;
[Link](new Button("Button Five"), gbc);
setSize(300, 300);
setPreferredSize(getSize());
setVisible(true);
setDefaultCloseOperation(EXIT_ON_CLOSE);

}
Output:

232
[Link]
 The CardLayout class is unique among the other layout managers in
that it stores severaldifferent layouts.
 Each layout can be thought of as being on a separate index card in a
deck that can be shuffled so that any card is on top at a given time.
 This can be useful for user interfaces with optional components that can
be dynamically enabled and disabled upon user input.
 You can prepare the other layouts and have them hidden, ready to be
activated when needed.
 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 for GridBagLayout created in Swing:

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

import [Link].*;

public class CardLayoutExample extends JFrame implements


ActionListener{
CardLayout card;
JButton b1,b2,b3;
Container c;
CardLayoutExample(){

233
c=getContentPane();
card=new CardLayout(40,30);
//create CardLayout object with 40 hor space and 30 ver space
[Link](card);

b1=new JButton("Apple");
b2=new JButton("Boy");
b3=new JButton("Cat");
[Link](this);
[Link](this);
[Link](this);

[Link]("a",b1);[Link]("b",b2);[Link]("c",b3);

}
public void actionPerformed(ActionEvent e) {
[Link](c);
}

public static void main(String[] args) {


CardLayoutExample cl=new CardLayoutExample();
[Link](400,400);
[Link](true);
[Link](EXIT_ON_CLOSE);
}
}

Output:

234
Event Handling:

 Event Handling is the mechanism that controls the event and decides
what should happen if an event occurs. This mechanism have the code
which is known as event handler that is executed when an event occurs.

 Changing the state of an object is known as an event. For example, click


on button, dragging mouse etc. The [Link] package provides
many event classes and Listener interfaces for event handling.

 These events are packaged in [Link]. Events specific to Swing


are stored in [Link].

 The event handling mechanism used by Swing is the same as that used
by the [Link] approach is called the delegation event model.

Java Uses the Delegation Event Model to handle the events. This model
defines the standard mechanism to generate and handle the events.

The Delegation Event Model has the following key participants namely:

 Source - The source is an object on which event occurs. Source is


responsible for providing information of the occurred event to it's
handler. Java provide as with classes for source object.
 Listener - It is also known as event handler. Listener is responsible for
generating response to an event. From java implementation point of view
the listener is also an object. Listener waits until it receives an event.
Once the event is received, the listener process the event and then
returns.

Event classes (EventName) and Listener interfaces

235
Adapter Classes

Java adapter classes provide the default implementation of listener interfaces. If


you inherit the adapter class, you will not be forced to provide the
implementation of all the methods of listener interfaces. So it saves code.

236
The adapter classes are found in [Link], [Link] and
[Link] packages. The Adapter classes with their corresponding
listener interfaces are

[Link] Adapter classes


Adapter class Listener interface

WindowAdapter WindowListener

KeyAdapter KeyListener

MouseAdapter MouseListener

MouseMotionAdapter MouseMotionListener

[Link] Adapter classes

Adapter class Listener interface


DragSourceAdapter DragSourceListener
DragTargetAdapter DragTargetListener

[Link] Adapter classes

Adapter class Listener interface


MouseInputAdapter MouseInputListener
InternalFrameAdapter InternalFrameListener

Keyboard Listener Example using with Keyboard Adapter Example


Swing
import [Link].*; import [Link].*;
import [Link].*; import [Link].*;
import [Link].*; public class KeyAdapterExample
class KeyEventEx implements extends KeyAdapter{

237
KeyListener{ Label l;
TextArea area;
public void keyPressed(KeyEvent ke) Frame f;
{ KeyAdapterExample(){
[Link]("Key Pressed f=new Frame("Key Adapter");
["+[Link]()+"]"); l=new Label();
} [Link](20,50,200,20);
public void keyReleased(KeyEvent ke) area=new TextArea();
{ [Link](20,80,300, 300);
[Link]("Key Released [Link](this);
["+[Link]()+"]");
} [Link](l);[Link](area);
public void keyTyped(KeyEvent ke) [Link](400,400);
{ [Link](null);
[Link]("Key Entered [Link](true);
["+[Link]()+"]"); }
} public void keyReleased(KeyEvent
e) {
} String text=[Link]();
class Myframe2 extends JFrame String words[]=[Link]("\\s");
{ [Link]("Words: "+[Link]+"
Myframe2() Characters:"+[Link]());
{ }
[Link](710,500);
[Link](true); public static void main(String[]
[Link]("MouseEvents"); args) {
//[Link](new FlowLayout()); new KeyAdapterExample();
getContentPane().setBackground(Colo }
[Link]); }
[Link](new KeyEventEx());
[Link](JFrame Output:
.EXIT_ON_CLOSE);
}
}
class KeyboardEvents
{
public static void main(String arg[])
{
Myframe2 f=new Myframe2();

238
}
}

Inner Classes

Recall that an inner class is a class defined within another class, or even within
an expression.

// Inner class demo.


import [Link].*;
import [Link].*;
/*
<applet code="InnerClassDemo" width=200 height=100>
</applet>
*/
public class InnerClassDemo extends Applet {

public void init()


{
addMouseListener(new MyMouseAdapter());
}

class MyMouseAdapter extends MouseAdapter {

public void mousePressed(MouseEvent me) {


showStatus("Mouse Pressed");
}

239
Here, InnerClassDemo is a top-level class that extends Applet.
MyMouseAdapter is an inner class that extends MouseAdapter. Because
MyMouseAdapter is defined within the scope of InnerClassDemo, it has
access to all of the variables and methods within the scope of that class.

Therefore, the mousePressed( ) method can call the showStatus( ) method


directly. It no longer needs to do this via a stored reference to the applet. Thus,
it is no longer necessary to pass MyMouseAdapter( ) a reference to the
invoking object.

Anonymous Inner Classes


An anonymous inner class is one that is not assigned a name. Consider the
applet shown in the following listing. As before, its goal is to display the string
“Mouse Pressed” in the status bar of the applet viewer or browser when the
mouse is pressed.

// Anonymous inner class demo.


import [Link].*;
import [Link].*;
/*
<applet code="AnonymousInnerClassDemo" width=200 height=100>
</applet>
*/
public class AnonymousInnerClassDemo extends Applet {
public void init() {
addMouseListener(new MouseAdapter() {
public void mousePressed(MouseEvent me) {
showStatus("Mouse Pressed");
}
});
}
}

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.
 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. were created with the standard applet

240
viewer, called appletviewer, provided by the JDK. But we can use any
applet viewer or browser we like.

 Execution of an applet does not begin at main( ).

 Output to our applet’s window is not performed by


[Link]( ).

 Rather, in non-Swing applets, output is handled with various AWT


methods, such as drawString( ), which outputs a string to a specified
X,Y location. Input is also handled differently than in a console
application.

 To use an applet, it is specified in an HTMLfile. One way to do this is by


using the APPLET tag.

 The applet will be executed by a Java-enabled web browser when it


encounters the APPLET tag within the HTMLfile. 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.

 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.

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

Two Types of Applets

241
 The first are those based directly on the Applet class 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.

Lifecycle methods for Applet:

The [Link] class 4 life cycle methods and [Link] class


provides 1 life cycle methods for an applet.

[Link] class

For creating any applet [Link] 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.

[Link] 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.

run an Applet?

There are two ways to run an applet

242
1. By html file.
2. By appletViewer tool (for testing purpose).

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.

//[Link]
import [Link];
import [Link];
public class First extends Applet{

public void paint(Graphics g){


[Link]("welcome",150,150);
}

[Link]

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

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
[Link]. Now Html file is not required but it is for testing purpose only.

//[Link]
import [Link];
import [Link];
public class First extends Applet{

public void paint(Graphics g){


[Link]("welcome to applet",150,150);
}

}
/*
243
<applet code="[Link]" width="300" height="300">
</applet>
*/

To execute the applet by appletviewer tool, write in command prompt:

c:\>javac [Link]
c:\>appletviewer [Link]

Passing Parameters to Applets

the APPLET tag in HTML allows you to pass parameters to your applet.
To retrieve a parameter, use the getParameter( ) method. It returns the value
of the specified parameter in the form of a String object. Thus, for numeric and
boolean values, you will need to convert their string representations into their
internal formats. Here is an example that demonstrates passing parameters:

Example 1:
/*
<applet code="MyApplet" height="300" width="500">
<param name="name" value="Ramesh" />
<param name="age" value="25" />
</applet>
*/

import [Link].*;
public class MyApplet extends Applet
{
String n;
String a;
public void init()
{
n = getParameter("name");
a = getParameter("age");
}
public void paint(Graphics g)
{
[Link]("Name is: " + n, 20, 20);
[Link]("Age is: " + a, 20, 40);
}
}

244
Creating a Swing Applet

Swing-based applets are similar to AWT-based applets, but with an important


difference: A Swing applet extends JApplet rather than Applet. JApplet is
derived from Applet. Thus, JApplet includes all of the functionality found in
Applet and adds support for Swing. JApplet is a top-level Swing container,
which means that it is not derived from JComponent.

Because JApplet is a top-level container, it includes the various panes


described earlier. This means that all components are added to JApplet’s
content pane in the same way that components are added to JFrame’s content
pane.

As we prefer Swing to AWT. Now we can use JApplet that can have all the controls of
swing. The JApplet class extends the Applet class.

Example:
/* <applet code="[Link]" width="300" height="300"> */

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

public class EventJApplet extends JApplet implements ActionListener{


JButton b;
JTextField tf;
public void init()
{

tf=new JTextField();
[Link](30,40,150,20);

b=new JButton("Click");
[Link](80,150,70,40);

add(b);add(tf);

245
[Link](this);

setLayout(null);
}

public void actionPerformed(ActionEvent e)


{
[Link]("Welcome");
}

}
Output:

In the above example, we have created all the controls in init() method because
it is invoked only once.

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

Painting in Swing

Painting Swing components is based on the AWT callback method, so it


supports the paint and repaint methods. Swing painting also extends the
functionality of paint operations with a number of additional features.

When the paint method is called, it is translated to all lightweight components


using the [Link] class's paint method. This causes all defined
areas to be repainted.

246
There are three customized callbacks for Swing components, which factor out a
single paint method into three subparts. These are

 paintComponent()
 paintBorder()
 paintChildren()

o paintComponent()
You use the paintComponent method to call the UI delegate object's
paint method. The paintComponent method passes a copy of the
Graphics object to the UI delegate object's paint method. This protects
the rest of the paint code from irrevocable changes.

You cannot call the paintComponent method if UI delegate is set to null.


o paintBorder()
You use the paintBorder method to paint a component's border.
o paintChildren()
You use the paintChildren method to paint a component's child
components.

Example:

import [Link].*;
import [Link].*;
import [Link].*;
public class paintSwing extends Applet implements MouseMotionListener{

public void init(){


addMouseMotionListener(this);
setBackground([Link]);
}

public void mouseDragged(MouseEvent me){


Graphics g=getGraphics();
[Link]([Link]);
[Link]([Link](),[Link](),5,5);
}
public void mouseMoved(MouseEvent me){}

}
Output:

247
Exploring Swing and Controls

JLabel :

The object of JLabel class is a component for placing text in a container. It is


used to display a single line of read only text. The text can be changed by an
application but a user cannot edit it directly. It inherits JComponent class.

Constructors:
Constructor Description
Creates a JLabel instance with no image and
JLabel()
with an empty string for the title.
Creates a JLabel instance with the specified
JLabel(String s)
text.
Creates a JLabel instance with the specified
JLabel(Icon i)
image.
JLabel(String s, Icon i, int Creates a JLabel instance with the specified
horizontalAlignment) text, image, and horizontal alignment.

Examople
In Swing In awt
import [Link].*; import [Link].*;
class LabelExample class LabelExample{
{ public static void main(String args[]){
public static void main(String args[]) Frame f= new Frame("Label
{ Example");
JFrame f= new JFrame("Label Label l1,l2;
Example"); l1=new Label("First Label.");
JLabel l1,l2; [Link](50,100, 100,30);

248
l1=new JLabel("First Label."); l2=new Label("Second Label.");
[Link](50,50, 100,30); [Link](50,150, 100,30);
l2=new JLabel("Second Label."); [Link](l1); [Link](l2);
[Link](50,100, 100,30); [Link](400,400);
[Link](l1); [Link](l2); [Link](null);
[Link](300,300); [Link](true);
[Link](null); }
[Link](true); }
}
}

Output:

ImageIcon

The class ImageIcon is an implementation of the Icon interface that paints


Icons from Images.

ImageIcon(String filename)

It obtains the image in the file named filename.

The icon and text associated with the label can be obtained by the following
methods:

Icon getIcon( )

String getText( )

The icon and text associated with a label can be set by these methods:

249
void setIcon(Icon icon)
void setText(String str)

Here, icon and str are the icon and text, respectively. Therefore, using setText(
) it is possible to change the text inside a label during program execution.

The following applet illustrates how to create and display a label containing
both an icon and a string. It begins by creating an ImageIcon object for the file
[Link], which depicts the flag for France. This is used as the second
argument to the JLabel constructor.

The first and last arguments for the JLabel constructor are the label text and
the alignment. Finally, the label is added to the content pane.

// Demonstrate JLabel and ImageIcon.


import [Link].*;
import [Link].*;
/*
<applet code="JLabelDemo" width=250 height=150>
</applet>
*/
public class JLabelDemo extends JApplet {
public void init() {
try {
[Link](
new Runnable() {
public void run() {
makeGUI();
}
}
);
} catch (Exception exc) {
[Link]("Can't create because of " + exc);
}
}
private void makeGUI() {
// Create an icon.
ImageIcon ii = new ImageIcon("[Link]");
// Create a label.
JLabel jl = new JLabel("France", ii, [Link]);
// Add the label to the content pane.
add(jl);
}
}

Output:
250
JTextField

JTextField is the simplest Swing text component. It is also probably its most
widely used text
component. JTextField allows you to edit one line of text. It is derived from
JTextComponent,
which provides the basic functionality common to Swing text components.
JTextField uses
the Document interface for its model.
Three of JTextField’s constructors are shown here:
Constructor Description
JTextField() Creates a new TextField
Creates a new TextField initialized with the
JTextField(String text)
specified text.
JTextField(String text, int Creates a new TextField initialized with the
columns) specified text and columns.
Creates a new empty TextField with the specified
JTextField(int columns)
number of columns.

Methods:
Methods Description
It is used to add the specified action
void addActionListener(ActionListener
listener to receive action events from
l)
this textfield.
It returns the currently set Action for
Action getAction() this ActionEvent source, or null if no
Action is set.
void setFont(Font f) It is used to set the current font.
It is used to remove the specified action
void
listener so that it no longer receives
removeActionListener(ActionListener l)
action events from this textfield.

251
Example:
import [Link].*;
class TextFieldExample
{
public static void main(String args[])
{
JFrame f= new JFrame("TextField Example");
JTextField t1,t2;
t1=new JTextField("Welcome to Java.");
[Link](50,100, 200,30);
t2=new JTextField("AWT ");
[Link](50,150, 200,30);
[Link](t1); [Link](t2);
[Link](400,400);
[Link](null);
[Link](true);
}
}
Output:

252
JTextField Example with ActionListener
(calculator)

import [Link].*;
import [Link].*;
public class TextFieldExample implements ActionListener{
JTextField tf1,tf2,tf3;
JButton b1,b2;
TextFieldExample(){
JFrame f= new JFrame();
tf1=new JTextField();
[Link](50,50,150,20);
tf2=new JTextField();
[Link](50,100,150,20);
tf3=new JTextField();
[Link](50,150,150,20);
[Link](false);
b1=new JButton("+");
[Link](50,200,50,50);
b2=new JButton("-");
[Link](120,200,50,50);
[Link](this);
[Link](this);
[Link](tf1);[Link](tf2);[Link](tf3);[Link](b1);[Link](b2);
[Link](300,300);
[Link](null);
[Link](true);
}
public void actionPerformed(ActionEvent e) {
String s1=[Link]();
String s2=[Link]();
int a=[Link](s1);
int b=[Link](s2);
int c=0;
if([Link]()==b1){
c=a+b;
}else if([Link]()==b2){
c=a-b;
}

253
String result=[Link](c);
[Link](result);
}
public static void main(String[] args) {
new TextFieldExample();
}}

Output:

The Swing Buttons


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.

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.

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

254
button.

It is used to enable or disable the


void setEnabled(boolean b)
button.

It is used to set the specified Icon on the


void setIcon(Icon b)
button.

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

It is used to set the mnemonic on the


void setMnemonic(int a)
button.

void addActionListener(ActionListener It is used to add the action listener to


a) this object.

Example:

import [Link].*;
import [Link].*;
import [Link].*;
class button extends JFrame implements ActionListener
{
JButton b1,b2,b3;
button()
{
[Link]("Swing window close operation");
[Link](400,400);
[Link](null);
[Link](true);
b1=new JButton("red");
b2=new JButton("blue");
b3=new JButton("green");
[Link]().setBackground([Link]);
[Link](JFrame.EXIT_ON_CLOSE);
[Link](b1);
[Link](50,50,100,50);
[Link](b2);
[Link](200,50,100,50);
[Link](b3);

255
[Link](350,50,100,50);

[Link](this);
[Link](this);
[Link](this);
}
public void actionPerformed(ActionEvent ae)
{
if([Link]()==b1)
{
getContentPane().setBackground([Link]);
}
if([Link]()==b2)
{
getContentPane().setBackground([Link]);
}
if([Link]()==b3)
{
getContentPane().setBackground([Link]);
}
}
}
class buttonEx
{
public static void main(String[] args) {
new button();
}
} OUTPUT:

JToggleButton

JToggleButton is used to create toggle button, it is two-states button to switch


on or off.

256
A toggle button looks just like a push button, but it acts differently because it
has two states: pushed and released. That is, when you press a toggle button,
it stays pressed rather than popping back up as a regular push button does.
When you press the toggle button a second time, it releases (pops up).
Therefore, each time a toggle button is pushed, it toggles between its two
states.

Constructors
Constructor Description
It creates an initially unselected toggle
JToggleButton()
button without setting the text or image.
It creates a toggle button where properties
JToggleButton(Action a)
are taken from the Action supplied.
It creates an initially unselected toggle
JToggleButton(Icon icon)
button with the specified image but no text.
JToggleButton(Icon icon, boolean It creates a toggle button with the specified
selected) image and selection state, but no text.
It creates an unselected toggle button with
JToggleButton(String text)
the specified text.
JToggleButton(String text, It creates a toggle button with the specified
boolean selected) text and selection state.
It creates a toggle button that has the
JToggleButton(String text, Icon
specified text and image, and that is initially
icon)
unselected.
JToggleButton(String text, Icon It creates a toggle button with the specified
icon, boolean selected) text, image, and selection state.

Example:

import [Link];
import [Link];
import [Link];
import [Link];
import [Link];

public class JToggleButtonExample extends JFrame implements ItemListener {


public static void main(String[] args) {
new JToggleButtonExample();
}
private JToggleButton button;
JToggleButtonExample() {

257
setTitle("JToggleButton with ItemListener Example");
setLayout(new FlowLayout());
setJToggleButton();
setAction();
setSize(200, 200);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
private void setJToggleButton() {
button = new JToggleButton("ON");
add(button);
}
private void setAction() {
[Link](this);
}
public void itemStateChanged(ItemEvent eve) {
if ([Link]())
[Link]("OFF");
else
[Link]("ON");
}
}.

Output:

Check Boxes
The JCheckBox class provides the functionality of a check box. Its immediate
superclass is JToggleButton, which provides support for two-state buttons, as
just described. JCheckBox defines several constructors.

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

258
Creates an initially unselected check box with
JChechBox(String s)
text.
JCheckBox(String text, Creates a check box with text and specifies
boolean selected) whether or not it is initially selected.
Creates a check box where properties are taken
JCheckBox(Action a)
from the Action supplied.

Example:

import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
JCheckBox checkBox1 = new JCheckBox("C++");
[Link](100,100, 50,50);
JCheckBox checkBox2 = new JCheckBox("Java", true);
[Link](100,150, 50,50);
[Link](checkBox1);
[Link](checkBox2);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}}
Output:

259
JCheckBox Example with ItemListener

import [Link].*;
import [Link].*;
public class CheckBoxExample
{
CheckBoxExample(){
JFrame f= new JFrame("CheckBox Example");
final JLabel label = new JLabel();
[Link]([Link]);
[Link](400,100);
JCheckBox checkbox1 = new JCheckBox("C++");
[Link](150,100, 50,50);
JCheckBox checkbox2 = new JCheckBox("Java");
[Link](150,150, 50,50);
[Link](checkbox1); [Link](checkbox2); [Link](label);
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("C++ Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](new ItemListener() {
public void itemStateChanged(ItemEvent e) {
[Link]("Java Checkbox: "
+ ([Link]()==1?"checked":"unchecked"));
}
});
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new CheckBoxExample();
}
}

260
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.

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

Constructor Description
Creates an unselected radio button with no
JRadioButton()
text.
Creates an unselected radio button with
JRadioButton(String s)
specified text.
JRadioButton(String s, boolean Creates a radio button with the specified text
selected) and selected status.

JRadioButton Example with ActionListener

import [Link].*;
import [Link].*;
class RadioButtonExample extends JFrame implements ActionListener{
JRadioButton rb1,rb2;
JButton b;
RadioButtonExample(){

261
rb1=new JRadioButton("Male");
[Link](100,50,100,30);
rb2=new JRadioButton("Female");
[Link](100,100,100,30);
ButtonGroup bg=new ButtonGroup();
[Link](rb1);[Link](rb2);
b=new JButton("click");
[Link](100,150,80,30);
[Link](this);
add(rb1);add(rb2);add(b);
setSize(300,300);
setLayout(null);
setVisible(true);
}
public void actionPerformed(ActionEvent e){
if([Link]()){
[Link](this,"You are Male.");
}
if([Link]()){
[Link](this,"You are Female.");
}
}
public static void main(String args[]){
new RadioButtonExample();
}}

JTabbedPane
JTabbedPane encapsulates a tabbed pane. It manages a set of components by
linking them with tabs. Selecting a tab causes the component associated with
262
that tab to come to the forefront. Tabbed panes are very common in the
modern GUI, and you have no doubt used them many times. Given the
complex nature of a tabbed pane, they are surprisingly easy to
create and use.

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.

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

Example:

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

263
}}

Output:

JScrollPane
JScrollPane is a lightweight container that automatically handles the scrolling
of another component. The component being scrolled can either be an
individual component, such as a table, or a group of components contained
within another lightweight container, such as a JPanel. In either case, if the
object being scrolled is larger than the viewable area, horizontal and/or vertical
scroll bars are automatically provided, and the component can be scrolled
through the pane. Because JScrollPane automates scrolling, it usually
eliminates the need to manage individual scroll bars.

The viewable area of a scroll pane is called the viewport. It is a window in


which the component being scrolled is displayed. Thus, the viewport displays
the visible portion of the component being scrolled.

A JscrollPane is used to make scrollable view of a component. When screen size


is limited, we use a scroll pane to display a large component or a component
whose size can change dynamically.

Constructor Purpose
JScrollPane()
JScrollPane(Component) It creates a scroll pane. The Component parameter,
when present, sets the scroll pane's client. The two
JScrollPane(int, int) int parameters, when present, set the vertical and
JScrollPane(Component, horizontal scroll bar policies (respectively).
int, int)

264
Modifier Method Description
It sets the column header for
void setColumnHeaderView(Component)
the scroll pane.
It sets the row header for the
void setRowHeaderView(Component)
scroll pane.
void setCorner(String, Component) It sets or gets the specified
corner. The int parameter
specifies which corner and
must be one of the following
constants defined in
ScrollPaneConstants:
UPPER_LEFT_CORNER,
Component getCorner(String) UPPER_RIGHT_CORNER,
LOWER_LEFT_CORNER,
LOWER_RIGHT_CORNER,
LOWER_LEADING_CORNER,
LOWER_TRAILING_CORNER,
UPPER_LEADING_CORNER,
UPPER_TRAILING_CORNER.
void setViewportView(Component) Set the scroll pane's client.

Example:

import [Link];
import [Link];
import [Link];
import [Link];

public class JScrollPaneExample {


private static final long serialVersionUID = 1L;

private static void createAndShowGUI() {

// Create and set up the window.


final JFrame frame = new JFrame("Scroll Pane Example");

// Display the window.


[Link](500, 500);
[Link](true);

265
[Link](JFrame.EXIT_ON_CLOSE);

// set flow layout for the frame


[Link]().setLayout(new FlowLayout());

JTextArea textArea = new JTextArea(20, 20);


JScrollPane scrollableTextArea = new JScrollPane(textArea);

[Link](JScrollPane.HORIZONTAL_SCR
OLLBAR_ALWAYS);

[Link](JScrollPane.VERTICAL_SCROLLB
AR_ALWAYS);

[Link]().add(scrollableTextArea);
}
public static void main(String[] args) {

[Link](new Runnable() {

public void run() {


createAndShowGUI();
}
});
}
}

JList
266
The object of JList class represents a list of text items. The list of text items can
be set up so that the user can choose either one item or multiple items. It
inherits JComponent class.
Swing, the basic list class is called JList. It supports the selection of one or
more items from a list. Although the list often consists of strings, it is possible
to create a list of just about any object that can be displayed. JList is so widely
used in Java that it is highly unlikely that you have not seen one before.

Constructor Description
JList() Creates a JList with an empty, read-only, model.
Creates a JList that displays the elements in the
JList(ary[] listData)
specified array.
JList(ListModel<ary> Creates a JList that displays elements from the
dataModel) specified, non-null, model.

Methods Description
It is used to add a listener to
Void
the list, to be notified each
addListSelectionListener(ListSelectionListener
time a change to the selection
listener)
occurs.
It is used to return the
int getSelectedIndex()
smallest selected cell index.
It is used to return the data
model that holds a list of
ListModel getModel()
items displayed by the JList
component.
It is used to create a read-
void setListData(Object[] listData) only ListModel from an array
of objects.

import [Link].*;
public class ListExample
{
ListExample(){
JFrame f= new JFrame();
DefaultListModel<String> l1 = new DefaultListModel<>();
[Link]("Item1");
[Link]("Item2");
[Link]("Item3");

267
[Link]("Item4");
JList<String> list = new JList<>(l1);
[Link](100,100, 75,75);
[Link](list);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new ListExample();
}}

JComboBox

Swing provides a combo box (a combination of a text field and a drop-down list)
through the JComboBox class. A combo box normally displays one entry, but
it will also display a drop-down list that allows a user to select a different entry.
You can also create a combo box that lets the user enter a selection into the
text field.

Constructor Description

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

268
JComboBox(Object[] Creates a JComboBox that contains the elements in
items) the specified array.

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


items) the specified Vector.

Example:

import [Link].*;
public class ComboBoxExample {
JFrame f;
ComboBoxExample(){
f=new JFrame("ComboBox Example");
String country[]={"India","Aus","U.S.A","England","Newzealand"};
JComboBox cb=new JComboBox(country);
[Link](50, 50,90,20);
[Link](cb);
[Link](null);
[Link](400,500);
[Link](true);
}
public static void main(String[] args) {
new ComboBoxExample();
}
}

269
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.

Example:

import [Link].*;
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");
[Link](i1); [Link](i2); [Link](i3);
[Link](i4); [Link](i5);
[Link](submenu);
[Link](menu);
[Link](mb);
[Link](400,400);
[Link](null);
[Link](true);
}
public static void main(String args[])
{
new MenuExample();
}}
Output:

270
JDialog

The JDialog 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 Dialog class.

Unlike JFrame, it doesn't have maximize and minimize buttons.

Constructor Description
It is used to create a modeless dialog without a
JDialog()
title and without a specified Frame owner.
It is used to create a modeless dialog with
JDialog(Frame owner)
specified Frame as its owner and an empty title.
JDialog(Frame owner, String It is used to create a dialog with the specified
title, boolean modal) title, owner Frame and modality.

Example:

import [Link].*;
import [Link].*;
import [Link].*;
public class DialogExample {
private static JDialog d;
DialogExample() {
JFrame f= new JFrame();
d = new JDialog(f , "Dialog Example", true);
[Link]( new FlowLayout() );
JButton b = new JButton ("OK");
[Link] ( new ActionListener()
{

271
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}

---------------------------------------------Best of Luck-------------------------------------

272
public void actionPerformed( ActionEvent e )
{
[Link](false);
}
});
[Link]( new JLabel ("Click button to continue."));
[Link](b);
[Link](300,300);
[Link](true);
}
public static void main(String args[])
{
new DialogExample();
}
}

---------------------------------------------Best of Luck-------------------------------------

272

You might also like