Sunteți pe pagina 1din 62

CHAPTER 4

Java IO package
The java.io package contains nearly every class you might ever need to perform input and
output (I/O) in Java. All these streams represent an input source and an output destination. The
stream in the java.io package supports many data such as primitives, Object, localized
characters, etc.

A stream can be defined as a sequence of data. The InputStream is used to read data from a
source and the OutputStream is used for writing data to a destination.

The Java I/O package, a.k.a. java.io, provides a set of input streams and a set of output streams
used to read and write data to files or other input and output sources.

There are three categories of classes in java.io: input streams, output streams and everything else.

1)Input Streams

Input streams read data from an input source. An input source can be a file, a string, or memory--
anything that can contain data. All input streams inherit from InputStream--an abstract class that
defines the programming interface for all input streams.

The InputStream class defines a programming interface for reading bytes or arrays of bytes,
marking locations in the stream, skipping bytes of input, finding out the number of bytes that are
available for reading, and resetting the current position within the stream. An input stream is
automatically opened when you create it. You can explicitly close a stream with
the close() method, or let it be closed implicitly when the object is garbage collected.

2)Output Streams

Output streams write data to an output source. Similar to input sources, an output source can be
anything that can contain data: a file, a string, or memory.

The OutputStream class is a sibling to InputStream and is used to write data that can then be read
by an input stream. The OutputStream class defines a programming interface for writing bytes or
arrays of bytes to the stream and flushiing the stream. Like an input stream, an output stream is
automatically opened when you create it. You can explicitly close an output stream with
the close() method, or let it be closed implicitly when the object is garbage collected.

3)Everything Else

In addition to the streams classes, java.io contains a few other classes:


File
Represents a file on the host system.

1
RandomAccessFile
Represents a random access file.
StreamTokenizer
Tokenizes the contents of a stream.

Byte/Character Stream

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. Following is an example which makes use of these
two classes to copy an input file into an output file:

import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileInputStream in = null;
FileOutputStream out = null;

try {
in = new FileInputStream("input.txt");
out = new FileOutputStream("output.txt");

int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();

2
}
}
}
}
Now let's have a file input.txt with the following content:

This is test for copy file.


As a next step, compile above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put above code in CopyFile.java file
and do the following:

$javac CopyFile.java
$java CopyFile

Character Streams
Java Byte streams are used to perform input and output of 8-bit bytes, where as
JavaCharacter 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 major difference is that FileReader reads two bytes
at a time and FileWriter writes two bytes at a time.

We can re-write above example which makes use of these two classes to copy an input file
(having unicode characters) into an output file:

import java.io.*;

public class CopyFile {


public static void main(String args[]) throws IOException
{
FileReader in = null;
FileWriter out = null;

try {
in = new FileReader("input.txt");
out = new FileWriter("output.txt");
3
int c;
while ((c = in.read()) != -1) {
out.write(c);
}
}finally {
if (in != null) {
in.close();
}
if (out != null) {
out.close();
}
}
}
}
Now let's have a file input.txt with the following content:

This is test for copy file.


As a next step, compile above program and execute it, which will result in creating output.txt
file with the same content as we have in input.txt. So let's put above code in CopyFile.java file
and do the following:

$javac CopyFile.java
$java CopyFile

Buffered Reader/Writer

Buffered Reader

Introduction
The Java.io.BufferedReader class reads text from a character-input stream, buffering
characters so as to provide for the efficient reading of characters, arrays, and lines.

Following are the important points about BufferedReader:

4
 The buffer size may be specified, or the default size may be used.

 Each read request made of a Reader causes a corresponding read request to be made of
the underlying character or byte stream.

Class declaration
Following is the declaration for Java.io.BufferedReader class:

public class BufferedReader


extends Reader

The java.io.BufferedReader.read() method reads a single character from this buffered reader.

Example
The following example shows the usage of java.io.BufferedReader.read() method.

package com.tutorialspoint;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

public class BufferedReaderDemo {


public static void main(String[] args) throws Exception {

InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;

try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");

// create new input stream reader


isr = new InputStreamReader(is);

5
// create new buffered reader
br = new BufferedReader(isr);

int value=0;

// reads to the end of the stream


while((value = br.read()) != -1)
{
// converts int to character
char c = (char)value;

// prints character
System.out.println(c);
}

}catch(Exception e){
e.printStackTrace();
}finally{

// releases resources associated with the streams


if(is!=null)
is.close();
if(isr!=null)
isr.close();
if(br!=null)
br.close();
}
}
}

Assuming we have a text file c:/test.txt, which has the following content. This file will be used
as an input for our example program:

6
ABCDE
Let us compile and run the above program, this will produce the following result:

A
B
C
D
E

Buffered Writer
Introduction
The Java.io.BufferedWriter class writes text to a character-output stream, buffering characters
so as to provide for the efficient writing of single characters, arrays, and strings.Following are
the important points about BufferedWriter:

 The buffer size may be specified, or the default size may be used.

 A Writer sends its output immediately to the underlying character or byte stream.

Example
The following example shows the usage of java.io.BufferedWriter.write(String str) method.

package com.tutorialspoint;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.StringWriter;

public class BufferedWriterDemo {


public static void main(String[] args) throws IOException {

StringWriter sw = null;
BufferedWriter bw = null;

String str = "Hello World!";

7
try{
// create string writer
sw = new StringWriter();

//create buffered writer


bw = new BufferedWriter(sw);

// writing string to writer


bw.write(str);

// forces out the characters to string writer


bw.flush();

// string buffer is created


StringBuffer sb = sw.getBuffer();

//prints the string


System.out.println(sb);

}catch(IOException e){
// if I/O error occurs
e.printStackTrace();
}finally{
// releases any system resources associated with the stream
if(sw!=null)
sw.close();
if(bw!=null)
bw.close();
}
}
}
Let us compile and run the above program, this will produce the following result:

8
Hello World!

Reader

The Reader is the base class of all Reader's in the Java IO API. Subclasses include
a BufferedReader,PushbackReader, InputStreamReader, StringReader and several others.

Here is a simple Java IO Reader example:

Reader reader = new FileReader("c:\\data\\myfile.txt");

int data = reader.read();

