Download CS316– AJP UNIT-1 UNIT I JAVA FUNDAMENTALS Java I/O

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
CS316– AJP UNIT-1
UNIT I JAVA FUNDAMENTALS
Java I/O streaming – filter and pipe streams – Byte Code interpretation - Threading – Swing.
Java I/O Streaming
I/O in Java is built on streams. Input streams read data. Output streams write data
Output Streams
Java's basic output class is java.io.OutputStream :
public abstract class OutputStream
This class provides the fundamental methods needed to write data
public abstract void write(int b) throws IOException
public void write(byte[] data) throws IOException
public void write(byte[] data, int offset, int length)
throws IOException
public void flush( ) throws IOException
public void close( ) throws IOException
OutputStream use these methods to write data onto particular media..
OutputStream's fundamental method is
write(int b)
Page 1
CS316– AJP UNIT-1
This method takes as an argument an integer from to 255 and writes the corresponding byte
to the output stream. this method is declared abstract because subclasses will need to change
it to handle their particular medium
Input Streams
Java's basic input class is java.io.InputStream
public abstract class InputStream
class provides the fundamental methods needed to read data as raw bytes
public abstract int read( ) throws IOException
public int read(byte[] input) throws IOException
public int read(byte[] input, int offset, int length) throws
IOException public long skip(long n) throws IOException
public int available( ) throws IOException
public void close( ) throws IOException
InputStream use these methods to read data from particular media.
InputStream fundamental method is read( )
This method reads a single byte of data from the input stream's source and returns it as a
number from to 255.
End of stream is signified by returning -1, declared as abstract
Write a Program to Read Text from the Standard Input
import java.io.*;
public class ReadStandardIO{
public static void main(String[] args) throws IOException{
InputStreamReader inp = new
InputStreamReader(System.in) BufferedReader br = new
BufferedReader(inp); System.out.println("Enter text : ");
String str = in.readLine();
System.out.println("You entered String
: "); System.out.println(str);
}
}
Output:
C:\programs>javac ReadStandardIO.java
C:\programs>java ReadStandardIO
Enter text :
ADVANCED JAVA- Input Stream
You entered String :
ADVANCED JAVA- Input Stream
Page 2
CS316– AJP UNIT-1
Marking and Resetting
Provides methods that allow programs to back up and reread data
public void mark(int readAheadLimit)
public void reset( ) throws IOException
public boolean markSupported( )
mark( )method mark the current position in the stream
reset( )method reset the stream back to the marked position
markSupported( ) method returns true. If it does,the stream supports marking and resetting.
Filter Streams
Java provides a number of filter classes you can attach to raw streams to translate
the raw bytes to various 7-bit ASCII,8-bit Latin-1 and zip formats
two types of filter streams

