Java Applets and Multithreading Guide
Java Applets and Multithreading Guide
UNIT-IV
Applets – Concepts of Applets, differences between applets and applications, life cycle of an
applet, types of applets, creating applets, passing parameters to applets.
Event Handling: Events, Handling mouse and keyboard events, Adapter classes.
Files- Streams- Byte streams, Character streams, Text input/output.
UNIT-V
GUI Programming with Java – AWT class hierarchy, component, container, panel, window, frame,
graphics.
AWT controls: Labels, button, text field, check box, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT
Multithreading
But we use multithreading than multiprocessing because threads share a common memory area.
They don't allocate separate memory area so saves memory, and context-switching between the
threads takes less time than process.
1) It doesn't block the user because threads are independent and you can
performmultiple operations at sametime.
3) Threads are independent so it doesn't affect other threads if exception occur in a singlethread.
A thread can be in one of the five states. According to sun, there is only 4 states in thread life
cycle in java new, runnable, non-runnable and terminated. There is no running state.
But for better understanding the threads, we are explaining it in the 5 states.
The life cycle of the thread in java is controlled by JVM. The java thread states are as follows:
1. New
2. Runnable
3. Running
4. Non-Runnable(Blocked)
5. Terminated
1. By extending Threadclass
2. By implementing Runnableinterface.
Thread class:
Thread class provide constructors and methods to create and perform operations on a
[Link] class extends Object class and implements Runnable interface.
oThread()
oThread(String
name)
oThread(Runnable r)
oThread(Runnable r,String name)
Runnable interface:
The Runnable interface should be implemented by any class whose instances are intended to be
executed by a thread. Runnable interface have only one method named run().
1. public void run(): is used to perform action for athread.
Starting a thread:
start() method of Thread class is used to start a newly created thread. It performs following
tasks:
oA new thread starts(with new callstack).
oThe thread moves from New state to the Runnable state.
oWhen the thread gets a chance to execute, its target run() method will run.
When a thread invokes a synchronized method, it automatically acquires the lock for that object
and releases it when the thread completes its task.
classCustomer{ intamo
unt=10000;
synchronized void withdraw(int amount){
[Link]("going to withdraw...");
if([Link]<amount){
[Link]("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
[Link]-=amount;
[Link]("withdraw completed...");
}
synchronized void deposit(int amount)
{ [Link]("going to deposit...");
[Link]+=amount;
[Link]("deposit completed... ");
notify();
}
}
classTest{
public static void main(String args[])
{ final Customer c=newCustomer();
new Thread(){
public void run(){[Link](15000);}
}.start();
newThread(){
ThreadGroup(String name)
ThreadGroup(ThreadGroup parent, String name)
Now all 3 threads belong to one group. Here, tg1 is the thread group name, MyRunnable is the
class that implements Runnable interface and "one", "two" and "three" are the thread names.
1. [Link]().getThreadGroup().interrupt();
APPLETS:
An applet is a program that comes from server into a client and gets executed at client side and
displays the result.
An applet represents byte code embedded in a html page. (Applet = bytecode + html) and run with
the help of Java enabled browsers such as Internet Explorer.
An applet is a Java program that runs in a browser. Unlike Java applications applets do not have a
main () method.
To create applet we can use [Link] or [Link] class. All applets inherit the
super class „Applet‟. An Applet class contains several methods that help to control the execution
of an applet.
Advantages:
Applets provide dynamic nature for a webpage.
Applets are used in developing games and animations.
Writing and displaying (browser) graphics and animations is easier than
applications.
In GUI development, constructor, size of frame, window closing code etc. are not
required
Security Does not require any security Requires highest security for the
system as they are untrusted
Accessibility The java applications are Applets are designed just for
designed to work with the handling the client site
client as well as server. problems.
Client side / The applications don't Applets are designed for the
Server side have such type of criteria client site programming purpose
Example
public class MyClass import [Link].*;
{ import [Link].*;
public static void main(String
args[]) {} public
} class Myclass extends Applet
{
public void init()
{
}
public void start()
{
}
public void stop()
{
}
public void destroy() {}
Initialization:
public void init(): This method is used for initializing variables, parameters to create
components. This method is executed only once at the time of applet loaded into memory.
public void init()
{
//initialization
}
Runnning:
public void start (): After init() method is executed, the start method is executed
automatically. Start method is executed as long as applet gains focus. In this method code
related to opening files and connecting to database and retrieving the data and processing
the data is written.
Idle / Runnable:
public void stop (): This method is executed when the applet loses focus. Code related to
closing the files and database, stopping threads and performing clean up operations are
written in this stop method.
Dead/Destroyed:
public void destroy (): This method is executed only once when the applet is terminated
from the memory.
Executing above methods in that sequence is called applet life cycle.
We can also use public void paint (Graphics g) in applets.
//An Applet skeleton.
import [Link].*;
import [Link].*;
/*
<applet code="AppletSkel" width=300 height=100>
</applet>
*/
public class AppletSkel extends Applet {
3 Called first.
public
void init()
{
4 initialization
}
/* Called second, after init(). Also called whenever the applet is restarted. */
public void start() {
3 start or resume execution
}
4 Called when the applet is
stopped. public void stop()
{
5 suspends execution
}
/* Called when applet is terminated. This is the last method executed. */
public void destroy() {
5 perform shutdown activities
}
6 Called when an applet's window must
be restored. public void paint(Graphics
g) {
7 redisplay contents of window
}
}
After writing an applet, an applet is compiled in the same way as Java application but running of
an applet is different.
There are two ways to run an applet.
Executing an applet within a Java compatible web browser.
Executing an applet using „appletviewer‟. This executes the applet in a window.
To execute an applet using web browser, we must write a small HTML file which contains the
appropriate „APPLET‟ tag. <APPLET> tag is useful to embed an applet into an HTML page. It
has the following form:
<APPLET CODE=”name of the applet class file” HEIGHT = maximum height of applet in
pixels WIDTH = maximum width of applet in pixels ALIGN = alignment (LEFT, RIGHT,
MIDDLE, TOP, BOTTOM)>
<PARAM NAME = parameter name VALUE = its
value> </APPLET>
Execution: appletviewer [Link] or appletviewer [Link]
The <PARAM> tag useful to define a variable (parameter) and its value inside the HTML page
which can be passed to the applet. The applet can access the parameter value using
getParameter () method, as: String value = getParameter (“pname”);
Example Program:
Following is a simple applet named [Link] −
import [Link].*; import [Link].*;
public class HelloWorldApplet extends Applet {
public void paint (Graphics g) { [Link] ("Hello World", 25, 50);
}}
Invoking an Applet - [Link]
<html>
<title>The Hello, World Applet</title>
<applet code = "[Link]" width = "320" height = "120">
</applet>
</html>
TYPES OF APPLETS
Applets are of two types:
// Local Applets
// Remote Applets
Local Applets: An applet developed locally and stored in a local system is called local applets.
So, local system does not require internet. We can write our own applets and embed them into
the web pages.
Remote Applets: The applet that is downloaded from a remote computer system and embed
applet into a web page. The internet should be present in the system to download the applet and
run it. To download the applet we must know the applet address on web known as Uniform
Resource Locator(URL) and must be specified in the applets HTML document as the value of
CODEBASE.
PASSING PARAMETERS TO AN APPLET
Java applet has the feature of retrieving the parameter values passed from the html page. So, you
can pass the parameters from your html page to the applet embedded in your page. The param
tag(<parma name="" value=""></param>) is used to pass the parameters to an applet. The
applet has to call the getParameter() method supplied by the [Link] parent class.
Ex3: [Link]
import [Link].*;
import [Link].*;
/*<Applet code="hai" height="250" width="250">
<PARAM name="Message" value="Hai friend how are you ..?"></APPLET>
*/
class hai extends Applet
{
private String defaultMessage = "Hello!";
public void paint(Graphics g) {
The advantage of this design is that the application logic that processes events is
cleanly separated from the user interface logic that generates those events. A user interface
element is able to "delegate" the processing of an event to a separate piece of code.
In the delegation event model, listeners must register with a source in order to
receive an event notification. This provides an important benefit: notifications are sent only
to listeners that want to receive them.
EVENTS
In the delegation model, an event is an object that describes a state change in a source. It can be
generated as a consequence of a person interacting with the elements in a graphical user
interface. Some of the activities that cause events to be generated are pressing a button, entering
a character via the keyboard, selecting an item in a list, and clicking the mouse.
Events may also occur that are not directly caused by interactions with a user interface.
For example, an event may be generated when a timer expires, a counter exceeds a value,
software or hardware failure occurs, or an operation is completed.
EVENT SOURCES
A source is an object that generates an event. This occurs when the internal state of that object
changes in some way. Sources may generate more than one type of event. A source must register
listeners in order for the listeners to receive notifications about a specific type of event. Each
type of event has its own registration method.
Here is the general form:
public void add Type Listener( Type Listener el )
EVENT LISTENERS
A listener is an object that is notified when an event occurs. It has two major requirements. First,
it must have been registered with one or more sources to receive notifications about specific
types of events. Second, it must implement methods to receive and process these notifications.
The methods that receive and process events are defined in a set of interfaces found in
[Link].
For example, the MouseMotionListener interface defines two methods to receive notifications
when the mouse is dragged or moved.
EVENT CLASSES
The classes that represent events are at the core of Java's event handling mechanism. At the root
of the Java event class hierarchy is EventObject, which is in [Link]. It is the superclass for all
events.
It’s one constructor is shown here:
EventObject(Object src )
EventObject contains two methods: getSource( ) and toString( ) .
The getSource( ) method returns the source of the event. Ex: Object getSource( )
toString( ) returns the string equivalent of the event.
The package [Link] defines several types of events that are generated by various user
interface elements.
Event Class Description
ActionEvent Generated when a button is pressed, a list item is double-clicked, or a menu
item is selected.
AdjustmentEvent Generated when a scroll bar is manipulated.
ComponentEvent Generated when a component is hidden, moved, resized or becomes visible.
ContainerEvent Generated when a component is added to or removed from a container.
FocusEvent Generated when a component gains or loses keyboard focus.
InputEvent Abstract super class for all component input event classes.
ItemEvent Generated when a check box or list item is clicked; so occurs when a choice
selection is made or a checkable menu item is selected or deselected.
KeyEvent Generated when input is received from the keyboard.
MouseEvent Generated when the mouse is dragged, moved, clicked, pressed, or released;
also generated when the mouse enters or exits a component.
MouseWheelEvent Generated when the mouse wheel is moved. (Added by Java 2, version 1.4)
TextEvent Generated when the value of a text area or text field is changed.
WindowEvent Generated when a window is activated, closed, deactivated, deiconified,
iconified, opened, or quit.
mouseY =
10;
msg = "Mouse exited.";
repaint();
}
// Handle button pressed.
public void mousePressed(MouseEvent me) {
// save coordinates
mouseX =
[Link]();
mouseY =
[Link](); msg =
"Down"; repaint();
}
// Handle button released.
public void mouseReleased(MouseEvent me) {
1. save
coordinates
mouseX
=[Link]();
mouseY =
*/7+[Link](
);
msg
= "Up";
repaint();
}
2. Handle mouse dragged.
public void mouseDragged(MouseEvent me) {
1. save coordinates
mouseX =
[Link]();
}
Adapter Classes
Java provides a special feature, called an adapter class , that can simplify the creation of event
handlers in certain situations. An adapter class provides an empty implementation of all methods
in an event listener interface.
Adapter classes are useful when you want to receive and process only some of the events that are
handled by a particular event listener interface.
For example, the MouseMotionAdapter class has two methods, mouseDragged( ) and
mouseMoved( ) . The signatures of these empty methods are exactly as defined in the
MouseMotionListener interface. If you were interested in only mouse drag events, then you
could simply extend MouseMotionAdapter and implement mouseDragged( ) . The empty
implementation of mouseMoved( ) would handle the mouse motion events for you.
Adapter Class
ComponentAdapter Listener Interface
ContainerAdapter ComponentListener
FocusAdapter ContainerListener
KeyAdapter FocusListener
MouseAdapter KeyListener
MouseMotionAdapter MouseListener
WindowAdapter MouseMotionListener
WindowListener
EX: // Demonstrate an adapter.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="AdapterDemo" width=300 height=100>
</applet>
*/
public class AdapterDemo extends Applet
{
public void init() {
addMouseListener(new MyMouseAdapter(this));
addMouseMotionListener(new
MyMouseMotionAdapter(this)); }
}
class MyMouseAdapter extends MouseAdapter
{
AdapterDemo adapterDemo;
public MyMouseAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse clicked.
public void mouseClicked(MouseEvent me)
{ [Link]("Mouse clicked");
}
}
class MyMouseMotionAdapter
extends MouseMotionAdapter {
AdapterDemo adapterDemo;
public MyMouseMotionAdapter(AdapterDemo adapterDemo)
{
[Link] = adapterDemo;
}
// Handle mouse dragged.
public void mouseDragged(MouseEvent me)
{
[Link]("Mouse dragged");
}
}
Java provides strong but flexible support for I/O related to files and networks.
Byte Streams
Java byte streams are used to perform input and output of 8-bit bytes. Though there are many
classes related to byte streams but the most frequently used classes are, FileInputStream and
FileOutputStream.
Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{ FileInputStream in = null;
FileOutputStream out = null;
try {
in = new FileInputStream("[Link]");
out = new FileOutputStream("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
} } }}
Now let's have a file [Link] with the following content:
This is test for copy file.
$javac [Link]
$java CopyFile
Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, whereas
Java Character streams are used to perform input and output for 16-bit unicode. Though
there are many classes related to character streams but the most frequently used classes
are, FileReader and FileWriter.
Though internally FileReader uses FileInputStream and FileWriter uses FileOutputStream but
here the major difference is that FileReader reads two bytes at a time and FileWriter writes two
bytes at a time.
Example
import [Link].*;
public class CopyFile
{
public static void main(String args[]) throws IOException
{ FileReader in = null;
FileWriter out = null;
try {
in = new FileReader("[Link]");
out = new FileWriter("[Link]");
int c;
while ((c = [Link]()) != -1) {
[Link](c);
}
}finally {
if (in != null) {
[Link]();
}
if (out != null) {
[Link]();
}
}
}
}
The two important streams are FileInputStream and FileOutputStream (File Handling)
In Java, FileInputStream and FileOutputStream classes are used to read and write data in file. In
another words, they are used for file handling in java.
Java FileOutputStream class
Java FileOutputStream is an output stream for writing data to a file. It is a class belongs to byte
streams. It can be used to create text files.
First we should read data from the keyword. It uses DataInputStream class for reading data from the
keyboard is as:
DataInputStream dis=new DataInputStream([Link]);
FileOutputStream used to send data to the file and attaching the file to FileOutputStream. i.e.,
FileOutputStream fout=new FileOutputStream(“File_name”);
The next step is to read data from DataInputStream and write it into FileOutputStream. It means read data
from dis object and write it into fout object. i.e.,
ch=(char)[Link](); //read one character into ch
[Link](ch); //write ch into file.
Finally closing the file using: [Link]();
Creating a Text file:
Example: Write a program to read data from the keyboard and write it to [Link] file.
import [Link].*;
class Test{
public static void main(String args[])
{
DataInputStream dis=new DataInputStream([Link]);
FileOutputstream fout=new
FileOutputStream("[Link]"); [Link]("Enter
text @ at the end:”); char ch; while((ch=(char)[Link]())!
=‟@‟)
[Link](ch);
[Link]();
}
}
Output: javac [Link]
Java Test
Java FileInputStream class
It is useful to read data from a file in the form of sequence of bytes. It is possible to read data
from a text file using FileInputStream. i.e.,
FileInputStream fin= new FileInputStream(“[Link]”);
To read data from
the file is, ch=[Link]();
When there is no more data available to read then it returns -1.
The Output Stream is used to send data to the monitor. i.e., PrintStream, for displaying the data we can
use [Link].
[Link](ch);
Reading data from a text file using FileInputStream:
Java FileInputStream class obtains input bytes from a file. It is used for reading streams of raw
bytes such as image data. It should be used to read byte-oriented data for example to read image,
audio, video etc.
Example: Write a program to read data from [Link] using FileInputStream and display
it on monitor.
import [Link].*;
class ReadFile
{
public static void main(String args[])
{
FileInputStream fin=new
FileInputStream("[Link]"); [Link](“File
Contents:”); int ch; while((ch=[Link]())!=-1)
{
[Link]((char)ch);
}
[Link]();
}
}
Output: javac [Link]
java ReadFile
III
UNIT V: GUI Programming with Java – AWT class hierarchy, component, container,
panel, window, frame, graphics.
AWT controls: Labels, button, text field, check box, check box groups, choices, lists,
scrollbars, and graphics.
Layout Manager – Layout manager types: border, grid and flow.
Swing – Introduction, limitations of AWT, Swing vs AWT.
Control Fundamentals
The AWT supports the following types of controls:
3. Labels
4. Push buttons
5. Check boxes
6. Choice lists
7. Lists
8. Scroll bars
9. Text editing
Container
The Container is a component in AWT that can contain other components like buttons, textfields,
labels etc. The classes that extend Container class are known as container such as Frame, Dialog
and Panel.
III
Window
The window is the container that has 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 height) sets the size(width and height) of the component.
public void setLayout(LayoutManager m) defines the layout manager for the component.
public void setVisible(boolean status) changes the visibility of the component, by
default false.
Layout Managers
III
A layout manager arranges the child components of a container. It positions and sets the size of
components within the container's display area according to a particular layout scheme.
The layout manager's job is to fit the components into the available area, while maintaining the
proper spatial relationships between the components. AWT comes with a few standard layout
managers that will collectively handle most situations; you can make your own layout managers
if you have special requirements.
LayoutManager at work
Every container has a default layout manager; therefore, when you make a new container, it
comes with a LayoutManager object of the appropriate type. You can install a new layout
manager at any time with the setLayout() method. Below, we set the layout manager of a
container to a BorderLayout:
setLayout ( new BorderLayout( ) );
Every component determines three important pieces of information used by the layout manager
in placing and sizing it: a minimum size, a maximum size, and a preferred size.
These are reported by the getMinimumSize(), getMaximumSize(), and getPreferredSize(),
methods of Component, respectively.
When a layout manager is called to arrange its components, it is working within a fixed area. It
usually begins by looking at its container's dimensions, and the preferred or minimum sizes of
the child components.
Layout manager types
Flow Layout
FlowLayout is a simple layout manager that tries to arrange components with their preferred
sizes, from left to right and top to bottom in the display. A FlowLayout can have a specified
justification of LEFT, CENTER, or RIGHT, and a fixed horizontal and vertical padding.
By default, a flow layout uses CENTER justification, meaning that all components are centered
within the area allotted to them. FlowLayout is the default for Panel components like Applet.
III
GridLayout takes the number of rows and columns in its constructor. If you subsequently
give it too many objects to manage, it adds extra columns to make the objects fit. You can also
set the number of rows or columns to zero, which means that you don't care how many elements
the layout manager packs in that dimension.
For example, GridLayout(2,0) requests a layout with two rows and an unlimited number of
columns; if you put ten components into this layout, you'll get two rows of five columns each.
The following applet sets a GridLayout with three rows and two columns as its layout
manager;
import [Link].*;
/*
<applet code="Grid" width="500"
height="500"> </applet>
*/
public class Grid extends [Link]
{
public void init()
{
setLayout( new GridLayout( 3, 2 ));
III
The five buttons are laid out, in order, from left to right, top to bottom, with one empty spot.
Border Layout
BorderLayout is a little more interesting. It tries to arrange objects in one of five geographical
locations: "North," "South," "East," "West," and "Center," possibly with some padding between.
BorderLayout is the default layout for Window and Frame objects. Because each
component is associated with a direction, BorderLayout can manage at most five components; it
squashes or stretches those components to fit its constraints.
When we add a component to a border layout, we need to specify both the component and the
position at which to add it. To do so, we use an overloaded version of the add() method that
takes an additional argument as a constraint.
The following applet sets a BorderLayout layout and adds our five buttons again, named for
their locations;
import [Link].*;
/*
<applet code="Border" width="500" height="500">
</applet>
*/
public class Border extends [Link]
{
public void init()
{
setLayout( new [Link]() );
add( new Button("North"), "North" ); add(
new Button("East"), "East" );
add( new Button("South"), "South" );
add( new Button("West"), "West" );
add( new Button("Center"), "Center" );
}
}
AWT controls
Labels:
The easiest control to use is a label. A label is an object of type Label, and it contains a string,
which it displays. Labels are passive controls that do not support any interaction with the user.
// Demonstrate
Labels import
[Link].*; import
[Link].*; /*
<applet code="LabelDemo" width=300 height=200>
</applet> */
public class LabelDemo extends Applet
{
public void init()
{
Label one = new Label("One");
Label two = new Label("Two");
Label three = new Label("Three");
add labels to applet window
add(one);
add(two);
add(three);
}
}
Buttons:
The most widely used control is the push button. A push button is a component that contains a
label and that generates an event when it is pressed. Push buttons are objects of type Button.
Button class is useful to create push buttons. A push button triggers a series of events.
To create push button: Button b1 =new Button("label");
To get the label of the button: String l = [Link]();
To set the label of the button: [Link]("label");
To get the label of the button clicked: String str = [Link]();
\{ Demonstrate Buttons
import [Link].*;
import [Link].*;
import [Link].*;
/* <applet code="ButtonDemo" width=250 height=150>
</applet> */
Check Boxes:
A check box is a control that is used to turn an option on or off. It consists of a small box that
can either contain a check mark or not. There is a label associated with each check box that
describes what option the box represents. You change the state of a check box by clicking on
it. Check boxes can be used individually or as part of a group.
/*
<applet code="CheckboxDemo" width=250 height=200>
</applet>
*/
public class CheckboxDemo extends Applet implements ItemListener
{
String msg = "";
checkbox Win98, winNT, solaris, mac;
TextField:
The TextField class implements a single-line text-entry area, usually called an edit control.
Text fields allow the user to enter strings and to edit the text using the arrow keys, cut and
paste keys, and mouse selections.
// Demonstrate text field.
import [Link].*;
import
[Link].*;
import [Link].*;
/*
<applet code="TextFieldDemo" width=380 height=150>
</applet>
*/
public class TextFieldDemo extends Applet implements ActionListener
{
TextField name, pass;
TextArea:
Sometimes a single line of text input is not enough for a given task. To handle these
situations, the AWT includes a simple multiline editor called TextArea .
\{ Demonstrate
TextArea. import
[Link].*; import
[Link].*;
/*
<applet code="TextAreaDemo" width=300
height=250> </applet>
*/
public class TextAreaDemo extends Applet
{
public void init()
{
String val = "There are two ways of constructing " + "a software design.\n" + "One way is to
make it so simple\n" + "that there are obviously no deficiencies.\n" + "And the other way is to
make it so complicated\n" + "that there are no obvious deficiencies.\n\n" + " -C.A.R. Hoare\n\n"
+ "There's an old story about the person who wished\n" + "his computer were as easy to use as
his telephone.\n" + "That wish has come true,\n" + "since I no longer know how to use my
telephone.\n\n" + " -Bjarne Stroustrup, AT&T, (inventor of C++)";
TextArea text = new TextArea(val, 10, 30);
add(text);
}
}
CheckboxGroup
It is possible to create a set of mutually exclusive check boxes in which one and only one
check box in the group can be checked at any one time. These check boxes are often called
radio buttons. A Radio button represents a round shaped button such that only one can be
selected from a panel. Radio button can be created using CheckboxGroup class and
Checkbox classes.
· To create a radio button: CheckboxGroup cbg = new CheckboxGroup ();
Checkbox cb = new Checkbox ("label", cbg, true);
· To know the selected checkbox: Checkbox cb = [Link] ();
· To know the selected checkbox label: String label = [Link]().getLabel ();
/*
<applet code="CBGroup" width=250 height=200>
</applet>
*/
Lists
The List class provides a compact, multiple-choice, scrolling selection list. Unlike the
Choice object, which shows only the single selected item in the menu, a List object can be
constructed to show any number of choices in the visible window. It can also be created to
allow multiple selections. List provides these constructors: List( )
List(int numRows )
List(int numRows , boolean multipleSelect )
A List box is similar to a choice box, it allows the user to select multiple items.
· To create a list box:
(or) List lst = new List();
In addition to the familiar components, such as buttons, check boxes, and labels, Swing
supplies several exciting additions, including tabbed panes, scroll panes, trees, and tables.
Even familiar components such as buttons have more capabilities in Swing. For example, a
button may have both an image and a text string associated with it. Also, the image can be
changed as the state of the button changes.
Unlike AWT components, Swing components are not implemented by platform specific
code. Instead, they are written entirely in Java and, therefore, are platform-independent.
The term lightweight is used to describe such elements.
The [Link] package provides classes for java swing API such as JButton, JTextField, JTextArea,
JRadioButton, JCheckbox, JMenu, JColorChooser etc.
AWT Swing
AWT components are called Heavyweight Swings are called light weight component
component. because swing components sits on the top of
AWT components and do the work.
AWT components are platform dependent. Swing components are made in purely java and
they are platform independent.
AWT is a thin layer of code on top of the OS. Swing is much larger. Swing also has very
much richer functionality.
AWT stands for Abstract windows toolkit. Swing is also called as JFC’s (Java Foundation
classes).
This feature is not supported in AWT. We can have different look and feel in Swing.
Using AWT, you have to implement a lot of Swing has them built in.
things yourself.
This feature is not available in AWT. Swing has many advanced features like JTabel, Jtabbed pane w
Note: To close the frame, we can take the help of getDefaultCloseOperation () method of
JFrame class, as shown here: getDefaultCloseOperation (constant);
where the constant can be any one of the following:
◼ JFrame.EXIT_ON_CLOSE: This closes the application upon clicking on close button.
◼ JFrame.DISPOSE_ON_CLOSE: This disposes the present frame which is visible
on the screen. The JVM may also terminate.
◼ JFrame.DO_NOTHING_ON_CLOSE: This will not perform any operation
uponclicking on close button.
◼ JFrame.HIDE_ON_CLOSE: This hides the frame upon clicking on close button.
Window Panes: In swings the components are attached to the window panes only. A window
pane represents a free area of a window where some text or components can be displayed. For
example, we can create a frame using JFrame class in [Link] which contains a free area
inside it, this free area is called 'window pane'. Four types of window panes are available in
[Link] package.
Glass Pane: This is the first pane and is very close to the monitors screen. Any components to
be displayed in the foreground are attached to this glass pane. To reach this glass pane, we use
getGlassPane () method of JFrame class.
Root Pane: This pane is below the glass pane. Any components to be displayed in the
background are displayed in this pane. Root pane and glass pane are used in animations also.
For example, suppose we want to display a flying aeroplane in the sky. The aeroplane can be
displayed as a .gif or .jpg file in the glass pane where as the blue sky can be displayed in the root
pane in the background. To reach this root pane, we use getRootPane () method of JFrame class.
Layered Pane: This pane lies below the root pane. When we want to take several components
as a group, we attach them in the layered pane. We can reach this pane by calling
getLayeredPane () method of JFrame class.
Content Pane: This is the bottom most pane of all. Individual components are attached to this
pane. To reach this pane, we can call getContentPane () method of JFrame class.
Displaying Text in the Frame:
paintComponent (Graphics g) method of JPanel class is used to paint the portion of a component
in swing. We should override this method in our class. In the following example, we are writing
our class MyPanel as a subclass to JPanel and override the painComponent () method.
TEXT FIELDS
The Swing text field is encapsulated by the JTextComponent class, which extends JComponent.
It provides functionality that is common to Swing text components. One of its subclasses is
JTextField, which allows you to edit one line of text. Some of its constructors are shown here:
JTextField( )
JTextField(int cols)
JTextField(String s, int cols)
JTextField(String s)
import [Link].*;
import [Link].*;
/*
<applet code="JTextFieldDemo" width=300 height=50>
</applet>
*/
public class JTextFieldDemo extends JApplet
{ JTextField jtf;
public void init()
{
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add text field to content
pane jtf = new
JTextField(15);
[Link](jtf);
}
}
BUTTONS
Swing buttons provide features that are not found in the Button class defined by the AWT. For
example, you can associate an icon with a Swing button. Swing buttons are subclasses of the
AbstractButton class, which extends JComponent. AbstractButton contains many methods that
allow you to control the behavior of buttons, check boxes, and radio buttons.
The JButton Class
The JButton class provides the functionality ofa push button. JButton allows an icon, a string, or
both to be associated with the push button. Some of its constructors are shown here:
· To create a JButton with text: JButton b = new JButton (“OK”);
· To create a JButton with image: JButton b = new JButton (ImageIcon ii);
· To create a JButton with text & image: JButton b = new JButton (“OK”, ImageIcon ii);
It is possible to create components in swing with images on it. The image is specified by
ImageIcon class object.
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JButtonDemo" width=250 height=300>
</applet>
*/
public class JButtonDemo extends JApplet implements ActionListener
{ JTextField jtf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
// Add buttons to content pane
ImageIcon france = new ImageIcon("[Link]");
JButton jb = new JButton(france);
[Link]("France");
[Link](this); [Link](jb);
cb = new JCheckBox("C++",
normal);[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Java",normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
cb = new JCheckBox("Perl",normal);
[Link](rollover);
[Link](selected);
[Link](this);
[Link](cb);
// Add text field to the content pane
jtf = new JTextField(15);
[Link](jtf);
}
public void itemStateChanged(ItemEvent ie)
{ JCheckBox cb = (JCheckBox)[Link]();
[Link]([Link]());
}
}
RADIO BUTTONS
Radio buttons are supported by the JRadioButton class, which is a concrete implementation of
AbstractButton. Its immediate superclass is JToggleButton, which provides support for two-
state buttons. Some of its constructors are shown here:
JRadioButton(Icon i)
JRadioButton(Icon i, boolean state)
JRadioButton(String s)
JRadioButton(String s, boolean state)
JRadioButton(String s, Icon i)
JRadioButton(String s, Icon i, boolean state)
import [Link].*;
import [Link].*;
import [Link].*;
/*
<applet code="JRadioButtonDemo" width=300 height=50>
</applet>
*/
public class JRadioButtonDemo extends JApplet implements ActionListener
{ JTextField tf;
public void init() {
// Get content pane
Container contentPane = getContentPane();
[Link](new FlowLayout());
1. Add radio buttons to content pane
JRadioButton b1 = new
JRadioButton("A");
[Link](this);
[Link](b1);
JRadioButton b2 = new JRadioButton("B");
[Link](this);
[Link](b2);
JRadioButton b3 = new JRadioButton("C");
[Link](this);
[Link](b3);
[Link] a button group
ButtonGroup bg = new ButtonGroup();
[Link](b1);
[Link](b2);
[Link](b3);
// Create a text field and add it
// to the content pane
tf = new JTextField(5);
[Link](tf);
}
public void actionPerformed(ActionEvent ae) {
[Link]([Link]());
}
}
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.