while(data != -1){

char dataChar = (char) data;

data = reader.read();

Notice, that while an InputStream returns one byte at a time, meaning a value between 0 and 255
(or -1 if the stream has no more data), the Reader returns a char at a time, meaning a value
between 0 and 65535 (or -1 if the stream has no more data). This does not necessarily mean that
the Reader reads two bytes at a time from the source it is connected to. It may read one or more
bytes at a time, depending on the encoding of the text being read.

Combining Readers With InputStreams

A Reader can be combined with an InputStream. If you have an InputStream and want to read
characters from it, you can wrap it in an InputStreamReader. Pass the InputStream to the
constructor of theInputStreamReader like this:

Reader reader = new InputStreamReader(inputStream);

In the constructor you can also specify what character set to use to decode the text etc. More on
that in the text on InputStreamReader.

9
Writer

The Writer class is the base class of all Writers in the Java IO API. Subclasses
include BufferedWriterand PrintWriter among others.

Here is a simple Java IO Writer example:

Writer writer = new FileWriter("c:\\data\\file-output.txt");

writer.write("Hello World Writer");

writer.close();

Combining Writers With OutputStreams

A Writer can be combined with an OutputStream just like Readers and InputStream's. Wrap
theOutputStream in an OutputStreamWriter and all characters written to the Writer are passed
on to theOutputStream. Here is an OutputStreamWriter example:

Writer writer = new OutputStreamWriter(outputStream);

Combining Readers and Writers

Just like with streams, Reader's and Writer's can be combined into chains to achieve more
interesting IO. It works just like combining the Reader with InputStream's or
the Writer with OutputStream's. For instance, you can achieve buffering by wrapping a Reader in
a BufferedReader, or a Writer in a BufferedWriter. Here are two such examples:

Reader reader = new BufferedReader(new FileReader(...));

Writer writer = new BufferedWriter(new FileWriter(...));

Java IO: PrintWriter

The PrintWriter class enables you to write formatted data to an underlying Writer. For instance,
writingint, long and other primtive data formatted as text, rather than as their byte values.

Here is a simple example:

10
PrintWriter writer = new PrintWriter(writer);

writer.print(true);

writer.print((int) 123);

writer.print((float) 123.456);

writer.printf(Locale.UK, "Text + data: %1$", 123);

writer.close();

The PrintWriter class contains the powerful format() and printf() methods (they do exactly the
same, but the name "printf" is more familiar to C-programmers). These methods allow you to
mix text and data in very advanced ways, using a formatting string. For more information
about format() and printf() see the JavaDoc.

The PrintWriter has a wide selection of contructors that enable you to connect it to a File,
anOutputStream, or a Writer.

RandomAccessFile – Reading Sequentially and Randomly

A file can be read either sequentially (continuously) or randomly (here and there). So far, in all
the programs, what we have done is sequential access, starting from the beginning of the file to
the end of the file. Or we have skipped some bytes in a file and read the remaining bytes of the
file with skip() method. In random access, the file pointer is taken to a specific byte and that byte
is read or modified. To support random access (to read and write at any position in a file), there
comes special class – java.io.RandomAccessFile.

Random access is very much required in quick accessing the data randomly as in the case of
super bazaar billing, help desk in a bank or railways and airline reservations etc. These types of
programs where quick response is required are known as mission critical operations.

11
The java.io.RandomAccessFile is very special as it contains unique features that other I/O
streams do not.
1. It is not a subclass of InputStream or OutputStream. It is a direct subclass of Object
class, but placed in java.io package.
2. It neighter an input stream nor output stream as it can do both the jobs of reading and
writing. For this reason, while opening the file with RandomAccessFile class, we must
specify the mode – read mode or write mode.
3. It can read or write a file both sequentially and randomly.
4. It includes the methods for reading and writing. All the methods of DataInputStream
class and DataOutputStream classes are available in RandomAccessFile (as it implements
both DataInput and DataOutput interfaces) like readInt(), writeInt(), readDouble() and
writeDouble() etc.
Following is the class signature

public class RandomAccessFile extends Object implements DataOutput, DataInput


The two important modes supported byRandomAccessFile are "r" and "rw".
Reading randomly with RandomAccessFile
In the following program, a file, xyz.txt is opened which is initially empty. In a for loop, 10
integer values are written sequentially and then also read sequentially. Later, the file pointer is
taken to a specific integer value and then the value is read and later also modified.
The file operations done with RandomAccessFile in the program are:

1 import java.io.*;
2 public class RAFDemo
3 {
4 public static void main(String args[]) throws IOException
5 {
6 RandomAccessFile rafile = new RandomAccessFile("xyz.txt", "rw");
7 // writing 10 integer values sequentially one after another
8 for(int i = 0; i < 10; i++)
9 {
10 rafile.writeInt(i*5);
11 }
12 // to know the file pointer position in the file
13 System.out.println("File pointer position before skipping: " + rafile.getFilePointer());
14
15 // to shift the file pointer to 0 (starting) position to read from beginning
16 rafile.seek(0);
17 System.out.println("File pointer position after skipping: " + rafile.getFilePointer());
18
19 System.out.println("Reading sequentially one after another:");
20 for(int i = 0; i < 10; i++)
21 {
22 System.out.println(rafile.readInt());
23 }

12
24 // to read randomly 4th integer value
25 rafile.seek(3*4); // 3 integer values of size 4 bytes each
26 System.out.println("4th integer value reading randomly: " + rafile.readInt());
27
28 // to change randomly the 7th intger value
29 rafile.seek(6*4); // 6 integer values of size 4 bytes each
30
31 rafile.writeInt(12345);
32 // to read and print again sequentially
33 rafile.seek(0); // again place the file pointer at the start
34 System.out.println("\nValues after modification of 7th integer value randomly");
35 for(int i = 0; i < 10; i++)
36 {
37 System.out.println(rafile.readInt());
38 }
39 rafile.close();
40 }
41 }

13
CHAPTER 5
COMPONENTS AND GRAPHICS

Graphical User Interface


Graphical User Interface (GUI) offers user interaction via some graphical
components. For example our underlying Operating System also offers GUI via
window,frame,Panel, Button, Textfield, TextArea, Listbox, Combobox, Label,
Checkbox etc. These all are known as components. Using these components we
can create an interactive user interface for an application.
GUI provides result to end user in response to raised events.GUI is entirely based
events. For example clicking over a button, closing a window, opening a window,
typing something in a textarea etc. These activities are known as events.GUI
makes it easier for the end user to use an application. It also makes them
interesting.

Basic Terminologies
Term Description

Component Component is an object having a graphical representation that can be displayed on the
screen and that can interact with the user. For examples buttons, checkboxes, list and
scrollbars of a graphical user interface.

Container Container object is a component that can contain other components.Components added to
a container are tracked in a list. The order of the list will define the components' front-to-
back stacking order within the container. If no index is specified when adding a component
to a container, it will be added to the end of the list.

Panel Panel provides space in which an application can attach any other components, including
other panels.

Window Window is a rectangular area which is displayed on the screen. In different window we can
execute different program and display different data. Window provide us with multitasking
environment. A window must have either a frame, dialog, or another window defined as its
owner when it's constructed.

Frame A Frame is a top-level window with a title and a border. The size of the frame includes any
area designated for the border. Frame encapsulateswindow. It and has a title bar, menu
bar, borders, and resizing corners.

14
Canvas Canvas component represents a blank rectangular area of the screen onto which the
application can draw. Application can also trap input events from the use from that blank
area of Canvas component.

Examples of GUI based Applications


Following are some of the examples for GUI based applications.
 Automated Teller Machine (ATM)
 Airline Ticketing System
 Information Kiosks at railway stations
 Mobile Applications
 Navigation Systems

Advantages of GUI over CUI


 GUI provides graphical icons to interact while the CUI (Character User Interface) offers
the simple text-based interfaces.

 GUI makes the application more entertaining and interesting on the other hand CUI does
not.

 GUI offers click and execute environment while in CUI every time we have to enter the
command for a task.

 New user can easily interact with graphical user interface by the visual indicators but it is
difficult in Character user interface.

 GUI offers a lot of controls of file system and the operating system while in CUI you
have to use commands which is difficult to remember.

 Windows concept in GUI allow the user to view, manipulate and control the multiple
applications at once while in CUI user can control one task at a time.

 GUI provides multitasking environment so as the CUI also does but CUI does not
provide same ease as the GUI do.

 Using GUI it is easier to control and navigate the operating system which becomes very
slow in command user interface. GUI can be easily customized.

15
AWT GRAPHICS CLASS

Introduction
The Graphics class is the abstract super class for all graphics contexts which allow an application to draw
onto components that can be realized on various devices, or onto off-screen images as well.

A Graphics object encapsulates all state information required for the basic rendering operations that Java
supports. State information includes the following properties.

 The Component object on which to draw.

 A translation origin for rendering and clipping coordinates.

 The current clip.

 The current color.

 The current font.

 The current logical pixel operation function.

 The current XOR alternation color

Class declaration
Following is the declaration for java.awt.Graphics class:

public abstract class Graphics

extends Object

Class constructors
S.N. Constructor & Description

1
Graphics() ()

Constructs a new Graphics object.

16
Class methods
S.N. Method & Description

1
abstract void clearRect(int x, int y, int width, int height)

Clears the specified rectangle by filling it with the background color of the current drawing
surface.

2
abstract void clipRect(int x, int y, int width, int height)

Intersects the current clip with the specified rectangle.

3
abstract void copyArea(int x, int y, int width, int height, int dx, int dy)

Copies an area of the component by a distance specified by dx and dy.

4
abstract Graphics create()

Creates a new Graphics object that is a copy of this Graphics object.

5
Graphics create(int x, int y, int width, int height)

Creates a new Graphics object based on this Graphics object, but with a new translation and
clip area.

6
abstract void dispose()

Disposes of this graphics context and releases any system resources that it is using.

7
void draw3DRect(int x, int y, int width, int height, boolean raised)

Draws a 3-D highlighted outline of the specified rectangle.

17
8
abstract void drawArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Draws the outline of a circular or elliptical arc covering the specified rectangle.

9
void drawBytes(byte[] data, int offset, int length, int x, int y)

Draws the text given by the specified byte array, using this graphics context's current font and
color.

10
void drawChars(char[] data, int offset, int length, int x, int y)

Draws the text given by the specified character array, using this graphics context's current font
and color.

11
abstract boolean drawImage(Image img, int x, int y, Color bgcolor, ImageObserver
observer)

Draws as much of the specified image as is currently available.

12
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)