  readers 

writers

filter streams
TelnetInputStream - compressed, encrypted text file arrives from the local
network interface FileOutputStream – used to write data into the file
BufferedInputStream - buffers the data to speed up the
entire process CipherInputStream - decrypts the data.
GZIPInputStream - decompresses the deciphered data
InputStreamReader - converts the decompressed data to Unicode text.
Chaining Filters Together
Filters are connected to streams by their constructor
FileInputStream fin = new FileInputStream("data.txt");
BufferedInputStream bin = new BufferedInputStream(fin);
BufferedInputStream object bin is created by passing fin as an argument
to the BufferedInputStream constructor
Page 3
CS316– AJP UNIT-1
Buffered Streams
BufferedOutputStream class stores written data in a buffer until the buffer is full or
the stream is flushed
public BufferedOutputStream(OutputStream out)
public BufferedOutputStream(OutputStream out, int bufferSize)
buffer size is set to 512 bytes for an output stream.
BufferedInputStream class also has a protected byte array named buf that servers as a buffer
public BufferedInputStream(InputStream in)
public BufferedInputStream(InputStream in, int bufferSize)
buffer size is set to 2,048 bytes for an input stream
BufferedInputStream does not declare any new methods of its own. It only overrides methods
from InputStream
Read file line by line using DataInputStream and BufferedReader
Page 4
CS316– AJP UNIT-1
import java.io.*;
class FileRead
{
public static void main(String args[])
{
try{
// Open the file that is the first
// command line parameter
FileInputStream fstream = new FileInputStream("textfile.txt"); //
Get the object of DataInputStream
DataInputStream in = new DataInputStream(fstream);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
//Read File Line By Line
while ((strLine = br.readLine()) != null)
{ // Print the content on the console
System.out.println (strLine);
}
//Close the input stream
in.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Output:
C:\programs> javac FileRead.java
C:\programs> java FileRead
This file is reading from bufferedreader and datainputstream
Write To File
import java.io.*;
public class WriteFile{
public static void main(String[] args) throws IOException{
File f=new File("textfile1.txt");
FileOutputStream fop=new FileOutputStream(f);
if(f.exists()){
String str="This data is written through the program";
fop.write(str.getBytes());
fop.flush();
fop.close();
System.out.println("The data has been written");
Page 5
CS316– AJP UNIT-1
}
else
System.out.println("This file is not exist");
}
}
Output:
C:\Programs>javac WriteFile.java
C:\ Programs>java WriteFile
The data has been written
PrintStream
PrintStream class is the first filter output stream
output streams can also be chained to print streams, using these
two constructors: public PrintStream(OutputStream out)
public PrintStream(OutputStream out, boolean autoFlush)
PrintStream has 9 overloaded print( ) methods and 10 overloaded println( ) methods
public void print(boolean b)
public void print(char c)
public void print(int i) public
void print(long l) public void
print(float f) public void
print(double d) public void
print(char[] text) public void
print(String s) public void
print(Object o) public void
println( )
public void println(boolean b)
public void println(char c)
public void println(int i) public
void println(long l) public void
println(float f) public void
println(double d) public void
println(char[] text) public void
println(String s) public void
println(Object o)
PushbackInputStream
PushbackInputStream is a subclass of FilterInputStream that provides a pushback
stack so that a program can "unread" bytes onto the input stream
Page 6
CS316– AJP UNIT-1
unread( ) methods that push bytes into the buffer
public void unread(int b) throws IOException
pushes an unsigned byte given as an int between and 255 onto the stream.
There are two more unread( ) methods that push a specified array or subarray onto the stream
public void unread(byte[] input) throws IOException
public void unread(byte[] input, int offset, int length) throws IOException
By default, the buffer is only one byte long, and trying to unread more than one byte throws
an IOException. However, the buffer size can be changed with the second constructor as
follows
public PushbackInputStream(InputStream in)
public PushbackInputStream(InputStream in, int size)
PushbackInputStream does not allow marking and resetting
Java program to write text to a file:
import java.io.*;
class FileWrite
{
public static void main(String args[])
{
try{
// Create file
FileWriter fstream = new FileWriter("out.txt",true);
BufferedWriter out = new BufferedWriter(fstream);
out.write("Hello Java");
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
}
Output
C:\Programs>javac FileWrite.java
C:\ Programs>java FileWrite
Data Streams
Page 7
CS316– AJP UNIT-1
DataInputStream and DataOutputStream classes provide methods for reading and writing
Java's primitive data types and strings in a binary format
DataOutputStream class offers these 11 methods for writing particular Java data types
public final void writeBoolean(boolean b) throws IOException
public final void writeByte(int b) throws IOException
public final void writeShort(int s) throws IOException
public final void writeChar(int c) throws IOException
public final void writeInt(int i) throws IOException public
final void writeLong(long l) throws IOException public
final void writeFloat(float f) throws IOException
public final void writeDouble(double d) throws IOException
public final void writeChars(String s) throws IOException
public final void writeBytes(String s) throws IOException
public final void writeUTF(String s) throws IOException
1. All data is written in big-endian format
2. Integers are written in two's complement in the minimum number of bytes possible
3. byte is written as one two'scomplement byte
4. short as two two's-complement bytes
5. int as four two'scomplement bytes
6. long as eight two's-complement bytes.
7. Floats and doubles are written in IEEE 754 form in 4 and 8 bytes
8. Booleans are written as a single byte with the value for false and 1 for true
9. Chars are written as two unsigned bytes
10. writeChars( ) - method simply iterates through the String argument, writing
each character in turn as a 2-byte
11. The writeBytes( ) method iterates through the String argument but writes only
the least significant byte of each character
DataInputStream
two multibyte read( ) methods that read data into an array or subarray and return
the number of bytes read
public final int read(byte[] input) throws IOException
public final int read(byte[] input, int offset, int length) throws
IOException public final void readFully(byte[] input) throws IOException
public final void readFully(byte[] input, int offset, int length)throws IOException
public final String readLine( ) throws IOException
PipedStreams
Java.io packages contains two classes
PipedInputStream
PipedOutputStream
Page 8
CS316– AJP UNIT-1
Methods used
Int available()
Void close()
Void connect(PipedOutputStream src)
Int read()
Int read(byte[] b,int off,int len)
Protected void receive(int b)
PipedOutputStreams
Constructors
PipedOutputStreams()
PipedOutputStreams(PipedInputStream snk)
Mothod used
Close()
Connect(pipedInputStream snk)
Flush()
Write(byte[] b,int offset,int length)
Write(int b)
Filter Readers and Writers
InputStreamReader and OutputStreamWriter classes on top of input and output streams
that change the interface from a byte-oriented interface to a character-oriented interface
Subclasses of FilterReader and FilterWriter
BufferedReader
BufferedWriter
LineNumberReader
PushbackReader
PrintWriter
Buffered readers and writers
BufferedReader and BufferedWriter classes are the character-based equivalents of the byteoriented BufferedInputStream and BufferedOutputStream classes
BufferedInputStream and BufferedOutputStream use an internal array of bytes as a buffer,
BufferedReader and BufferedWriter use an internal array of chars.
Default size of buffer is 8,192 characters
Page 9
CS316– AJP UNIT-1
public BufferedReader(Reader in, int bufferSize)
public BufferedReader(Reader in)
public BufferedWriter(Writer out)
public BufferedWriter(Writer out, int bufferSize)
LineNumberReader
Subclasses of bufferedReader
keeps track of the current line number being read
3. To retrieve the line number use
public int getLineNumber( )
4. subsequent lines can be changed with the setLineNumber( ) method
1.
2.
Constructor used
public LineNumberReader(Reader in)
public LineNumberReader(Reader in, int bufferSize)
PushbackReader
PushbackInputStream class pushes back chars rather than bytes
methods that push characters onto the reader's input buffer
public void unread(int c) throws IOException public
void unread(char[] cbuf) throws IOException
public void unread(char[] cbuf, int offset, int length) throws IOException
By default, the size of the pushback buffer is only one character
Change the pushback buffer using constructor below
public PushbackReader(Reader in)
public PushbackReader(Reader in, int bufferSize)
PrintWriter
PrintWriter class is a replacement for Java 1.0's PrintStream class handles
multibyte character sets
Constructors:
public PrintWriter(Writer out)
public PrintWriter(Writer out, boolean autoFlush)
public PrintWriter(OutputStream out)
public PrintWriter(OutputStream out, boolean autoFlush)
Methods:
Page 10
CS316– AJP UNIT-1
public void flush( )
public void close( )
public boolean checkError( )
protected void setError( )
public void write(int c)
public void write(char[] text, int offset,
int length) public void write(char[] text)
public void write(String s, int offset, int length)
public void write(String s)
public void print(boolean b)
public void print(char c)
public void print(int i) public
void print(long l) public void
print(float f) public void
print(double d) public void
print(char[] text) public void
print(String s) public void
print(Object o) public void
println( )
public void println(boolean b)
public void println(char c)
public void println(int i) public
void println(long l) public void
println(float f) public void
println(double d) public void
println(char[] text) public void
println(String s) public void
println(Object o)
Reading and Writing Data using IO
Streams import java.io.*;
class ReadWriteData
{
public static void main(String args[])
{
int ch=0;
int[] numbers = { 12, 8, 13, 29,
50 }; try
{
System.out.println("1. write Data");
System.out.println("2. Read Data");
System.out.println("Enter your choice ");
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
ch=Integer.parseInt(br.readLine());
Page 11
CS316– AJP UNIT-1
switch(ch){
case 1:
FileOutputStream fos = new FileOutputStream("datafile.txt");
BufferedOutputStream bos = new BufferedOutputStream(fos);
DataOutputStream out =new DataOutputStream (bos);
for (int i = 0; i < numbers.length; i
++) { out.writeInt(numbers[i]);
}
System.out.print("write
successfully"); out.close();
case 2:
FileInputStream fis = new FileInputStream("datafile.txt");
BufferedInputStream bis=new BufferedInputStream(fis);
DataInputStream in =new DataInputStream (bis);
while (true){
System.out.print(in.readInt());
}
default:
System.out.println("Invalid choice");
}
}
catch (Exception e) {
System.err.println("Error in read/write data to a file: " + e);
}
}
}
Output:
C:\Programs>javac ReadWriteData.java
C:\ Programs >java ReadWriteData
1. write Data
2. Read Data
Enter your choice
2
358696
Write successfully
C:\Programs>java ReadWriteData
1. write Data
2. Read Data
Enter your
choice 1 358696
Page 12
CS316– AJP UNIT-1
Counting Number of lines, Words, Characters in a File
import java.io.*;
public class WordCount{
private static void linecount(String fName, BufferedReader in) throws
IOException{ long numChar = 0;
long numLine=0;
long numWords
= 0; String line;
do{
line = in.readLine();
if (line != null){
numChar += line.length();
numWords +=
wordcount(line); numLine++;
}
}while(line != null);
System.out.println("File Name: " + fName);
System.out.println("Number of characters: " + numChar);
System.out.println("Number of words: " + numWords);
System.out.println("Number of Lines: " + numLine);
}
private static void linecount(String fileName){
BufferedReader in = null;
try{
FileReader fileReader = new FileReader(fileName);
in = new BufferedReader(fileReader);
linecount(fileName,in);
}
catch(IOException e){
e.printStackTrace();
}
}
private static long wordcount(String line){
long numWords = 0;
int index = 0;
boolean prevWhiteSpace = true;
while(index < line.length()){
char c = line.charAt(index++);
boolean currWhiteSpace = Character.isWhitespace(c);
if(prevWhiteSpace && !currWhiteSpace){
numWords++;
}
prevWhiteSpace = currWhiteSpace;
}
return numWords;
}
public static void main(String[] args){
Page 13
CS316– AJP UNIT-1
long numChar = 0;
long numLine=0;
String line;
try{
if (args.length == 0)
{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
line = in.readLine();
numChar = line.length();
if (numChar != 0){
numLine=1;
}
System.out.println("Number of characters: " + numChar);
System.out.println("Number of words: " + wordcount(line));
System.out.println("Number of lines: " + numLine);
}else{
for(int i = 0; i < args.length;
i++){ linecount(args[i]);
}
}
}
catch(IOException e){
e.printStackTrace();
}
}
}
Output:
Random Access File
import java.io.*;
public class RandAccessFile{
Page 14
CS316– AJP UNIT-1
public static void main(String[] args) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("Enter File name : ");
String str = in.readLine();
File file = new File(str);
if(!file.exists())
{
System.out.println("File does not exist.");
System.exit(0);
}
try{
//Open the file for both reading and writing
RandomAccessFile rand = new RandomAccessFile(file,"rw");
rand.seek(file.length()); //Seek to end of file
rand.writeBytes("PROFMARIAMICHAEL.COM"); //Write end of file
rand.close();
System.out.println("Write Successfully"); }
catch(IOException e)
{
System.out.println(e.getMessage());
}
}
}
Output
C:\Programs>javac RandAccessFile.java
C:\ Programs >java RandAccessFile
Enter File name : Filterfile.txt
Write Successfully
Page 15
CS316– AJP UNIT-1
Bytecode Interpretation
Java bytecode is the form of instructions that the Java Virtual Machine executes. Each
bytecode opcode is one byte in length, although some require parameters, resulting in some
multi-byte instructions. Not all of the possible 256 opcodes are used. 51 are reserved for
future use. To understand the details of the bytecode. As each byte has 256 potential values,
there are 256 possible opcodes. Of these, 0x00 through 0xca, 0xfe, and 0xff are assigned
values. 0xca is reserved as a breakpoint instruction for debuggers and is not used by the
language. Similarly, 0xfe and 0xff are not used by the language, and are reserved for internal
use by the virtual machine.
Instructions fall into a number of broad groups:
 Load and store (e.g. aload_0,istore) 
 Arithmetic and logic (e.g. ladd,fcmpl)  
Type conversion (e.g. i2b,d2i) 
 Object creation and manipulation (new,putfield)  
Operand stack management (e.g. swap,dup2) 


Control transfer (e.g. ifeq,goto) 
Method invocation and return (e.g. invokespecial,areturn) 
Computational Model
The model of computation of Java bytecode is that of a stack-oriented programming
language. For example, assembly code for an x86 processor might look like this:
add eax, edx
mov ecx, eax
This code would add two values and move the result to a different location
0 iload_1
1 iload_2
2 iadd
3 istore_3
The Execution Engine decodes the bytecode and performs the actions necessary to
implement each instruction. Its interface is quite simple, consisting of a single function that
takes a Context as an argument, and executes the method whose frame is on top of the
Context's call stack.
Since Jupiter's design delegates much of the execution responsibility to other parts of the
system, not much remains to be done by the Execution Engine itself. The current interpreter
Page 16
CS316– AJP UNIT-1
implementation divides the functionality into three modules, which are shown
along with the ExecutionEngine interface in Figure .
These modules are each responsible for implementing a portion of the Execution Engine
functionality:

The opcode Spec module defines each of the Java opcodes in terms of
Jupiter's base interfaces. It takes the form of a header file that is
included (with #include) into the interpreter module. It is designed to
beused by any Execution Engine, be it an interpreter or a JIT compiler.




The Interpreter Support module provides functionality that is independent of the
particular interpreter implementation, such as the stack-unwinding algorithm for
excepti
The Interpreter module implements the Execution Engine interface, making use
of the opcode Spec and Interpreter Support modules as necessary. 
The current Execution Engine implementation is a threaded interpreter, meaning that,
after executing one opcode, it branches directly to the code for executing the next opcode
Threading
A thread is a thread of execution in a program. The Java Virtual Machine allows an
application to have multiple threads of execution running concurrently. Every
thread has a priority. Threads with higher priority are executed in preference to
threads with lower priority.
Even a single application is often expected to do more than one thing at a time. For
example, that streaming audio application must simultaneously read the digital audio
off the network, decompress it, manage playback, and update its display.
Even the word processor should always be ready to respond to keyboard and mouse events,
no matter how busy it is reformatting text or updating the display. Software that can do
such things is known as concurrent software.
The Java platform is designed from the ground up to support concurrent programming,
with basic concurrency support in the Java programming language and the Java class
libraries.
Page 17
CS316– AJP UNIT-1
Processes
A process has a self-contained execution environment. A process generally has a complete,
private set of basic run-time resources; in particular, each process has its own memory
space.
Processes are often seen as synonymous with programs or applications. However, what
the user sees as a single application may in fact be a set of cooperating processes. To
facilitate communication between processes, most operating systems support Inter
Process Communication (IPC) resources, such as pipes and sockets.
Thread
Threads are sometimes called lightweight processes. Both processes and threads provide
an execution environment, but creating a new thread requires fewer resources than
creating a new process. Threads exist within a process — every process has at least one.
Threads share the process's resources, including memory and open files. This makes for
efficient, but potentially problematic, communication.
Life Cycle Of Threads
Life cycle of thread is Important While a thread is alive, it is in one of several states.
By invoking start() method, it doesn?t mean that the thread has access to CPU and start
executing straight away. Several factors determine how it will proceed.
Page 18
CS316– AJP UNIT-1
1. New state ? After the creations of Thread instance the thread is in this state but before
the start() method invocation. At this point, the thread is considered not alive.
2. Runnable (Ready-to-run) state ? A thread start its life from Runnable state. A thread
first enters runnable state after the invoking of start() method but a thread can return
to this state after either running, waiting, sleeping or coming back from blocked
state also. On this state a thread is waiting for a turn on the processor.
3. Running state ? A thread is in running state that means the thread is currently
executing. There are several ways to enter in Runnable state but there is only one way
to enter in Running state: the scheduler select a thread from runnable pool.
4. Dead state ? A thread can be considered dead when its run() method completes. If
any thread comes on this state that means it cannot ever run again.
5. Blocked - A thread can enter in this state because of waiting the resources that
are hold by another thread.
6. Different states implementing Multiple-Threads are:
As we have seen different states that may be occur with the single thread. A running thread
can enter to any non-runnable state, depending on the circumstances. A thread cannot enters
directly to the running state from non-runnable state, firstly it goes to runnable state. Now lets
understand the some non-runnable states which may be occur handling the multithreads.

Sleeping ? On this state, the thread is still alive but it is not runnable, it might be
return to runnable state later, if a particular event occurs. On this state a thread sleeps
for a specified amount of time. You can use the method sleep( ) to stop the running
state of a thread. 
static void sleep(long millisecond) throws InterruptedException

Waiting for Notification ? A thread waits for notification from another thread. The
thread sends back to runnable state after sending notification from another thread. 
Page 19
CS316– AJP UNIT-1
final void wait(long timeout) throws InterruptedException
final void wait(long timeout, int nanos) throws InterruptedException
final void wait() throws InterruptedException

Blocked on I/O ? The thread waits for completion of blocking operation. A thread can
enter on this state because of waiting I/O resource. In that case the thread sends back
to runnable state after availability of resources. 

Blocked for joint completion ? The thread can come on this state because of waiting 
the completion of another thread.

Blocked for lock acquisition ? The thread can come on this state because of waiting to
acquire the lock of an object. 



Methods that can be applied apply on a Thread:
Some Important Methods defined in java.lang.Thread are shown in the table:
Method
Return
Type
Description
currentThread( Thread
)
Returns an object reference to the thread in which it is
invoked.
getName( )
String
Retrieve the name of the thread object or instance.
start( )
void
Start the thread by calling its run method.
run( )
void
sleep( )
void
isAlive( )
boolean
activeCount( ) int
interrupt( )
yield( )
void
void
This method is the entry point to execute thread, like
the main method for applications.
Suspends a thread for a specified amount of time (in
milliseconds).
This method is used to determine the thread is running
or not.
This method returns the number of active threads in a
particular thread group and all its subgroups.
The method interrupt the threads on which it is
invoked.
By invoking this method the current thread pause its
execution temporarily and allow other threads to
execute.
Page 20
CS316– AJP UNIT-1
This method and join(long millisec) Throws
join( )
void
InterruptedException. These two methods are invoked
on a thread. These are not returned until either the
thread has completed or it is timed out respectively.
Program:
Import java.io.*
Class PipedStrem
{
Public static void main(String args[])
{
PipedOutputStream pos=new PipedOutputStream();
PipedInputStream pis=new PipedInputSTream();
try
{
pos.connect(pis);
new Producer(pos).start();
new Consumer(pos).start();
}
Catch(Exception e)
{
e.printStackTrace()
}
}
}
Class Producer extends Thread
{
Private PipedOutputStream pos;
Producer(PipedOutputStream pos)
{
this.pos=pos;
}
Public void run()
{
Try
{
Pos.write(“Hello welcome to III CSE”.getBytes());
Pos.flush();
Pos.close();
}
Catch(Exception e)
{
e.printStackTrace();
}
}
}
Class Consumer extends Thread
Page 21
CS316– AJP UNIT-1
{
Private PipedInputStream pis
Consumer(PipedInputStream pis)
{
this.pis=pis;
}
Public void run()
{
Try
{
Byte[] buf=new byte[100];
Int len=pis.read(buf);
System.out.println(new String(buf,0,len));
Pis.close();
}
Catch(Exception e)
{
e.printStackTrace();
}
}
}
Page 22
CS316– AJP UNIT-1
SWING:
Swing library is an official Java GUI toolkit released by Sun Microsystems. It is
used to create Graphical user interfaces with Java.
The main characteristics of the Swing toolkit



platform independent

configurable
 lightweight 
The Swing API has 18 public packages:


















javax.accessibility
ja
javax.swing.tree
javax.swing.undo
Page 23
CS316– AJP UNIT-1
Swing is an advanced GUI toolkit. It has a rich set of widgets. From basic widgets like
buttons, labels, scrollbars to advanced widgets like trees and tables. Swing itself is written in
Java.
Swing is a part of JFC, Java Foundation Classes. It is a collection of packages for creating
full featured desktop applications. JFC consists of AWT, Swing, Accessibility, Java 2D, and
Drag and Drop. Swing was released in 1997 with JDK 1.2. It is a mature toolkit. The Java
platform has Java2D library, which enables developers to create advanced 2D graphics
and imaging. There are basically two types of widget toolkits.




Lightweight 
Heavyweight 
There is also another GUI library for the Java programming language. It is called SWT.
The Standard widget toolkit. The SWT library was initially developed by the IBM
corporation. Now it is an open source project maintained by the Eclipse community. The
SWT is an example of a heavyweight toolkit. It lets the underlying OS to create GUI. SWT
uses the java native interface to do the job.
Swing Packages
javax.swing
The high level swing package primarily consists of components, adapters,
default component models and interfaces for all the delegates and models.
javax.swing.border
The border package declares the Border interface and classes, which define specific
border rendering styles.
javax.swing.plaf
The plaf package contains the Pluggable Look-and-Feel API for developers interested
in defining custom interfaces.
javax.swing.table
The table package contains the interfaces and classes, which support the Swing
table component.
javax.swing.text
The text package contains the support classes for the Swing
document framework. javax.swing.text.html
The text.html package contains the support classes for a basic HTML renderer.
javax.swing.undo
The undo package provides the support classes for implementing
undo/redo capabilities in a GUI.
javax.accessibility
The JFC Accessibility package is included with Swing and available for testing
Page 24
CS316– AJP UNIT-1
Widgets
This section describes how to use the various Swing widgets. Part of the
component hierarchy looks similar to AWT.
here are over double the number of components in Swing than in AWT. This second set of
components is what most appeals to developers, as it provides a much richer set of widgets to
use.
Page 25
CS316– AJP UNIT-1
Program
Calculator Program Applet
import
import
import
import
javax.swing.*;
java.awt.event.*;
java.awt.FlowLayout;
java.awt.BorderLayout;
public class CalcProgram extends JFrame implements ActionListener
Page 26
CS316– AJP UNIT-1
{
JTextField num1 = new JTextField("0.00");
JTextField num2 = new JTextField("0.00");
JLabel answer = new JLabel("0.00");
JLabel symbol = new JLabel("+");
JLabel equals = new JLabel("=");
JButton addButton = new JButton(" +
"); JButton subButton = new JButton(" "); public CalcProgram()
{
JPanel fields = new JPanel(new
FlowLayout()); fields.add(num1);
fields.add(symbol);
fields.add(num2);
fields.add(equals);
fields.add(answer);
JPanel buttons = new JPanel(new FlowLayout());
buttons.add(addButton);
buttons.add(subButton);
getContentPane().setLayout(new BorderLayout());
getContentPane().add("North", fields);
getContentPane().add("Center", buttons);
addButton.addActionListener(this);
subButton.addActionListener(this);
pack();
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
double x = Double.parseDouble(num1.getText());
double y = Double.parseDouble(num2.getText()); if
(e.getSource() == addButton)
{
answer.setText(String.valueOf( x + y ));
symbol.setText("+");
}
if (e.getSource() == subButton)
{
answer.setText(String.valueOf( x - y ));
symbol.setText("-");
}
}
public static void main(String args[])
{
CalcProgram c = new CalcProgram();
}
}
Page 27