Documente Academic
Documente Profesional
Documente Cultură
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
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.*;
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:
$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.*;
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:
$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.
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:
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;
InputStream is = null;
InputStreamReader isr = null;
BufferedReader br = null;
try{
// open input stream test.txt for reading purpose.
is = new FileInputStream("c:/test.txt");
5
// create new buffered reader
br = new BufferedReader(isr);
int value=0;
// prints character
System.out.println(c);
}
}catch(Exception e){
e.printStackTrace();
}finally{
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;
StringWriter sw = null;
BufferedWriter bw = null;
7
try{
// create string writer
sw = new StringWriter();
}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.
while(data != -1){
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.
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:
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.
writer.close();
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:
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:
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.
10
PrintWriter writer = new PrintWriter(writer);
writer.print(true);
writer.print((int) 123);
writer.print((float) 123.456);
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.
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
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
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.
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.
Class declaration
Following is the declaration for java.awt.Graphics class:
extends Object
Class constructors
S.N. Constructor & Description
1
Graphics() ()
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)
3
abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
4
abstract Graphics create()
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)
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)
12
abstract boolean drawImage(Image img, int x, int y, ImageObserver observer)
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)
19
abstract void drawPolygon(int[] xPoints, int[] yPoints, int nPoints)
20
void drawPolygon(Polygon p)
21
abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)
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)
27
abstract void fillArc(int x, int y, int width, int height, int startAngle, int arcAngle)
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)
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)
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()
34
abstract Shape getClip()
35
abstract Rectangle getClipBounds()
36
Rectangle getClipBounds(Rectangle r)
37
Rectangle getClipRect()
38
abstract Color getColor()
21
Gets this graphics context's current color.
39
abstract Font getFont()
40
FontMetrics getFontMetrics()
41
abstract FontMetrics getFontMetrics(Font f)
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)
45
abstract void setColor(Color c)
46
abstract void setFont(Font 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()
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.*;
23
public AWTGraphicsDemo(){
prepareGUI();
awtGraphicsDemo.setVisible(true);
setSize(400,400);
addWindowListener(new WindowAdapter() {
System.exit(0);
});
@Override
g.setColor(Color.GRAY);
g.setFont(font);
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
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.
A default layout is present in each container which can be overridden using setLayout method.
25
1
Container
AWT UI Elements:
Following is the list of commonly used containers while designed GUI using AWT.
1
Panel
Panel is the simplest container. It provides space in which any other component can be placed,
including other panels.
2
Frame
3
Window
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:
extends Component
26
Class constructors
S.N. Constructor & Description
1
Container()
Class methods
S.N. Method & Description
1
Component add(Component comp)
2
Component add(Component comp, int index)
3
void add(Component comp, Object constraints)
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)
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)
27
8
void addNotify()
9
void addPropertyChangeListener(PropertyChangeListener listener)
10
void add Property Change Listener(String proper tyName, Property Change Listener
listener)
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()
14
void deliverEvent(Event e)
15
void doLayout()
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()
19
float getAlignmentY()
20
Component getComponent(int n)
21
Component getComponentAt(int x, int y)
22
Component getComponentAt(Point p)
23
int getComponentCount()
24
Component[] getComponents()
25
int getComponentZOrder(Component comp)
26
ContainerListener[] getContainerListeners()
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()
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()
33
Dimension getMinimumSize()
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()
36
Insets insets()
30
37
void invalidate()
38
boolean isAncestorOf(Component c)
39
boolean isFocusCycleRoot()
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()
42
boolean isFocusTraversalPolicySet()
Returns whether the focus traversal policy has been explicitly set for this Container.
43
void layout()
44
void list(PrintStream out, int indent)
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)
31
47
Dimension minimumSize()
48
void paint(Graphics g)
49
void paintComponents(Graphics g)
50
protected String paramString()
51
Dimension preferredSize()
52
void print(Graphics g)
53
void printComponents(Graphics g)
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)
56
void remove(Component comp)
32
57
void remove(int index)
58
void removeAll()
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)
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)
33
67
void setLayout(LayoutManager mgr)
68
void transferFocusBackward()
Transfers the focus to the previous component, as though this Component were the focus
owner.
69
void transferFocusDownCycle()
70
void update(Graphics g)
71
void validate()
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:
Class constructors
S.N. Constructor & Description
1
Panel()
2
Panel(LayoutManager layout)
Class methods
S.N. Method & Description
1
void addNotify()
35
Creates the Panel's peer.
2
AccessibleContext getAccessibleContext()
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.*;
36
public AwtContainerDemo(){
prepareGUI();
}
37
headerLabel = new Label();
headerLabel.setAlignment(Label.CENTER);
statusLabel = new Label();
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
}
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
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:
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.
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()
2
AccessibleContext getAccessibleContext()
3
int getCursorType()
4
int getExtendedState()
5
static Frame[] getFrames()
6
Image getIconImage()
7
Rectangle getMaximizedBounds()
42
8
MenuBar getMenuBar()
9
int getState()
10
String getTitle()
11
boolean isResizable()
12
boolean isUndecorated()
13
protected String paramString()
14
void remove(MenuComponent m)
15
void removeNotify()
Makes this Frame undisplayable by removing its connection to its native screen resource.
16
void setCursor(int cursorType)
17
void setExtendedState(int state)
43
18
void setIconImage(Image image)
19
void setMaximizedBounds(Rectangle bounds)
20
void setMenuBar(MenuBar mb)
Sets the menu bar for this frame to the specified menu bar.
21
void setResizable(boolean resizable)
22
void setState(int state)
23
void setTitle(String title)
24
void setUndecorated(boolean undecorated)
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 AwtContainerDemo(){
prepareGUI();
awtContainerDemo.showFrameDemo();
mainFrame.setSize(400,400);
mainFrame.addWindowListener(new WindowAdapter() {
System.exit(0);
});
headerLabel.setAlignment(Label.CENTER);
statusLabel.setAlignment(Label.CENTER);
statusLabel.setSize(350,100);
msglabel.setAlignment(Label.CENTER);
controlPanel.setLayout(new FlowLayout());
45
mainFrame.add(headerLabel);
mainFrame.add(controlPanel);
mainFrame.add(statusLabel);
mainFrame.setVisible(true);
frame.setSize(300, 300);
frame.setLayout(new FlowLayout());
frame.add(msglabel);
frame.addWindowListener(new WindowAdapter() {
frame.dispose();
});
okButton.addActionListener(new ActionListener() {
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
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.
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.
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.
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.
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:
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()
{
// 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
}
public static void main(String args[])
{
new AWTPanel();
}
}
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;
// Create a frame
Frame frame = new Frame("Example Frame");
/*
*/
Panel panel = new Panel();
53
panel.add(new Button("Button_B"));
panel.add(new Button("Button_C"));
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
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.
}
}
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.
57
import java.awt.*;
import java.awt.event.*;
import java.util.regex.*;
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.
extends EventListener
somethingHappened(XXXEvent e);
somethingElseHappened(XXXEvent e);
...
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.
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