Draws as much of the specified image as is currently available.

13
abstract boolean drawImage(Image img, int x, int y, int width, int height, Color bgcolor,
ImageObserver observer)

Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.

14
abstract boolean drawImage(Image img, int x, int y, int width, int height, ImageObserver
observer)

Draws as much of the specified image as has already been scaled to fit inside the specified
rectangle.

18
15
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1,
int sx2, int sy2, Color bgcolor, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.

16
abstract boolean drawImage(Image img, int dx1, int dy1, int dx2, int dy2, int sx1, int sy1,
int sx2, int sy2, ImageObserver observer)

Draws as much of the specified area of the specified image as is currently available, scaling it
on the fly to fit inside the specified area of the destination drawable surface.

17
abstract void drawLine(int x1, int y1, int x2, int y2)

Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this graphics
context's coordinate system.

18
abstract void drawOval(int x, int y, int width, int height)

Draws the outline of an oval.

19
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)

Draws a closed polygon defined by arrays of x and y coordinates.

20
void drawPolygon(Polygon p)

Draws the outline of a polygon defined by the specified Polygon object.

21
abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)

Draws a sequence of connected lines defined by arrays of x and y coordinates.

22
void drawRect(int x, int y, int width, int height)

19
Draws the outline of the specified rectangle.

23
abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)

Draws an outlined round-cornered rectangle using this graphics context's current color.

24
abstract void drawString(AttributedCharacterIterator iterator, int x, int y)

Renders the text of the specified iterator applying its attributes in accordance with the
specification of the TextAttribute class.

25
abstract void drawString(String str, int x, int y)

Draws the text given by the specified string, using this graphics context's current font and
color.

26
void fill3DRect(int x, int y, int width, int height, boolean raised)

Paints a 3-D highlighted rectangle filled with the current color.

27
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)

Fills a circular or elliptical arc covering the specified rectangle.

28
abstract void fillOval(int x, int y, int width, int height)

Fills an oval bounded by the specified rectangle with the current color.

29
abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)

Fills a closed polygon defined by arrays of x and y coordinates.

20
30
void fillPolygon(Polygon p)

Fills the polygon defined by the specified Polygon object with the graphics context's current
color.

31
abstract void fillRect(int x, int y, int width, int height)

Fills the specified rectangle.

32
abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight)

Fills the specified rounded corner rectangle with the current color.

33
void finalize()

Disposes of this graphics context once it is no longer referenced.

34
abstract Shape getClip()

Gets the current clipping area.

35
abstract Rectangle getClipBounds()

Returns the bounding rectangle of the current clipping area.

36
Rectangle getClipBounds(Rectangle r)

Returns the bounding rectangle of the current clipping area.

37
Rectangle getClipRect()

Deprecated. As of JDK version 1.1, replaced by getClipBounds().

38
abstract Color getColor()

21
Gets this graphics context's current color.

39
abstract Font getFont()

Gets the current font.

40
FontMetrics getFontMetrics()

Gets the font metrics of the current font.

41
abstract FontMetrics getFontMetrics(Font f)

Gets the font metrics for the specified font.

42
boolean hitClip(int x, int y, int width, int height)

