[go: up one dir, main page]

0% found this document useful (0 votes)
79 views12 pages

IC Module 3

This document discusses I/O streams in Java, including byte streams for machine data and character streams for human-readable text. It also covers applets, the applet architecture which is event-driven, basic applet components like init() and paint(), and event handling in Java using listener interfaces. Sample code demonstrates a simple applet and handling button clicks by implementing the ActionListener interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
79 views12 pages

IC Module 3

This document discusses I/O streams in Java, including byte streams for machine data and character streams for human-readable text. It also covers applets, the applet architecture which is event-driven, basic applet components like init() and paint(), and event handling in Java using listener interfaces. Sample code demonstrates a simple applet and handling button clicks by implementing the ActionListener interface.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

1

MODULE III
I/O I/O Basics Byte Streams and Character Streams, Reading Console Input, Collections
Framework, Applets & Applet Architecture-Applet Skelton- Passing Parameters to Applet, Event
Handling-Event Model- Event Classes Event Listener Interfaces, AWT AWT Classes AWT
Controls Layout Managers and Menus.Swing- JApplet Jbuttons - JTables.
Character and Byte Streams:
When dealing with input/output, you have to keep in mind that there are two broad categories of
data: machine-formatted data and human-readable text. Machine-formatted data is represented in
binary form, the same way that data is represented inside the computer, that is, as strings of zeros
and ones. Human-readable data is in the form of characters. When you read a number such
as 3.141592654, you are reading a sequence of characters and interpreting them as a number. The
same number would be represented in the computer as a bit-string that you would find
unrecognizable.
To deal with the two broad categories of data representation, Java has two broad categories of
streams: byte streams for machine-formatted data and character streams for human-readable data.
There are many predefined classes that represent streams of each type.
An object that outputs data to a byte stream belongs to one of the subclasses of the abstract
class OutputStream. Objects that read data from a byte stream belong to subclasses of InputStream.
If you write numbers to an OutputStream, you won't be able to read the resulting data yourself. But
the data can be read back into the computer with an InputStream. The writing and reading of the
data will be very efficient, since there is no translation involved: the bits that are used to represent
the data inside the computer are simply copied to and from the streams.
For reading and writing human-readable character data, the main classes are the abstract
classes Reader and Writer. All character stream classes are subclasses of one of these. If a number is
to be written to aWriter stream, the computer must translate it into a human-readable sequence of
characters that represents that number. Reading a number from a Reader stream into a numeric
variable also involves a translation, from a character sequence into the appropriate bit string. (Even
if the data you are working with consists of characters in the first place, such as words from a text
editor, there might still be some translation. Characters are stored in the computer as 16-bit Unicode
values. For people who use Western alphabets, character data is generally stored in files in ASCII
code, which uses only 8 bits per character. The Reader and Writer classes take care of this
translation, and can also handle non-western alphabets in countries that use them.)
Byte streams can be useful for direct machine-to-machine communication, and they can sometimes
be useful for storing data in files, especially when large amounts of data need to be stored
efficiently, such as in large databases. However, binary data is fragile in the sense that its meaning is
not self-evident. When faced with a long series of zeros and ones, you have to know what
information it is meant to represent and how that information is encoded before you will be able to
interpret it. Of course, the same is true to some extent for character data, which is itself coded into
binary form. But the binary encoding of character data has been standardized and is well
understood, and data expressed in character form can be made meaningful to human readers. The
InternetComputing Module 3

2
current trend seems to be towards increased use of character data, represented in a way that will
make its meaning as self-evident as possible.
Original version of Java did not have character streams, and that for ASCII-encoded character data,
byte streams are largely interchangeable with character streams. In fact, the standard input and
output streams, System.in and System.out, are byte streams rather than character streams. However,
you should use Readers and Writers rather than InputStreams and OutputStreams when working
with character data, even when working with the standard ASCII character set.
The standard stream classes discussed in this section are defined in the package java.io, along with
several supporting classes. You must import the classes from this package if you want to use them
in your program. That means either importing individual classes or putting the directive "import
java.io.*;" at the beginning of your source file. Streams are necessary for working with files and for
doing communication over a network. They can also be used for communication between two
concurrently running threads, and there are stream classes for reading and writing data stored in the
computer's memory.
The beauty of the stream abstraction is that it is as easy to write data to a file or to send data over a
network as it is to print information on the screen.
Applet Fundamentals
import java.awt.*;
import java.applet.*;
public class SimpleApplet extends Applet {
public void paint (Graphics g) {
g.drawString("First Applet", 50, 50 );
}
}
AWT is Abstract Window Toolkit.
AWT contains support for a window-based, graphical interface.
Paint method defined by AWT. Called whenever the applet must redraw its output.
<applet code="SimpleApplet" width=200 height=200>
</applet>
else
InternetComputing Module 3

3
C:\>appletviewer MyHTML.html
Applet Architecture
Event driven
An applet waits until an event occurs.
The AWT notifies the applet about an event by calling event handler that has been provided by the
applet.The applet takes appropriate action and then quickly return control to AWT.
Applet Skeleton
import java.awt.*;
import java.applet.*;
/*
<applet code="AppletSkel" width=300 height=200>
</applet>
*/
public class AppletSkel extends Applet {
//Called First
public void init() {
// initialization
}
/* Called second, after init(). Also called whenever the applet is restarted.*/
public void start() {
// start or resume execution
}
// Called when the applet is stopped.
public void stop() {
// Suspends execution
InternetComputing Module 3

4
}
/*Called when applet is terminated. This is last method executed.*/
public void destroy() {
//perform shutdown activities
}
//Called when an applets window must be restored.
public void paint(Graphics g) {
//redisplay contents of window
}
}
Order
When applet begins:
init()
start()
paint()
When an applet is terminated
stop()
destroy()
Simple Applet Display Methods
void drawstring(String message, int x, int y)
void setBackground(Color newColor)
void setForeground(Color newColor)

Sample Program
InternetComputing Module 3

5
import java.awt.*;
import java.applet.*;
/*
<applet code="Sample" width=300 height=200>
</applet>
*/
public class Sample extends Applet {
String msg;
public void init() {
setBackground(Color.cyan);
setForeground(Color.red);
msg = "Inside init() ";
}
public void start() {
msg += "Inside start() ";
}
public void paint(Graphics g) {
msg += "Inside paint().";
g.drawString(msg, 20, 30);
}
}

EVENT HANDLING
GUI applications are event-driven. They generate some events when the user of the program
interacts with the GUI. Clicking a button, closing a window, or hitting a key results in a appropriate
InternetComputing Module 3

6
event being sent to the application.
In Java, events are represented by objects. When an event occurs, the system collects all the
information relevant to the event and constructs an object to contain that information. Different
types of events are represented by objects belonging to different classes. For example, when the
user presses a button on the mouse, an object belonging to a class called MouseEvent is constructed.
The object contains information such as the GUI component on which the user clicked, the (x,y)
coordinates of the point in the component where the click occurred, and which button on the mouse
was pressed. When the user presses a key on the keyboard, a KeyEvent is created. After the event
object is constructed, it is passed as a parameter to a designated subroutine. By writing that
subroutine, the programmer says what should happen when the event occurs.
For an event to have any effect, a program must detect the event and react to it. In order to detect an
event, the program must "listen" for it. Listening for events is something that is done by an object
called an event listener. An event listener object must contain instance methods for handling the
events for which it listens. For example, if an object is to serve as a listener for events of type
MouseEvent, then it must contain the following method (among several others):
public void mousePressed(MouseEventevt) { . . . }
The body of the method defines how the object responds when it is notified that a mouse button has
been pressed. The parameter, evt, contains information about the event. This information can be
used by the listener object to determine its response. The methods that are required in a mouse event
listener are specified in an interface named MouseListener. To be used as a listener for mouse
events, an object must implement this MouseListener interface
ie .,The event handling in Java based on event delegation model. Its principal elements are
o Event Objects
Encapsulates information about different types of user interaction
o Event source objects
Particular GUI Component with which the user interacts. They inform event listeners about
events when these events occur and supply the necessary information about these events
o Event Listener
Is an object that is notified by the event source when an event occurred. It then responds to
the event.

Example 1
Handling Buttons
importjava.awt.*;
importjava.applet.*;
importjava.awt.event.*;
public class ButtonApplet extends java.applet.Applet implements ActionListener {
Button button;
String msg;
InternetComputing Module 3

7
public void init() {
button= new Button("click here");
add(button);
button.addActionListener(this);
}
public void actionPerformed(ActionEvent e) {
String str= e.getActionCommand();
if(str.equals("click here"))
msg="Welcome to Event Handling";
}
public void paint(Graphics g) {
g.drawString(msg, 10,100);
}
}
AWT and SWINGS
Java Foundation Classes (JFC) provide two frame works for building GUI based applications, The
Abstract window Toolkit (AWT) and Swing.
When a Java programs with an AWT GUI executes on different Java platforms, the programs GUI
components display differently in each platform. The Swing components allow programmers to
specify the same look and feel across all platforms. Swing components are not weighted down
complex capabilities of the platform in which they are used. AWT components are tied to the local
platform are known as heavy weight components. They rely on the local platforms windowing
system to determine their functionality and their look and feel.
The AWT Object Categories
The object classes used for constructing interactive windowing user interfaces contain three basic
types of entities:
Containers-Containers are visual objects into which components can be placed so that
several can be grouped together in a consistent fashion. For example, a frame is a container,
as is a radio button group, and a panel. All these containers are discussed shortly.
Components-Components are the visual entities with which the user specifically interacts.
Components must be placed in some kind of container in order to be visible. You access
them later as members of this container. Examples of components are buttons, text fields,
and scrollbars.
Layout managers-Layout manager are used to arrange the components in a container in a
InternetComputing Module 3

8
desired fashion. Layout managers enable you to align buttons along the left edge of a
window in one program and arrange them in a grid in the next.