Returns true if the specified rectangular area might intersect the current clipping area.

43
abstract void setClip(int x, int y, int width, int height)

Sets the current clip to the rectangle specified by the given coordinates.

44
abstract void setClip(Shape clip)

Sets the current clipping area to an arbitrary clip shape.

45
abstract void setColor(Color c)

Sets this graphics context's current color to the specified color.

46
abstract void setFont(Font font)

Sets this graphics context's font to the specified font.

22
47
abstract void setPaintMode()

Sets the paint mode of this graphics context to overwrite the destination with this graphics
context's current color.

48
abstract void setXORMode(Color c1)

Sets the paint mode of this graphics context to alternate between this graphics context's current
color and the new specified color.

49
String toString()

Returns a String object representing this Graphics object's value.

50
abstract void translate(int x, int y)

Translates the origin of the graphics context to the point (x, y) in the current coordinate system.

Methods inherited
This class inherits methods from the following classes:

 java.lang.Object

Graphics Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint
> gui >

AWTGraphicsDemo.java

package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

import java.awt.geom.*;

public class AWTGraphicsDemo extends Frame {

23
public AWTGraphicsDemo(){

super("Java AWT Examples");

prepareGUI();

public static void main(String[] args){

AWTGraphicsDemo awtGraphicsDemo = new AWTGraphicsDemo();

awtGraphicsDemo.setVisible(true);

private void prepareGUI(){

setSize(400,400);

addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

@Override

public void paint(Graphics g) {

g.setColor(Color.GRAY);

Font font = new Font("Serif", Font.PLAIN, 24);

g.setFont(font);

g.drawString("Welcome to TutorialsPoint", 50, 150);

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AWTGraphicsDemo.java

If no error comes that means compilation is successful. Run the program using following command.

24
D:\AWT>java com.tutorialspoint.gui.AWTGraphicsDemo

Verify the following output

AWT Containers
Containers are integral part of AWT GUI components. A container provides a space where a component
can be located. A Container in AWT is a component itself and it adds the capability to add component to
itself. Following are noticable points to be considered.

 Sub classes of Container are called as Containter. For example Panel, Frame and Window.

 Container can add only Component to itself.

 A default layout is present in each container which can be overridden using setLayout method.

Sr. No. Container & Description

25
1
Container

It is a generic container object which can contain other AWT components.

AWT UI Elements:
Following is the list of commonly used containers while designed GUI using AWT.

Sr. Container & Description


No.

1
Panel

Panel is the simplest container. It provides space in which any other component can be placed,
including other panels.

2
Frame

A Frame is a top-level window with a title and a border

3
Window

A Window object is a top-level window with no borders and no menubar.

AWT Container Class

Introduction
The class Container is the super class for the containers of AWT. Container
object can contain other AWT components.

Class declaration
Following is the declaration for java.awt.Container class:

public class Container

extends Component

26
Class constructors
S.N. Constructor & Description

1
Container()

This creates a new Container.

Class methods
S.N. Method & Description

1
Component add(Component comp)

Appends the specified component to the end of this container.

2
Component add(Component comp, int index)

Adds the specified component to this container at the given position.

3
void add(Component comp, Object constraints)

Adds the specified component to the end of this container.

4
void add(Component comp, Object constraints, int index)

Adds the specified component to this container with the specified constraints at the specified
index.

5
Component add(String name, Component comp)

Adds the specified component to this container.

6
void addContainerListener(ContainerListener l)

Adds the specified container listener to receive container events from this container.

7
protected void addImpl(Component comp, Object constraints, int index)

Adds the specified component to this container at the specified index.

27
8
void addNotify()

Makes this Container displayable by connecting it to a native screen resource.

9
void addPropertyChangeListener(PropertyChangeListener listener)

Adds a PropertyChangeListener to the listener list.

10
void add Property Change Listener(String proper tyName, Property Change Listener
listener)

Adds a PropertyChangeListener to the listener list for a specific property.

11
void applyComponentOrientation(ComponentOrientation o)

Sets the ComponentOrientation property of this container and all components contained within
it.

12
boolean areFocusTraversalKeysSet(int id)

Returns whether the Set of focus traversal keys for the given focus traversal operation has been
explicitly defined for this Container.

13
int countComponents()

Deprecated. As of JDK version 1.1, replaced by getComponentCount().

14
void deliverEvent(Event e)

Deprecated. As of JDK version 1.1, replaced by dispatchEvent(AWTEvent e)

15
void doLayout()

Causes this container to lay out its components.

16
Component findComponentAt(int x, int y)

Locates the visible child component that contains the specified position.

17
Component findComponentAt(Point p)

28
Locates the visible child component that contains the specified point.

18
float getAlignmentX()

Returns the alignment along the x axis.

19
float getAlignmentY()

Returns the alignment along the y axis.

20
Component getComponent(int n)

Gets the nth component in this container.

21
Component getComponentAt(int x, int y)

Locates the component that contains the x,y position.

22
Component getComponentAt(Point p)

Gets the component that contains the specified point.

23
int getComponentCount()

Gets the number of components in this panel.

24
Component[] getComponents()

Gets all the components in this container.

25
int getComponentZOrder(Component comp)

Returns the z-order index of the component inside the container.

26
ContainerListener[] getContainerListeners()

Returns an array of all the container listeners registered on this container.

27
Set<AWTKeyStroke> getFocusTraversalKeys(int id)

29
Returns the Set of focus traversal keys for a given traversal operation for this Container.

28
FocusTraversalPolicy getFocusTraversalPolicy()

Returns the focus traversal policy that will manage keyboard traversal of this Container's
children, or null if this Container is not a focus cycle root.

29
Insets getInsets()

Determines the insets of this container, which indicate the size of the container's border.

30
LayoutManager getLayout()

Gets the layout manager for this container.

31
<T extends EventListener> T[] getListeners(Class<T> listenerType)

Returns an array of all the objects currently registered as FooListeners upon this Container.

32
Dimension getMaximumSize()

Returns the maximum size of this container.

33
Dimension getMinimumSize()

Returns the minimum size of this container.

34
Point getMousePosition(boolean allowChildren)

Returns the position of the mouse pointer in this Container's coordinate space if the Container is
under the mouse pointer, otherwise returns null.

35
Dimension getPreferredSize()

Returns the preferred size of this container.

36
Insets insets()

Deprecated. As of JDK version 1.1, replaced by getInsets().

30
37
void invalidate()

Invalidates the container.

38
boolean isAncestorOf(Component c)

Checks if the component is contained in the component hierarchy of this container.

39
boolean isFocusCycleRoot()

Returns whether this Container is the root of a focus traversal cycle.

40
boolean isFocusCycleRoot(Container container)

Returns whether the specified Container is the focus cycle root of this Container's focus
traversal cycle.

41
boolean isFocusTraversalPolicyProvider()

Returns whether this container provides focus traversal policy.

42
boolean isFocusTraversalPolicySet()

Returns whether the focus traversal policy has been explicitly set for this Container.

43
void layout()

Deprecated. As of JDK version 1.1, replaced by doLayout().

44
void list(PrintStream out, int indent)

Prints a listing of this container to the specified output stream.

45
void list(PrintWriter out, int indent)

Prints out a list, starting at the specified indentation, to the specified print writer.

46
Component locate(int x, int y)

Deprecated. As of JDK version 1.1, replaced by getComponentAt(int, int).

31
47
Dimension minimumSize()

Deprecated. As of JDK version 1.1, replaced by getMinimumSize().

48
void paint(Graphics g)

Paints the container.

49
void paintComponents(Graphics g)

Paints each of the components in this container.

50
protected String paramString()

Returns a string representing the state of this Container.

51
Dimension preferredSize()

Deprecated. As of JDK version 1.1, replaced by getPreferredSize().

52
void print(Graphics g)

Prints the container.

53
void printComponents(Graphics g)

Prints each of the components in this container.

54
protected void processContainerEvent(ContainerEvent e)

Processes container events occurring on this container by dispatching them to any registered
ContainerListener objects.

55
protected void processEvent(AWTEvent e)

Processes events on this container.

56
void remove(Component comp)

Removes the specified component from this container.

32
57
void remove(int index)

Removes the component, specified by index, from this container.

58
void removeAll()

Removes all the components from this container.

59
void removeContainerListener(ContainerListener l)

Removes the specified container listener so it no longer receives container events from this
container.

60
void removeNotify()

Makes this Container undisplayable by removing its connection to its native screen resource.

61
void setComponentZOrder(Component comp, int index)

Moves the specified component to the specified z-order index in the container.

62
void setFocusCycleRoot(boolean focusCycleRoot)

Sets whether this Container is the root of a focus traversal cycle.

63
void setFocusTraversalKeys(int id, Set<? extends AWTKeyStroke> keystrokes)

Sets the focus traversal keys for a given traversal operation for this Container.

64
void setFocusTraversalPolicy(FocusTraversalPolicy policy)

Sets the focus traversal policy that will manage keyboard traversal of this Container's children,
if this Container is a focus cycle root.

65
void setFocusTraversalPolicyProvider(boolean provider)

Sets whether this container will be used to provide focus traversal policy.

66
void setFont(Font f)

Sets the font of this container.

33
67
void setLayout(LayoutManager mgr)

Sets the layout manager for this container.

68
void transferFocusBackward()

Transfers the focus to the previous component, as though this Component were the focus
owner.

69
void transferFocusDownCycle()

Transfers the focus down one focus traversal cycle.

70
void update(Graphics g)

Updates the container.

71
void validate()

Validates this container and all of its subcomponents.

72
protected void validateTree()

Recursively descends the container tree and recomputes the layout for any subtrees marked as
needing it (those marked as invalid).

Methods inherited
This class inherits methods from the following classes:

 java.awt.Component

 java.lang.Object

34
AWT Panel Class

Introduction
The class Panel is the simplest container class. It provides space in which an
application can attach any other component, including other panels. It uses
FlowLayout as default layout manager.

Class declaration
Following is the declaration for java.awt.Panel class:

public class Panel


extends Container
implements Accessible

Class constructors
S.N. Constructor & Description

1
Panel()

Creates a new panel using the default layout manager.

2
Panel(LayoutManager layout)

Creates a new panel with the specified layout manager.

Class methods
S.N. Method & Description

1
void addNotify()

35
Creates the Panel's peer.

2
AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Panel.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Container

 java.awt.Component

 java.lang.Object

Panel Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtContainerDemo.java

package com.tutorialspoint.gui;

import java.awt.*;
import java.awt.event.*;

public class AwtContainerDemo {


private Frame mainFrame;
private Label headerLabel;
private Label statusLabel;
private Panel controlPanel;
private Label msglabel;

36
public AwtContainerDemo(){
prepareGUI();
}

public static void main(String[] args){


AwtContainerDemo awtContainerDemo = new
AwtContainerDemo();
awtContainerDemo.showPanelDemo();
}

private void prepareGUI(){


mainFrame = new Frame("Java AWT Examples");
mainFrame.setSize(400,400);
mainFrame.setLayout(new GridLayout(3, 1));
mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){


System.exit(0);
}
});

37
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);

msglabel = new Label();


msglabel.setAlignment(Label.CENTER);
msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

controlPanel = new Panel();


controlPanel.setLayout(new FlowLayout());

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

private void showPanelDemo(){


headerLabel.setText("Container in action: Panel");

Panel panel = new Panel();


panel.setBackground(Color.magenta);
panel.setLayout(new FlowLayout());
panel.add(msglabel);

controlPanel.add(panel);

38
mainFrame.setVisible(true);
}
}

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Verify the following output

39
AWT Frame Class

Introduction
The class Frame is a top level window with border and title. It uses BorderLayout as default
layout manager.

Class declaration
Following is the declaration for java.awt.Frame class:

public class Frame


extends Window
implements MenuContainer
Field
Following are the fields for java.awt.Frame class:

 static float BOTTOM_ALIGNMENT -- Ease-of-use constant for getAlignmentY.

 static int CROSSHAIR_CURSOR -- Deprecated. replaced by Cursor.CROSSHAIR_CURSOR.

 static int DEFAULT_CURSOR -- Deprecated. replaced by Cursor.DEFAULT_CURSOR.

 static int E_RESIZE_CURSOR -- Deprecated. replaced by Cursor.E_RESIZE_CURSOR.

 static int HAND_CURSOR -- Deprecated. replaced by Cursor.HAND_CURSOR.

 static int ICONIFIED -- This state bit indicates that frame is iconified.

 static int MAXIMIZED_BOTH -- This state bit mask indicates that frame is fully maximized (that is both horizontally and
vertically).

 static int MAXIMIZED_HORIZ -- This state bit indicates that frame is maximized in the horizontal direction.

40
 static int MAXIMIZED_VERT -- This state bit indicates that frame is maximized in the vertical direction.

 static int MOVE_CURSOR -- Deprecated. replaced by Cursor.MOVE_CURSOR.

 static int N_RESIZE_CURSOR -- Deprecated. replaced by Cursor.N_RESIZE_CURSOR.

 static int NE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NE_RESIZE_CURSOR.

 static int NORMAL -- Frame is in the "normal" state.

 static int NW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.NW_RESIZE_CURSOR.

 static int S_RESIZE_CURSOR -- Deprecated. replaced by Cursor.S_RESIZE_CURSOR.

 static int SE_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SE_RESIZE_CURSOR.

 static int SW_RESIZE_CURSOR -- Deprecated. replaced by Cursor.SW_RESIZE_CURSOR.

 static int TEXT_CURSOR -- Deprecated. replaced by Cursor.TEXT_CURSOR.

 static int W_RESIZE_CURSOR -- Deprecated. replaced by Cursor.W_RESIZE_CURSOR.

 static int WAIT_CURSOR -- Deprecated. replaced by Cursor.WAIT_CURSOR.

Class constructors
S.N. Constructor & Description

1
Frame()
Constructs a new instance of Frame that is
initially invisible.

2
Frame(GraphicsConfiguration gc)
Constructs a new, initially invisible Frame with
the specified GraphicsConfiguration.

3
Frame(String title)
Constructs a new, initially invisible Frame
object with the specified title.

41
4
Frame(String title, GraphicsConfiguration
gc)
Constructs a new, initially invisible Frame
object with the specified title and a
GraphicsConfiguration.

Class methods
S.N. Method & Description

1
void addNotify()

Makes this Frame displayable by connecting it to a native screen resource.

2
AccessibleContext getAccessibleContext()

Gets the AccessibleContext associated with this Frame.

3
int getCursorType()

Deprecated. As of JDK version 1.1, replaced by Component.getCursor().

4
int getExtendedState()

Gets the state of this frame.

5
static Frame[] getFrames()

Returns an array of all Frames created by this application.

6
Image getIconImage()

Returns the image to be displayed as the icon for this frame.

7
Rectangle getMaximizedBounds()

Gets maximized bounds for this frame.

42
8
MenuBar getMenuBar()

Gets the menu bar for this frame.

9
int getState()

Gets the state of this frame (obsolete).

10
String getTitle()

Gets the title of the frame.

11
boolean isResizable()

Indicates whether this frame is resizable by the user.

12
boolean isUndecorated()

Indicates whether this frame is undecorated.

13
protected String paramString()

Returns a string representing the state of this Frame.

14
void remove(MenuComponent m)

Removes the specified menu bar from this frame.

15
void removeNotify()

Makes this Frame undisplayable by removing its connection to its native screen resource.

16
void setCursor(int cursorType)

Deprecated. As of JDK version 1.1, replaced by Component.setCursor(Cursor).

17
void setExtendedState(int state)

Sets the state of this frame.

43
18
void setIconImage(Image image)

Sets the image to be displayed as the icon for this window.

19
void setMaximizedBounds(Rectangle bounds)

Sets the maximized bounds for this frame.

20
void setMenuBar(MenuBar mb)

Sets the menu bar for this frame to the specified menu bar.

21
void setResizable(boolean resizable)

Sets whether this frame is resizable by the user.

22
void setState(int state)

Sets the state of this frame (obsolete).

23
void setTitle(String title)

Sets the title for this frame to the specified string.

24
void setUndecorated(boolean undecorated)

Disables or enables decorations for this frame.

Methods inherited
This class inherits methods from the following classes:

 java.awt.Window

 java.awt.Container

 java.awt.Component

 java.lang.Object

Frame Example
Create the following java program using any editor of your choice in say D:/ > AWT > com > tutorialspoint > gui >

AwtContainerDemo.java

44
package com.tutorialspoint.gui;

import java.awt.*;

import java.awt.event.*;

public class AwtContainerDemo {

private Frame mainFrame;

private Label headerLabel;

private Label statusLabel;

private Panel controlPanel;

private Label msglabel;

public AwtContainerDemo(){

prepareGUI();

public static void main(String[] args){

AwtContainerDemo awtContainerDemo = new AwtContainerDemo();

awtContainerDemo.showFrameDemo();

private void prepareGUI(){

mainFrame = new Frame("Java AWT Examples");

mainFrame.setSize(400,400);

mainFrame.setLayout(new GridLayout(3, 1));

mainFrame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

System.exit(0);

});

headerLabel = new Label();

headerLabel.setAlignment(Label.CENTER);

statusLabel = new Label();

statusLabel.setAlignment(Label.CENTER);

statusLabel.setSize(350,100);

msglabel = new Label();

msglabel.setAlignment(Label.CENTER);

msglabel.setText("Welcome to TutorialsPoint AWT Tutorial.");

controlPanel = new Panel();

controlPanel.setLayout(new FlowLayout());

45
mainFrame.add(headerLabel);

mainFrame.add(controlPanel);

mainFrame.add(statusLabel);

mainFrame.setVisible(true);

private void showFrameDemo(){

headerLabel.setText("Container in action: Frame");

final Frame frame = new Frame();

frame.setSize(300, 300);

frame.setLayout(new FlowLayout());

frame.add(msglabel);

frame.addWindowListener(new WindowAdapter() {

public void windowClosing(WindowEvent windowEvent){

frame.dispose();

});

Button okButton = new Button("Open a Frame");

okButton.addActionListener(new ActionListener() {

public void actionPerformed(ActionEvent e) {

statusLabel.setText("A Frame shown to the user.");

frame.setVisible(true);

});

controlPanel.add(okButton);

mainFrame.setVisible(true);

Compile the program using command prompt. Go to D:/ > AWT and type the following command.

D:\AWT>javac com\tutorialspoint\gui\AwtContainerDemo.java

If no error comes that means compilation is successful. Run the program using following command.

D:\AWT>java com.tutorialspoint.gui.AwtContainerDemo

Verify the following output

46
AWT Layouts
Introduction
Layout means the arrangement of components within the container. In other way
we can say that placing the components at a particular position within the
container. The task of layouting the controls is done automatically by the Layout
Manager.

Layout Manager
The layout manager automatically positions all the components within the
container. If we do not use layout manager then also the components are
positioned by the default layout manager. It is possible to layout the controls by
hand but it becomes very difficult because of the following two reasons.

 It is very tedious to handle a large number of controls within the container.

 Oftenly the width and height information of a component is not given when
we need to arrange them.

47
Java provide us with various layout manager to position the controls. The
properties like size,shape and arrangement varies from one layout manager to
other layout manager. When the size of the applet or the application window
changes the size, shape and arrangement of the components also changes in
response i.e. the layout managers adapt to the dimensions of appletviewer or the
application window.

The layout manager is associated with every Container object. Each layout
manager is an object of the class that implements the LayoutManager interface.

Following are the interfaces defining functionalities of Layout Managers.

Sr. Interface & Description


No.

1 LayoutManager
The LayoutManager interface declares those
methods which need to be implemented by the class
whose object will act as a layout manager.

2 LayoutManager2
The LayoutManager2 is the sub-interface of the
LayoutManager.This interface is for those classes
that know how to layout containers based on layout
constraint object.

AWT Layout Manager Classes:


Following is the list of commonly used controls while designed GUI using AWT.

Sr. LayoutManager & Description


No.

1
BorderLayout
The borderlayout arranges the components to fit in the
five regions: east, west, north, south and center.

48
2
CardLayout
The CardLayout object treats each component in the
container as a card. Only one card is visible at a time.

3
FlowLayout
The FlowLayout is the default layout.It layouts the
components in a directional flow.

4
GridLayout
The GridLayout manages the components in form of a
rectangular grid.

5
GridBagLayout
This is the most flexible layout manager class.The
object of GridBagLayout aligns the component
vertically,horizontally or along their baseline without
requiring the components of same size.

AWT LayoutManager Interface

Introduction
The interfaceLayoutManager is used to define the interface for classes that know how to lay
out Containers.

Class declaration
Following is the declaration for java.awt.LayoutManager interface:

public interface LayoutManager

Interface methods
S.N. Method & Description

49
1
void addLayoutComponent(String name,
Component comp)
If the layout manager uses a per-component string,
adds the component comp to the layout, associating it
with the string specified by name.

2
void layoutContainer(Container parent)
Lays out the specified container.

3
Dimension minimumLayoutSize(Container parent)
Calculates the minimum size dimensions for the
specified container, given the components it contains.

4
Dimension preferredLayoutSize(Container parent)
Calculates the preferred size dimensions for the
specified container, given the components it contains.

5
void removeLayoutComponent(Component comp)
Removes the specified component from the layout.

50
Create a panel and attach it to a frame. Here is the code :

import java.awt.*;
class AWTPanel extends Frame
{
Panel panel;
Button b1,b2;
public AWTPanel()
{

// Set frame properties


setTitle("AWT Panel"); // Set the title
setSize(400,400); // Set size to the frame
setLayout(new FlowLayout()); // Set the
layout
setVisible(true); // Make the frame visible
setLocationRelativeTo(null); // Center the
frame

// Create the panel


panel=new Panel();

// Set panel background


panel.setBackground(Color.gray);

// Create buttons
b1=new Button(); // Create a button with
default constructor
b1.setLabel("I am button 1"); // Set the
text for button

51
b2=new Button("Button 2"); // Create a
button with sample text
b2.setBackground(Color.lightGray); // Set
the background to the button

// Add the buttons to the panel


panel.add(b1);
panel.add(b2);

// Add the panel to the frame


add(panel);

}
public static void main(String args[])
{
new AWTPanel();
}
}

Create a Container example


With this tutorial we shall show you how to create a Container in a Java Desktop
Application. The Container component in a very important one because it gives you the
ability to organize and group together the components you want.
In short in order to create a Component in a Java Desktop Application, one should follow
these steps:
 Create a new Frame and a new Panel wich will play the role of theContainer.
 You can the use the Panel.add method to add the Components you want with the
oriantation and to the position you want.

package com.javacodegeeks.snippets.desktop;

52
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Component;
import java.awt.Frame;
import java.awt.Panel;
import java.awt.TextArea;

public class CreateContainerExample {

public static void main(String[] args) {

// Create a frame
Frame frame = new Frame("Example Frame");

/*

* Create a container with a flow layout, which


arranges its children

* horizontally and center aligned.

* A container can also be created with a


specific layout using

* Panel(LayoutManager) constructor, e.g.

* Panel(new FlowLayout(FlowLayout.RIGHT)) for


right alignment

*/
Panel panel = new Panel();

// Add several buttons to the container


panel.add(new Button("Button_A"));

53
panel.add(new Button("Button_B"));
panel.add(new Button("Button_C"));

// Add a text area in the center of the


frame
Component textArea = new
TextArea("This is a sample text...");
frame.add(textArea,
BorderLayout.CENTER);

// Add the container to the bottom


of the frame
frame.add(panel,
BorderLayout.SOUTH);

// Display the frame


int frameWidth = 300;
int frameHeight = 300;
frame.setSize(frameWidth,
frameHeight);

frame.setVisible(true);
}

54
Event delegation

It is important to consider how users interact with the user interface when designing a graphical user
interface (GUI). The GUI may require users to click, resize, or drag and drop components of the interface,
and input data using the keyboard. These actions will result to an event and you need to write a code to
handle them.
Event handling code deals with events generated by GUI user interaction. The best practices for coding
event handlers are outlined in the event delegation model.
The event delegation model comprises three elements:

 Event source
 Event listener
 Adapter

Event source
An event source is a component, such as a GUI component, that generates an event. The event
source can be generated by any type of user interaction. You can also combine a number of
different types of events into one event object.

For example, if a user clicks and drags an icon, you can sum up the mouse-clicked event and the
mouse-moved event into one event object.

In the event delegation model, a class represents each event type. Event objects are all defined
in thejava.util.EventObject subclasses.

55
A generated event object

 provides the methods to add or remove the source event


 manages the list of registered event listeners
 provides the appropriate class type to the registered event listeners

Event listener
Event listeners are objects that receive notification of an event. Components define the events
they fire by registering objects called listeners for those event types. When an event is fired, an
event object is passed as an argument to the relevant listener object method. The listener object
then handles the event.

To receive notification of an event, the object must be registered with the event source. To
subscribe to the event source, you implement the appropriate listener interface.

All listeners are implementations of the EventListener interface or one of its subinterfaces.
The Java API provides a predefined listener interface for each set of event types that a source
can fire. For example, the MouseListenerinterface deals with mouse events, and
the ActionListener interface deals with action events fired by buttons and other components.

Each listener interface provides at least one method for delivering the event object to the listener,
in addition to any methods required for the action. All methods take one parameter and are part of
the EventObject class.
Adapter
Adapters are abstract classes that implement listener interfaces using predefined methods.
These are provided for convenience.

You can use an adapter to apply one listener's methods without having to implement all other
methods. Adapters provide empty implementations for all interfaces' methods, so you only need
to override the method you are interested in.
SwingWorker class is designed to be used for situations where you need to have a long running task run
in a background thread and provide updates to the GUI either when done or while still in progress.
Subclasses of SwingWorker must implement the doInBackground method to perform the background
computation.
When using the SwingWorker class, you need to subclass SwingWorker and override
the doInBackground method anddone method. You can code a lengthy operation
inside doInBackground and add another task into the done method before updating the Swing
component from the event thread.
With the release of Java SE 6.0, additional features for sorting and filtering the JTable have been added.
By filtering the contents of a JTable, only the rows that match the user specified constraints are
displayed. Users can click on a specific column to be able to sort the contents accordingly.

56
Sorting is done by associating a JTable with a RowSorter class. RowSorter maintains two mappings.
One maps rows in aJTable to the elements of the underlying model and the other let you go back again.
Having two mappings allows you to do sorting and filtering. The class is generic enough to work with
both TableModel and ListModel. TableRowSorter class is used to work with a JTable.
In the simplest case, you pass the TableModel to the TableRowSorter constructor and then pass the
created RowSorterinto the setRowSorter method of JTable.

The code shows an example:


TableModel model = new DefaultTableModel(rows, columns) {
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {
returnValue = getValueAt(0, column).getClass();
} else {
returnValue = Object.class;
}
return returnValue;
}
};

JTable table = new JTable(model);


RowSorter<TableModel> sorter =new
TableRowSorter<TableModel>(model);
table.setRowSorter(sorter);
JScrollPane pane = new JScrollPane(table);
frame.add(pane, BorderLayout.CENTER);
frame.setBounds(400, 350, 300, 225);
frame.setResizable(false);
frame.setVisible(true);

}
}
To perform filtering on a JTable, a RowFilter needs to be associated with the TableRowSorter and
use it to filter the contents of a table using the include method.

The syntax for the include method is:


boolean include(RowFilter.Entry<? extends M,? extends I> entry)
For each entry in the model associated with the RowSorter, the method indicates whether the specified
entry should be shown in the current view of the model. In many cases, you don't need to create your
own RowFilter implementation.
In the given example, we use the regexFilter() method which uses a regular expression for filtering.
import javax.swing.*;
import javax.swing.table.*;

57
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;

public class SampleFilterJTable {


public static void main(String args[]) {
JFrame frame = new JFrame("Sorting JTable");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
Object rows[][] = {
{"CLSRE", "Callinsure", 388.44},
{"INTRSW", "Inter-Swift", 12.56},
{"BRCD", "Brocadero", 57.13},
{"MIMPS", "Med-Imps", 32.52},
{"CBCO", "Custom Boat Co.", 443.26},
{"SETLS", "Sharp-End Tools", 12.90},
{"PHLX", "Phlogistix", 31.25},
{"MTLD", "Mathemetric Ltd.", 45.89}
};
Object columns[] = {"Symbol", "Name", "Price"};
TableModel model =
new DefaultTableModel(rows, columns) {
public Class getColumnClass(int column) {
Class returnValue;
if ((column >= 0) && (column < getColumnCount())) {

Different types of event in Java AWT


There are many types of events that are generated by your AWT Application. These events are used to
make the application more effective and efficient. Generally, there are twelve types of event are used in
Java AWT. These are as follows :

1. ActionEvent
2. AdjustmentEvent
3. ComponentEvent
4. ContainerEvent
5. FocusEvent
6. InputEvent
7. ItemEvent

58
8. KeyEvent
9. MouseEvent
10. PaintEvent
11. TextEvent
12. WindowEvent
These are twelve mentioned events are explained as follows :

1. ActionEvent: This is the ActionEvent class extends from the AWTEvent class. It indicates the
component-defined events occurred i.e. the event generated by the component like Button,
Checkboxes etc. The generated event is passed to everyEventListener objects that receives such
types of events using the addActionListener() method of the object.

2. AdjustmentEvent: This is the AdjustmentEvent class extends from the AWTEvent class. When
the Adjustable Value is changed then the event is generated.

3. ComponentEvent: ComponentEvent class also extends from the AWTEvent class. This class
creates the low-level event which indicates if the object moved, changed and it's states (visibility
of the object). This class only performs the notification about the state of the object. The
ComponentEvent class performs like root class for other component-level events.

4. ContainerEvent: The ContainerEvent class extends from the ComponentEvent class. This is
a low-level event which is generated when container's contents changes because of addition or
removal of a components.

5. FocusEvent: The FocusEvent class also extends from the ComponentEvent class. This class
indicates about the focus where the focus has gained or lost by the object. The generated event
is passed to every objects that is registered to receive such type of events using
the addFocusListener() method of the object.

6. InputEvent: The InputEvent class also extends from the ComponentEvent class. This event
class handles all the component-level input events. This class acts as a root class for all
component-level input events.

7. ItemEvent: The ItemEvent class extends from the AWTEvent class. The ItemEvent class
handles all the indication about the selection of the object i.e. whether selected or not. The
generated event is passed to every ItemListener objects that is registered to receive such types

59
of event using the addItemListener() method of the object.

8. KeyEvent: KeyEvent class extends from the InputEvent class. The KeyEvent class handles all
the indication related to the key operation in the application if you press any key for any purposes
of the object then the generated event gives the information about the pressed key. This type of
events check whether the pressed key left key or right key, 'A' or 'a' etc.

9. MouseEvent: MouseEvent class also extends from the InputEvent class. The MouseEvent
class handle all events generated during the mouse operation for the object. That contains the
information whether mouse is clicked or not if clicked then checks the pressed key is left or right.

10. PaintEvent: PaintEvent class also extends from the ComponentEvent class. The PaintEvent
class only ensures that the paint() or update() are serialized along with the other events delivered
from the event queue.

11. TextEvent: TextEvent class extends from the AWTEvent class. TextEvent is generated when
the text of the object is changed. The generated events are passed to every TextListener object
which is registered to receive such type of events using the addTextListener() method of the
object.

12. WindowEvent : WindowEvent class extends from the ComponentEvent class. If the window or
the frame of your application is changed (Opened, closed, activated, deactivated or any other
events are generated), WindowEvent is generated.

60
The listener interface
An event listener interface defines the methods used by a
component to dispatch events. Each event type will have at least
one corresponding dispatch method in a listener interface.

A listener interface takes the following generic format:

public interface XXXListener

extends EventListener

// event dispatch methods

somethingHappened(XXXEvent e);

somethingElseHappened(XXXEvent e);

...

To listen for an event, a listener must implement


the XXXListener interface and register itself with the component.
When an event occurs, the component will call the proper
dispatch method. The methods are defined in an interface so that
any object can receive the event. As long as the listener
implements the interface, the component will know how to
dispatch the event to the listener.

Wrap-up
As you can see, there are dependencies between some of the
pieces. The listener interface corresponds directly to the event.
The event is necessarily the dispatch method's argument.

The component corresponds directly with the event and listener.


It needs to know about each so that it can create events,
dispatch events, and register listeners.

61
Unlike the other two pieces, the event object is independent. As a
result, many components are free to fire off the event type.
Furthermore, multiple interfaces may define methods to dispatch
the event.

62

S-ar putea să vă placă și