COMPONENT CLASSES
Common controls that are part of the component class include
Button, Canvas, Check box, Choice, Label, List, Scrollbar, Text area, Text field
These are the primary controls used over and over in programs to enable user interaction.
As a derivative of the Component class, these controls can be added to containers and arranged by
layouts. In addtion new controls can be from the classes that are available.
Buttons
Buttons are components that a user can press to activate a certain reaction on the part of the
program. Buttons can be labeled or unlabeled; although, clearly, an unlabeled button is not terribly
useful.
create
Button,
addActionListener
to
Button,
add
Button
to
Container:
Button b = new Button(label); cb.addActionListener(listener); container.add(b);

Example
importjava.awt.*;
importjava.awt.event.*;
importjava.applet.*;
/*
<applet code="ButtonDemo" width=250 height=150>
</applet>
*/
public class ButtonDemo extends Applet implements ActionListener {
String msg = "";
Button yes, no;
public void init() {
yes = new Button("Yes");
no = new Button("No");
add(yes);
add(no);
InternetComputing Module 3

9
yes.addActionListener(this);
no.addActionListener(this);
}
public void actionPerformed(ActionEventae) {
String str = ae.getActionCommand();
if(str.equals("Yes")) {
msg = "You pressed Yes.";
}
}
}

AWT stands for Abstract Window ToolKit. It is a portable GUI library between Solaris and
Windows 95/NT and Mac System 7.X(soon) for stand-alone applications and/or applets. Since it
can be used in applets it can be used on IRIX, SunOS, HP/UX, Linux which Netscape 2.0 supports.
The Abstract Window Toolkit provides many classes for programmers to use. It is your connection
between your application and the native GUI. The AWT hides you from the underlying details of
the GUI your application will be running on and thus is at very high level of abstraction. It takes the
lowest common denominator approach to retain portability. No floating toolbars or Balloon help
here...
It is a Java package and can be used in any Java program by importing java.awt.* via
the import keyword. The documentation for the package is available at the Java hompage. The
package will be covered briefly as this document is not considered advanced material because it
does not discuss Peers, ImageConsumers/Producers, Toolkits and other advanced AWT ilk. It is
recommend you look at the source code to see how the AWT really works.
AWT concepts
But first lets cover some basics that you'll need to know before diving into the AWT package. I
briefly mention some fundamental Java concepts and if they ring a bell then you should continue,
otherwise, you should get a better grasp of Java first.
Classes: public, protected and private
Almost every thing is a class in Java, except for primitives such as ints, chars, doubles, etc. And all
classes(reference types according to the lang spec) are derived from Object.
The cornerstone of most OO programing languages are classes. So expect to understand them
before using the AWT.
InternetComputing Module 3

10
Java has four types of access levels and one unamed default one:

public: Accessible everywhere.

private: Accessible only within the class

protected: Accessible to those within the same file(package) and/or derived classes.

private protected: Acessible to those within the class and derived classes. This is analogous
to C++'s protected member access. Introduced in JDK beta 2.

The default access level is very similar to protected.


SWINGS
Swings provides features not present in the AWT:
More Dynamic Components
New functionality can easily be added to Swing Components
More Complex Components
Jtree, JfileChooser, Jtable that have no AWT counterparts
New Containment model for root containers
Root containment like Jframe, Jdialog and Japplet use a containment model to
maintain their component hierarchy.
A new layout Manager
BoxLayOutManager
Pluggable look and feel.
From an architectural standpoint, Swing is not a replacement for the AWT,but extension that
contains alternative lightweight components for many of the native heavyweight components in the
AWT. Swing uses many of the same concepts as the AWT. It uses the same event model and the
same layout mangers.
All lightweight Swing components inherit from the Jcomponent class. The abstract
Jcomponent class defines common functionality that is shared by all lightweight Swing
components.
In the AWT, labels and buttons can only contain a short text string. In Swing, buttons and
labels can contain a short text string or an image or both.

JApplet
An applet is an object that is used by another program, typically a Web browser. The Web browser
is the application program and (at least conceptually) holds the main() method. The applet part of a
Web page provides services (methods) to the browser when the browser asks for them.
An applet object has many instance variables and methods. Most of these are defined in
the JApplet class.
InternetComputing Module 3

11

import javax.swing.JApplet;
import java.awt.*;

// assume that the drawing area is 150 by 150


public class JustOneCircle extends JApplet
{
final int radius = 25;

public void paint ( Graphics gr )


{
gr.setColor( Color.white );
gr.fillRect( 0, 0, 150, 150 );
gr.setColor( Color.black );

gr.drawOval( (150/2 - radius), (150/2 - radius), radius*2, radius*2 );


}
}

JButton
Simple uses of JButton are very similar to Button. You create a JButton with a String as a label, and
then drop it in a window. Events are normally handled just as with a Button: you attach
an ActionListener via the addActionListener method.
Creating a JButton
public JButton()
JButton button = new JButton();
public JButton(Icon image)
Icon icon = new ImageIcon("dog.jpg");
JButton button = new JButton(icon);
public JButton(String text)
JButton button = new JButton("Dog");
InternetComputing Module 3

12

public JButton(String text, Icon icon)


Icon icon = new ImageIcon("dog.jpg");
JButton button = new JButton("Dog", icon);
public JButton(Action action)
Action action = ...;
JButton button = new JButton(action);

InternetComputing Module 3

You might also like