Java Fundamentals: A Beginner’s Handbook

Java desde Cero

With this beginning a series of notes on Java, especially for those who want to start
know and use. This originated in an interest that arose in some of the subscribers to the mailing list of
Web developers, and also make available to the webmaster.
Many of you will know much more about Java than I, and I appreciate all types of
comments or corrections.
The idea is to give guidance for the orderly study of this language, very powerful and very consistent, although
still has some limitations that number will surely grow out of it.

What is Java

Java was originally developed by a group of Sun engineers, used by Netscape
later as a basis for Javascript. Although its use is highlighted on the Web, is used to create all sorts of
applications (local, intranet or internet).
Java is a language:
· Object
· Platform independent
Some notable features:
· Robust
· Automatically manages memory
Do not allow the use of inappropriate programming techniques
· Multithreading
· Client-server
· Security mechanisms embedded
· Built documentation tools

Object Language

Why put “from” objects and not “aimed at” objects? To emphasize that, unlike other languages like
C + + language is not modified to work with objects but is a language created to
working with objects from scratch. In fact, EVERYTHING that is in Java are objects.

What is an object?


Well, one can say that everything can be seen as an object. But let’s be clearer. An object, since
In our view, can be viewed as a piece of software that meets certain characteristics:
· Encapsulation
· Inheritance
Encapsulation means that the object is self-contained, meaning that the same definition of the object includes
so that it uses data (attributes) and procedures (methods) that act on them.
When using object-oriented programming, classes are defined (which define generic objects) and
how the objects interact with each other through messages. By creating an object of a given class are
says it creates an instance of the class, or object itself. For example, a class might be
“cars” and a car is given an instanceclass.
The advantage is that since there are no programs that act by modifying the object, it remains in
somewhat independent of the rest of the application. If necessary modify the object (for example, to
greater capacity), this can be done without touching the rest of the application … Which saves time

development and debugging! In Java, inclusive, do not exist at the global variables! (Although it seems
difficult to accept, this is a great advantage from the standpoint of development).
With regard to inheritance, simply means that you can create new classes that inherit from other
preexisting This simplifies programming, because the subclasses automatically incorporate
methods of mothers. For example, our class “car” could inherit from a more general one “vehicle” and
simply redefine the methods in the particular case of cars … Which means that with a
good class library, you can reuse a lot of code even without knowing what is inside.

A simple example

To go have an idea, let’s take an example of a Java class:
public class Sample extends Frame (
/ / Class attributes
Button if;
Button will not;
/ / Class methods:
public Sample () (
Label comment = new Label ( “Press a button,” Label.CENTER);
si = new Button ( “Yes”);
no = new Button ( “No”);
add ( “North”, comment);
add ( “East”, si);
add ( “West”, no);
))
This class is not very comprehensive way, but gives an idea … It’s an heir to the class class Frame(a type of
window)
That has a couple of buttons and a text. It contains two attributes ( “if” and “no”), which are two objects
Button type, and a single method called Display (like the class, so that is what is called a
constructor).

Platform independent

This is almost entirely true …
Actually, Java can be run up on a Commodore 64! The reality is that for use in
their full potential, requires an operating system multithreading (such as Unix, Windows95, OS / 2 …).
How’s this? Because in reality Java is an interpreted language … At least in principle.
When compiling a Java program, which is generated is a pseudo code defined by Sun, for a machine
generic. Then, when running on a given machine, the Java runtime software simply interprets the
directions, emulating the generic machine. Of course this is not very efficient, so that both
HotJava or Netscape and Explorer, when running the code for the first time, it will compile (using a
JIT: J ust I n T ime compiler), so for example when creating the second instance of an object code and
is compiled specifically for the host machine.
In addition, Sun and Intel have agreed to develop processors that work directly in
Java, so they plan to do very cheap machines that can connect to the network and run applications
Java client-server at very low cost.
The generic language that machine is public, and if you wanted to make a Java interpreter for a
Commodore had only to ask Sun to implement and approval (to verify that it meets
Java requirements as to how it interprets each instruction, safety, etc.).

Some features ..


Among the features we name we refer to robustness. Just by the way it is
designed, Java does not allow direct control of the hardware or memory (including any modification

values of pointers, for example), so you can say it is virtually impossible to hang a
Java program. The interpreter is always in control.
Even the compiler is smart enough to not allow a lot of things that could
bring problems, how to use variables without initializing, modifying pointer values directly, access
methods or variables incorrectly, use multiple inheritance, etc..
In addition, Java implements security mechanisms to limit access to resources of the machines where
runs, especially in the case of applets (which are applications that are loaded from a server and
running on the client).
It is also designed specifically to work on a network, so it incorporates objects
allow access to files remotely (via URL for example).
And with the JDK (Java Development Kit) come with many tools, including a
automatic documentation generator, with a little care to make comments in class,
including all documentation created for them in HTML format!

The Java Development Kit

All you can ask to develop Java applications are in:
· Http://java.Sun.Com/aboutJava/index.Html
In particular, they should download the JDK and the API Documentation for:
· Http://java.Sun.Com/java.Sun.Com/products/JDK/1.0.2/index.Html
(Also may be interested in particular Documentation Tool and some of the other packages of the page)
Note: This site is also a tutorial on Java, though a little hard to follow for the beginner.

The JDK (version 1.0.2) is available for SPARC / Solaris, x86/Solaris, MS-Windows 95/NT, and MacOS.
Also available is the source for those who want to adapt it for another operating system, and I read somewhere
that there is a spinning version for Linux and HP-UX.
Basically, the JDK consists of:
· The Java compiler, javac
· The Java interpreter, java
· A viewer applets, appletviewer
· The Java debugger, jdb (for work that needs to connect to the server from Sun)
· The documentation generator, javadoc
You can also download the same site a browser that supports Java (and indeed it is written entirelyin
Java), the HotJava.
To install simply have to unzip the file (I suggest to create a java directory for that),
but bear in mind does not decompress the classes.Zip!
Important for users of Windows95: all these applications must run from a window
DOS. In particular, they use long names and are case-sensitive, so sensitive
this is a source of many errors.
One very important thing: that all walks well oiled, add:
· The program directory in the path (eg c: javain)
· Environment variables:
· CLASSPATH =.; C: javalibclasses.Zip
· HOMEDRIVE = C:
· HOMEPATH =
· HOME = C:
with appropriate values for your environment.
Note that in CLASSPATH added the current directory (.) In order to compile and run from any
directory.

Let’s start at once!


Well, assuming you have installed everything, and before you start programming in Java, a small
clarification:

In fact one can say that there are three Javas:
· Javascript: is a version of Java directly interpreted, which is included as part of a
HTML page, making it very easy and convenient for very small, but in
reality has many limitations:
Support-no classes or inheritance
-No is precompiled
-No variables must be declared
· Check the references at runtime
-No code protection has since lowered in ascii
· Not all browsers support it completely, Explorer, for example, does not support the
Netscape’s latest additions, such as animated images.
· Standalone Java: Java programs that run directly through the java interpreter.
· Applets: Java programs that run under the environment of a browser (or appletviewer)
In it the last two are the same language, but changes slightly the way in which the object is implemented
main (application). Let’s see how to create applications without change can be implemented
almost the same as standalone or as an applet (there are actually things that applets can not do, as
access files without authorization.)
Javascript
We will not dwell much on Javascript for the above limitations, if we are interested
dedicate some of this language in the future. For now, just a simple example:
Calculator in Javascript:
<HTML>
<HEAD>
<SCRIPT LANGUAJE=”Javascript”>
function calc (form) (
if (confirm ( “Are you sure?”))
form.Resultado.Value = eval (form.Expr.Value)
else
alert ( “Please try again …”)
)
</ SCRIPT>
</ HEAD>
<BODY>
<FORM>
Enter an expression:
<INPUT TYPE=”text” NAME=”expr” 5>
<INPUT TYPE=”button” NAME=”Boton” value=”Calculate” ONCLICK=”calcula(this.Form)”>
<BR>
Results:
<INPUT TYPE=”text” NAME=”resultado” 5>
<BR>
</ FORM>

</ BODY>
</ HTML>
Basically, the code falls between the tags <SCRIPT> … </ SCRIPT>, and the parameters are passed to
it using form (<FORM> … </ FORM>). The language used is very similar to C + +, and
basically the code is executed by the action of a button (… OnClick = “estimates (this.Form)”).
Pressing the button will call the function with parameter estimates this.Form, which refers to the form that
belongs to the button.

The role assigned to the field value result of the form that is passed as parameter
(Form.Resultado.Value) the result of eval uar the value of expression expr of the form field
(Eval (form.Expr.Value)).
There are many examples of Javascript in:
· Http://www.C2.Net/ ~ andreww / javascript /
including dozens of calculators, games and other herbs!
There will also find documentation and a tutorial on Javascript.

Classes in Java

Well, first of all to know that in Java there are a lot of classes already defined and usable.
They come in standard libraries:
· Java.Lang – core classes, numbers, strings, objects, compiler, runtime, security, and threads (is
the only package that is automatically included in any Java program)
· Java.Io – classes that handle input and output
· Java.Util – useful classes, such as generic structures, handling date, time and strings, number
random, etc..
· Java.Net – classes to support networks: URLs, TCP, UDP, IP, etc..
· Java.Awt – classes for GUI management, windows.
· Java.Awt.Image – classes for image handling
· Java.Awt.Peer – classes that connect to the graphical interface implementations dependent
platform (motif, windows)
· Java.Applet – classes for creating applets and resources for audio playback.
In order to give an idea, integers, for example, are “instances” of a class does not redefine,
Integer, which descends from the Number class and implements the following attributes and methods:
public final class Integer extends java.Lang.Number (
/ / Attributes
public final static int MAX_VALUE;
public final static int MIN_VALUE;
/ / Constructor methods
public Integer (int value);
public Integer (String s);
/ / More Methods
public double doubleValue ();
public boolean equals (Object obj);
public float floatValue ();
public static Integer getInteger (String nm);
public static Integer getInteger (String nm, int val);
public static Integer getInteger (String nm, Integer val);
public int hashCode ();
public int intValue ();
public long longValue ();
public static int parseInt (String s);
public static int parseInt (String s, int radix);
public static String toBinaryString (int i);
public static String toHexString (int i);
public static String toOctalString (int i);
public String toString ();
public static String toString (int i);
public static String toString (int i, int radix);
public static Integer valueOf (String s);
public static Integer valueOf (String s, int radix);
)
Much, no?
This also gives us some ideas:
• The structure of a class
· Gosh, there are methods repeated!
Discuss the structure immediately, in repeating the methods (such as parseInt for example), the
called the method the compiler decides which of the implementations of the same use based on the
amount and type of parameters that we pass. For example, parseInt ( “134”) and parseInt ( “134”, 16),
compile, generate calls to two different methods.

Structure of a class

A class consists of:
algunas_palabras class nombre_de_la_clase [Something_Else] (
[lista_de_atributos]
[lista_de_métodos]

)

What is between [and] is optional …
We’ll see what to put in “algunas_palabras” and “Something_Else” for now we continue a little longer.
The list of attributes (our old local variables) follows the same format C: we first define the type
and then the name of the attribute, and finally the “;”.
public final static int MAX_VALUE
;
We also have “algunas_palabras” forward, but then analyze them.
As for technique, also follow the syntax of C, an example:
public int incContador ()
(/ / declaration and opening (
cnt + +; / / instructions, separated by “;”
return (cnt);
) / / End for)
Finally, we will accept comments between / * and * / as in C or using / / the beginning of the commentary (the
comment ends at the end of the line).
An example:
/ / Implementation of a simple counter
/ / Write to a file “Contador.Java” (WATCH OUT FOR THE ALL CAPS!)
/ / Compile with: “javac Contador.Java” (DO NOT FORGET THE. Java!)
/ / This class is not an application but is going to serve immediately
public class Counter (/ / Define the class Counter
/ / Attributes
int cnt; / / An integer to store the current value
/ / Constructor / / One constructor …
public Counter () (/ / … Has the same name as the class
cnt = 0; / / just initialize (1)
)
/ / Methods
public int incCuenta () (/ / A method to increase the counter
cnt + +; / / increment cnt
return cnt; / / and step returns the new value
)
public int getCuenta () (/ / This only returns the current value
return cnt; / / counter
)
)
Where, from an application or other object, you create an instance of the class Counter, by
instruction:
new Counter ()
the compiler looks for a method with the same name as the class that matches the call
the type and number of parameters. This method is called Constructor, and a class can have more than
a constructor (but not an object or instance, and that once created it can not be recreated on
same).
At run time, finding such instruction, the interpreter allocates space for the object / instance,
creates its structure and calls the constructor.
So the effect of new Counter () is precisely to reserve space for the counter and initialize it in
zero.
As for other methods can be called from other objects (including applications) of
Similarly a function is called from C.
For example, we use our counter in a very simple program to show us how it evolves:
/ / Let’s use our counter in a mini-application
/ / Write to a file “Ejemplo1.Java” (WATCH OUT FOR THE ALL CAPS!)
/ / Compile with: “javac Ejemplo.Java” (DO NOT FORGET THE. Java!)
/ / RUN WITH: “java Example1” (without the. Java)
import java.Io. *; / / Using the library input / output
public class Example1 (/ / IMPORTANT: Class Name
/ / Same as the name of the file!
/ / Integer to assign the value of the counter and print
/ / But not really necessary.
static int n;
/ / Counter and a variable type to instantiate the object …
static Counter laCuenta;
/ / This method, MAIN, IS THAT MAKES this behaves
/ / HOW TO APPLICATION. It’s where the program starts up when I run “java Example1”
/ / NOTE: main must be public & static.
public static void main (String args []) (
System.Out.Println ( “Account …”); / / Print the title
laCuenta = new Counter () / / an instance of the Accountant I
System.Out.Println (laCuenta.GetCuenta ()); / / 0 – print the current value (zero!)
n = laCuenta.IncCuenta (); / / 1 – Allocation and increased
System.Out.Println (n); / / Now print n
laCuenta.IncCuenta (); / / 2 – The rise (not use the value …
System.Out.Println (laCuenta.GetCuenta ()); / / … Return) and I print
System.Out.Println (laCuenta.IncCuenta ()) / / 3 – Now all in one step!
)
)
In Chapter III we will analyze this program in detail. For now we see the difference with an applet that
do the same:
/ / Applet implementation similar action Example1
/ / RECORD ON FILE “Ejemplo2.Java”
/ / Compile with: “javac Ejemplo2.Java”
/ / TO EXECUTE: Create an HTML page as shown later
import java.Applet .*;
import java.Net .*;
public class Example2 extends Applet (
static int n;
static Counter laCuenta;
/ / Constructor …
public Example2 () (
laCuenta = new Counter ();
)
/ / The paint method is executed every time there is to redraw
/ / NOTE THAT THE EFFECT OF CHANGING SIZE WHEN THE
/ / BROWSER WINDOW!
public void paint (Graphics g) (
g.DrawString ( “Account …”, 20, 20);
g.DrawString (String.ValueOf (laCuenta.GetCuenta ()), 20, 35);
n = laCuenta.IncCuenta ();
g.DrawString (String.ValueOf (n), 20, 50);
laCuenta.IncCuenta ();
g.DrawString (String.ValueOf (laCuenta.GetCuenta ()), 20, 65);
g.DrawString (String.ValueOf (laCuenta.IncCuenta ()), 20, 80);
)
)
It is now necessary to create an HTML page can be viewed. For this, create and then upload the file
ejemplo2.Htm with a browser that supports Java (or run in the DOS window: “appletviewer
ejemplo2.Htm “):
<HTML>
<HEAD>
<TITLE> Example 2 – Applet Counter </ TITLE>
</ HEAD>
<BODY>
<applet code=”Ejemplo2.Class” width=170 height=150>
</ applet>
</ BODY>
</ HTML>
To conclude this chapter, note the differences between standalone application and applet:
• The application uses a main method, where boot
• The applet, however, started from a constructor (method with the same name as the class)
Plus:
• In the application we use System.Out.Println to print to standard output
• In the applet need to “draw” the text over a graphic background, so we use the method
g.DrawString inside the paint method (which is called each time it is necessary to redraw the applet)
With little work you can combine both cases in a single object, so that the same kind serves to
use of two ways:

/ / File: Ejemplo3.Java
/ / Compile with: javac Ejemplo3.Java
import java.Applet .*;
import java.Net .*;
import java.Io. *;
Example3 public class extends Applet (
static int n;
static Counter laCuenta;
public Example3 () (
laCuenta = new Counter ();
)
public static void main (String args []) (
laCuenta = new Counter ();
paint ();
)
public static void paint () (
System.Out.Println ( “Account …”);
System.Out.Println (laCuenta.GetCuenta ());
n = laCuenta.IncCuenta ();
System.Out.Println (n);
laCuenta.IncCuenta ();
System.Out.Println (laCuenta.GetCuenta ());
System.Out.Println (laCuenta.IncCuenta ());
)
public void paint (Graphics g) (
g.DrawString ( “Account …”, 20, 20);
g.DrawString (String.ValueOf (laCuenta.GetCuenta ()), 20, 35);
n = laCuenta.IncCuenta ();
g.DrawString (String.ValueOf (n), 20, 50);
laCuenta.IncCuenta ();
g.DrawString (String.ValueOf (laCuenta.GetCuenta ()), 20, 65);
g.DrawString (String.ValueOf (laCuenta.IncCuenta ()), 20, 80);
)
)
This class can be run with “java Example3” in a DOS window, as loaded from a page
HTML:
<applet code=”Ejemplo3.Class” width=170 height=150>
</ applet>
Note that it is testing the applet with appletviewer (ejemplo3.Htm appletviewer “), as it indicates in
DOS window if there are any errors during execution. The browsers let through many mistakes,
simply lifting the screen out of the wrong code.
Note that in this whole development of class Example1, Example2 and Example3 at any time
returned to play the class Counter!

Class Structure

Let’s start by analyzing the counter class to go see the parts that constitute a class one by one and
in detail. This chapter will be a little bored with the comprehensive (although some more complicated points
exceptions and threads will leave them for later), but I feel good to have a summary
complete syntax now.
Then we’ll arming small applications to test everything.
Recall the definition of the class Counter:
/ / Implementation of a simple counter
public class Counter (
/ / Attributes
int cnt;
/ / Constructor
public Counter () (
cnt = 0;
)
/ / Methods
public int incCuenta () (
cnt + +;
return cnt;
)
public int getCuenta () (
return cnt;
))

Class declaration

The class is declared using the line public class Counter. In the general case, the declaration of a
class can contain the following elements:

[Public] [fine l |abstract] class
Class [extends
ClaseMadre] [implements
Interfase1 [, Interfase2] …]
Or, to interfaces:
[Public] interface interface [extends
InterfaseMadre1 [, InterfaseMadre2] …]
As shown, the only thing required is class and class name. The interfaces are a case of class
particular we will see later.

Public, final or abstract

Define a class as public (public)
means it can be used by any class in any
package. If not, can only be used by classes in the same package (more on packages later;
Basically, this is a group of related classes and interfaces, such as library packages
Included with Java).
A class final (final)
is that it can not have classes that inherit. This is used primarily by
safety reasons (for a class can not be replaced by one to inherit) or by design
application.
An abstract class (abstract)
is a class that can be inherited, but can not be instantiated. Is,
literally, the abstract (as the Number class defined in java.Lang). What is? To model
concepts. For example, the Number class is an abstract class that represents any kind of numbers (and
their methods are not implemented: they are abstract), the descendants of this class, such as Integer or Float,
it implemented the methods of the motherNumber, and can be instantiated.
As such, a class can not be final and abstract at a time (because the abstract class requires
descendants …)
A bit complex? He’ll understand better when we see cases, such as the interfaces (which
definition is abstract because it does not implement its methods).

Extends

The statement indicates what kind extends down from ours. If omitted, Java assumes that descends from the
superclass Object.

When a class extends another, it means that inherits its attributes and methods (ie, to
Unless we redefine, their methods are the same as the mother class and can be used in
transparent, unless privatemother in class or for subclasses of other packages
protected or own package). We shall see the status of methods very soon, do not despair!

Implements

An interface (interface)
is a class that declares its methods but not implemented, when a class
implements (implements)
one or more interfaces, it must contain the implementation of all methods (with
the same lists of parameters) of these interfaces.
This serves to give a common ancestor to several classes, forcing them to implement the same methods and,
therefore, to behave similarly in terms of its interface with other classes and subclasses.

Interface

An interface (interface), as mentioned, is a class that implements its methods but also left for the
implementation to other classes. The interfaces can also descend from other interfaces but not others
classes.
All their methods are by definition abstract and their attributes are final (though not shown in the
body of the interface).
They are useful to generate relationships between classes that are not otherwise related (making
implement the same methods), or to distribute packets of classes indicating the structure of the interface
but not individual classes (anonymous objects).
While different classes can implement the same interfaces, while descending from other classes, this
not really multiple inheritance since a class can inherit attributes and methods of an interface, and
classes that implement an interface may not even be related.

The body of the class

The class body, enclosed in (and) is the list of attributes (variables) and methods (functions) that
represent the class.
It is not mandatory, but in general the attributes are listed first and then the methods.

Attribute Declaration

In Java there is no global variables, all variables are declared within the body of the class or within a
method. Variables declared inside a method are local to the method, the variables declared in the
class body are said to be members of the class and are accessible by all class methods.
Moreover, in addition to the attributes of the class itself can access all the attributes of the class
which falls, for example, any class that descends from the Polygon class inherits the attributes npoints,
XPoints and ypoints.
Finally, members of the class attributes can be attributes of class or instance attributes are said
which are attributes of class if you use the static keyword:
In this case the variable is unique for all
instances (objects) of class (occupying a single location in memory). If not using static, the system creates a place
again for that variable with each instance (ie it is independent for each object).
The declaration follows a consistent format:
[Private | protected | public] [static] [final] [transient] [volatile] type variableName [= Value];
Private, protected or public
Java has 4 different types of access to variables or methods of a class: private, protected, public or
package (if nothing is specified).
According to the way an attribute is specified, objects of other classes have different possibilities
access:
Access from:
private protected public (package)
the class itself SSSS
subclass in the same
NSSS package
other classes in the
same package
NSSS
subclasses in other
NXSN packages
other classes in other
NNSN packages
S: You can access
N: not accessible
X: You can access the attribute on objects belonging to the subclass, but not those belonging to the class
mother. It is a special case we shall see examples of this.

Static and final

As previously noted, serves to define a static attribute and class, that is unique for all objects
kind.
As to the end, as in class, determines whether an attribute can not be overwritten or redefined. That is:
is not a variable but a constant.

Transient and volatile

They are quite particular cases and had not been implemented in Java 1.0.
Transient called attributes that are not recorded when an object is archived, so do not form part of
permanent state of it.

Volatile variables are used asynchronously modified by objects in different threads(literally
“threads, tasks running in parallel), basically this means that various tasks can try
simultaneously modify the variable and volatile ensures that re-read the variable (if it was
modified) each time you are going to use (ie instead of using storage registers as buffer).

The types of Java

The types of available variables are basically 3:
· Basic types (not objects)
· Arrays (arrays)
· Classes and interfaces
With what we see every time we create a class or interface you are defining a new type.
The basic types are:

Type Size / Format Description

8-bit byte 2’s complement integer from a byte
short 16-bit 2’s complement integer short
int 32-bit 2’s complement integer
long 64-bit 2’s complement Longint
float 32-bit IEEE 754 floating point single precision
double 64-bit IEEE 754 floating point, double precision
char 16-bit Unicode character A character
boolean true, false Boolean value (true or false)
The arrays are arrays of any type (basic or not). For example, a class Integer; an array of
objects of that class would be noticed:
Integer array [];
The arrangements are always dynamic, so that is not valid to put something like:
Integer string [5];
Although it does apply to initialize an array, as in:
int days [] = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
char letters [] = ( ‘E’, ‘F’, ‘M’, ‘A’, ‘M’, ‘J’, ‘J’, ‘A’, ‘S’, ‘O’, ‘N’, ‘D’);
String names [] = new String [12];
Side note: do not confuse a String (string) with an array of characters! Are things well
different!
We’ll talk later of String and StringBuffer classes.
In Java, for all variables of basic type is accessed to the value assigned to it directly (not
know the address of memory it occupies). For other (arrays, classes or interfaces) are accessed through
a pointer to the variable. The pointer value is not available or can be modified (as in C), Java does not
it needs this and also undermine the strength of language.
In fact, in Java there are no pointer types, struct or union.
An object is more than a structure, and
Unions are not necessary with an appropriate programming method (and also avoids the possibility of
access the data incorrectly).
Something else about the arrangements: because Java handles memory management for them, and launches
exceptions if you attempt to violate the space assigned to a variable, you avoid typical problems of C as
access forbidden memory locations or off site identified for the variable (as when using a
subscript larger than expected for an array …).

And the methods ..


The methods, like classes, have a declaration and a body.
The statement like the following:
[Private | protected | public] [static] [abstract] [final] [native] [synchronized] TipoDevuelto NombreMétodo
([Type1 name1 [, type2 name2]
…]) [throws excepción1 [, excepción2] …]
A not worry, little by little will clarify everything with examples.

Basically, the methods are like C functions: implemented through functions, operations and
control structures, the calculation of some parameter which is the object returned to the caller. Only
may return a value (type TipoDevuelto) but may not return any (in this case
TipoDevuelto is void).
As we shall see, the return value is specified with the return statement within
the method.
The methods may use values that will pass the object that calls (parameters), indicated with type1
name1, type2 name2
… In the scheme of the statement.
These parameters can be any of the types and views. If they are basic types, the method is
parameter value, if they are arrays, classes or interfaces, receives a pointer to the data (reference). Consider a
small example:
public int AumentarCuenta (int amount) (
cnt = cnt + quantity;
return cnt;
)
This method, if we add to the class counter, adds much to the accumulator cnt.
In detail:
· The method receives an integer value (quantity)
• lo adds to the instance variable cnt
· Returns the sum (return cnt)
What if I want to return more than one value? For example, suppose we want to do a method
within a class that returns the mouse position.
The following does not work:
GetMousePos void (int x, int y) (
x = …., / / this does not work!
y = …., / / this too!
)
because the method can not modify the parameters x and y (which have been passed by value, meaning that the
method is the numerical value but do not know where are the variables in memory).
The solution is used, instead of basic types, a class:
mousePos class (public int x, y;)
and then use that class in our method:
void GetMousePos (mousePos m) (
mx = … …;
m = … …;
)
The rest of the statement
Public, private
and protected act exactly the same for methods for attributes, so let’s see
the rest.
The static methods (static)
are, as the attributes, class methods, if the method is not static
instance method. The meaning is the same as for attributes: a static method is shared by
all instances of the class.
We talked about abstract classes, abstract methods (abstract)
are those who are given the
statement but not the implementation (ie consisting only of the header). Any class that
contains at least one abstract method (or mother whose class contains at least one abstract method not
is implemented on the daughter) is an abstract class.
Is finally a method that can not be redefined by any descendant of the class.

Native classes are those that are implemented in another language (eg C or C + +) characteristic of
machine. Sun recommends to use at your own risk, because they really are outside the language. But the
ability to use old libraries that one armed and has no desire to rewrite there!.
The classes allow you to synchronize multiple threads synchronizedfor the case where two or more access
the same data concurrently. Again, more details will be in the future, when we talk about threads.
Finally, the throws clause serves to indicate that the class generates certain exceptions.

The body of methods

Again, remember our old class Counter:
/ / Implementation of a simple counter
public class Counter (
… … … … … … ..
public int incCuenta () (
cnt + +;
return cnt;
)
… … … … … … …
)
Among the methods may include:
Statement by local variables
· Allowance variables

· Mathematical operations
• Calling other methods:
· Within the class
· Instance, other classes
· Class of any kind
· Control Structures
· Exceptions (try, catch, we’ll see below)

Declaration of local variables

Local variables are declared as attributes of the class:
Type variableName [= value];
Ex: int sum;
float price;
Counter laCuenta;
Only here are not declared private, public, etc., But the variables defined within the method are only
accessible by him.
The variables can be initialized to create:
Ex: int sum = 0;
float price = 12.3;
LaCuenta counter = new Counter ();

Variable assignments

It assigns a value to a variable using the = sign:
Variable = Constant | Expression;
Example: sum = sum + 1;
price = 1.05 * price;
laCuenta.Cnt = 0;
The last case is valid if cnt is a public variable of the class Counter.
Personally I do not think
convenient direct access to variables of another object, since future changes to the object called
or the caller may tend the spread of errors … It is better to use as getCuenta or
hypothetical inicializarContador for it. In fact, some suggest that all variables of a class is
declared as private.

In the first case, or in general:
Variable = variable operator expression;
can be written in simpler form:
Variable operator = expression;
For example, sum = sum + 9 – amount;
can be written: sum + = 9-quantity;
and price = price * 0.97;
as price *= 0.97;

Math

There are several types of operators:
Unary: + – + + – ~! (type) … .. Etc.
They are placed before (or in some cases after) the constant or expression.
For example:-cnt; / / change sign, for example if cnt is 12 the result is -12; cnt unchanged.
cnt + + / / equal to cnt + = 1;
cnt + +; / / equivalent to cnt + = 1; see the difference when talking about control structures
– cnt / / is equivalent to cnt -= 1;
cnt -; / / equivalent to cnt -= 1;
Binary: + – * /% … .. Etc.
Van between two constants or expressions or a combination thereof.

For example: cnt + 2; / / debuelvo the sum of both.
average + (value / 2), / / as shown, you can use parentheses.
h / men / / division.
Cumulative% 3 / / remainder of integer division between them.
Note: + is also used to concatenate strings, the String and StringBuffer talk soon.
When mixed strings and numeric values, they are automatically converted to strings:
“The phrase has” + ext + “letters”
becomes: “The phrase has 17 letters” / / assuming that cannot = 17

Operator Precedence in Java

The following is the precedence of operators in compound expressions. However, as in all
languages, you should use parentheses when in doubt.
Postfix []. (params) expr + + expr —
Unary + + expr – expr + expr-expr ~!
Creation and “cast” new (type)
Multiplicative * /%
Additives + —
Offset <<>>>>>
Relational <> <=> = instanceof
Equality ==! =
Bitwise &
Bitwise Exclusive OR ^
Bitwise Inclusive OR |
Logical AND & &
Logical OR | |
Conditional? :
Assignment = + = -= *= / =% = ^ = & = | = <<=>> =>> =
Some examples:
[] Defines arrays: int array [];
(params) is the parameter list when calling a method: convert (value, base);
new to create an instance of an object: new Counter ();
(type) changes the type of an expression to another: (float) (total% 10);
>> Bitwise shifts a binary value: base>> 3;
<= Returns true if a value is less than or equal to another: total <= maximum;
instanceof returns true if the object is an instance of the class: Pope instanceof Food;
| | Returns true if either expression is true: (a <5) | | (a> 20)
Method Calls
It calls a method of the same class with just the method name and parameters between
parentheses, as shown, among others, in the example in bold:
/ / File: Complejo.Java
/ / Compile with: javac Complejo.Java
public final class Complex extends Number (
/ / Attributes:
private float x;
private float y;
/ / Constructor:
public Complex (float rx, float iy) (
x = rx;
y = iy;
)
/ / Methods:

public float Norm () (
return (float) Math.Sqrt (x * x + y * y);
)
/ / Mandatory (they are abstract in Number):
public double doubleValue () (
return (double) Standard ();
)
public float floatValue () (
Standard return ();
)
public int intValue () (
return (int) Standard ();
)
public long longValue () (
return (long) Standard ();
)
public String toString () (
return “(” + x + “) + i (” + y +”)”;
)
)
They can test the class (minimum) with the following sample application, the bold line is an example of
a call to a method of an object of another class. Note that in this case, you must call the method
on an object (instance) exists, as follows:
Nombre_del_Objeto <point> Nombre_del_Método (parameters)
/ / File: Ejemplo4.Java
/ / Compile with: javac Ejemplo4.Java
/ / Run with: java Example4
import java.Io. *;
Example4 (public class
public static void main (String args []) (
NumComp Complex = new Complex (4, -3);
System.Out.Println (numComp.ToString ());
System.Out.Println (numComp.Norma ());
))
In the Complex class we have also an example of a call to a class method, or static:
return (float) Math.Sqrt (x * x + y *
y);
Since the method is class, no need to call for a particular object. In that case, instead of
name of an existing object can be used directly on behalf of the class:
Nombre_de_la_Clase <point> Nombre_del_Método (parameters)
Control structures
Control structures in Java are basically the same as in C, except goto, that there
(at last a serious language!)
if … [else]
The most common of all, allows to execute an instruction (or sequence of instructions) if one condition
given (or, with the else clause, execute another sequence otherwise).
if (Boolean_Expression) instrucción_si_true;
[else instrucción_si_false;]

or:
if (Boolean_Expression) (
instrucciones_si_true;
)
else (
instrucciones_si_false;
)
For example:
public final String toString () (
if (y <0)
return x + “-i” + (-y);
else
return + x + “+ i” + y;
)
… Brake switch … Case … Default
Lets run a series of operations in the event that a variable has a given integer value. The
execution skips every case until it finds one with the variable value, and runs from there to the
end of the case or until you find a break, in which case it jumps to the end of the case. The default allows to
a set of instructions that are executed in case of equality is not for any of the case.
switch (expresión_entera) (
case (value1) instrucciones_1;
[break;]
case (value2): instrucciones_2;
[break;]
… ..
case (valorN) instrucciones_N;
[break;]
default: instrucciones_por_defecto;
)
For example:
switch (month) (
case (2): if (leap ()) days = 29;
else days = 31;
break;
case (4):
case (6):
case (9):
case (11): days = 30;
break;
default: dias = 31;
)
While
Lets run a group of statements while a given condition is met:
while (Boolean_Expression) (
instructions …

)
For example:
while (line! = null) (
archivo.LeerLinea line = ();
System.Out.Println (line);
)
Do … While
Similar to above, except that the condition is evaluated at the end of the cycle and not at the beginning:
do (
instructions …
) While (Boolean_Expression);
For example:
do (
archivo.LeerLinea line = ();
if (line! = null) System.Out.Println (line);
) While (line! = Null);
For
Also to repeatedly execute a series of instructions, is a bit more complex:
for (instrucciones_iniciales; condición_booleana; instruccion_repetitiva_x) (
instructions …
)
While the instructions may be either (the loop is repeated while the condition is true), what
is often used to “count” the number of times you repeat the instructions, it could indicate as follows:
for (counter = valor_inicial; counter <valor_final; count + +) (
instructions …
)
For example:
for (i = 0, i <10; i + +) (
System.Out.Println (i);
)
or, to count backward;
for (i = 10; I> 0, i -) (
System.Out.Println (i);
)
Break and continue
These instructions can skip to the end of a repetitive execution (break) or the beginning of the same
(continue).
For instance:
import java.Io. *;
class Loop (

public static void main (String argv []) (
int i = 0;
for (i = 1, i <5; i + +) (
System.Out.Println ( “before” + i);
if (i == 2) continue;
if (i == 3) break;
System.Out.Println ( “after” + i);
)
)
)
The output is:
before 1
then 1
before 2
before 3
Why? “i” starts at 1 (print “before” and “after”); when it goes to 2, the continue skips to the beginning of
loop (does not print the “after”). Finally, when “i” is 3, break terminates the loop.
Other …

There are other instructions that control program flow:
· Synchronized (to see along with the threads)
· Catch,
· Throw,
· Try,
· Finally (to do with exceptions)
Now yes, we use all our knowledge in order to create some Java applications and step
go see the standard libraries …
Let’s do something …

Well, let’s do a little application to practice a bit.
To begin, we will develop a little class to work with complex numbers.
Complex class
/ / Save as Complejo.Java
/ / Compile with “javac Complejo.Java”
public final class Complex extends Number (
/ / Attributes:
private float x;
private float y;
/ / Constructors:
public Complex () (
x = 0;
y = 0;
)
public Complex (float rx, float iy) (
x = rx;
y = iy;
)
/ / Methods:
/ / Standard
Standard public final float () (
return (float) Math.Sqrt (x * x + y * y);
)
public final float Norm (Complex c) (
return (float) Math.Sqrt (ax * c.X + cy * cy);
)
/ / Conjugate
final public Complex conjugate () (
Complex r = new Complex (x,-y);
return r;
)
final public Complex conjugate (Complex c) (
Complex r = new Complex (cx,-cy);
return r;
)
/ / Mandatory (they are abstract in Number):
public final double doubleValue () (
return (double) Standard ();
)
public final float floatValue () (
Standard return ();
)
public final int intValue () (
return (int) Standard ();
)
public final long longValue () (
return (long) Standard ();
)
public final String toString () (
if (y <0)
return x + “-i” + (-y);
else
return x + “+ i” + y;
)
/ / Operations Math
public static final Complex Addition (Complex c1, Complex c2) (
return new Complex (c1.X + c2.X, c1.Y + c2.Y);
)
public static final Complex Subtract (Complex c1, Complex c2) (
return new Complex (c1.X-c2.X, c1.Y-c2.Y);
)
public static final Complex Product (Complex c1, Complex c2) (
return new Complex (c1.X * c2.X-c1.Y * c2.Y, c1.X * c2.Y + c1.Y * c2.X);
)
/ / We will come in handy to learn exceptions …
/ / As division by zero!
public static final DivEscalar Complex (Complex c, float f) (
return new Complex (ax / f, c / f);
)
public static final Complex Ratio (Complex c1, Complex c2) (
float x = c1.X * c2.X + c1.Y * c2.Y;
float y =-c1.X * c2.Y + c1.Y * c2.X;
float n = c2.X * c2.X + c2.Y * c2.Y;
Complex r = new Complex (x, y);
DivEscalar return (r, n);
)
)
We can make some comments …
First: no include here, since the only library we use is java.Lang and includes
automatically.
Second is public final class, which means that any kind in this or other packages can use it,
but any class can inherit (or so it’s a sterile class …).
Let’s summarize the attributes and methods of the class:
/ / Attributes:
private float x;
private float y;
Being private, we can not access them from outside. As well the class is final, no way
x and y access. Furthermore, not being static, each instance of the class will have its own x and y.
/ / Constructors:
public Complex ()
public Complex (float rx, float iy)
The class has two constructors, which are differentiated by their “signature” (signature), or the amount and type of
parameters. The first serves to create an object of type complex and undefined value (although
Actually the method is initialized to zero) with the second, we can define the value in creating it.
/ / Methods:
Standard public final float ()
public final float Norm (Complex c)
final public Complex conjugate ()
final public Complex conjugate (Complex c)
These methods also are dual, when used without parameters return the rule or conjugate
individual object (instance):

v = miComplejo.Norma () / / for example
otroComplejo = miComplejo.Conjugado ();
With parameters, however, return the rule or the conjugate of the parameter:
v = unComplejo.Norma (miComplejo);
otroComplejo = unComplejo.Conjugado (miComplejo);
Note that the following is invalid:
otroComplejo = Complejo.Norma (miComplejo), / / CAN NOT BE!
… Because the method is not static, therefore, must be named for a particular instance (in this case,
unComplejo).
/ / Mandatory (they are abstract in Number):
public final double doubleValue ()
public final float floatValue ()
public final int intValue ()
public final long longValue ()
These methods is required to define, since in the mother class Number are abstract methods, so it
we implement here.
Like all such methods are final, so it can not be redefined. It is important
Actually since the class can not have descendants …
public final String toString ()
This method serves to represent the complex as a character string of the form x + iy.
/ / Operations Math
public static final Complex Addition (Complex c1, Complex c2)
public static final Complex Subtract (Complex c1, Complex c2)
public static final Complex Product (Complex c1, Complex c2)
public static final DivEscalar Complex (Complex c, float f)
public static final Complex Ratio (Complex c1, Complex c2)
Here we define several mathematical operations. Note that are defined as static, meaning that the
methods are unique regardless of the instances. This allows us to execute on a
instance or directly on the class:
miComplejo = unComplejo.Suma (comp1, COMP2); / / worth
miComplejo = Complejo.Suma (comp1, COMP2) / / also true!
For example, the following application shows how you can use some of these methods:
/ / File: Ejemplo5.Java
/ / Compile with: javac Ejemplo5.Java
/ / Run with: java example5
import java.Io. *;
example5 (public class
public static void main (String args []) (
Complex c1 = new Complex (4, -3);
System.Out.Println (c1 + “rule =” + c1.Norma ());
Complex c2 = new Complex (-2.5);
System.Out.Println (c2 + “rule =” + c2.Norma () + “”);
System.Out.Println (“(“+ c1 + “) / 4:” + Complejo.DivEscalar (c1, 4));
System.Out.Println ( “Sum:” + Complejo.Suma (c1, c2));
System.Out.Println ( “Subtract:” + Complejo.Resta (c1, c2). ToString ());
System.Out.Println ( “Multip:” + Complejo.Producto (c1, c2). ToString ());
System.Out.Println ( “Currency:” + Complejo.Cociente (c1, c2). ToString ());
)
)
There are several things to note: for example, we can declare variables while we create:
Complex c1 = new Complex (4, -3);
c1 and c2 are two objects (instances) of class Complex.
Note also that there is no need to print:
System.Out.Println (c1.ToString ()…….);
since it automatically uses the method println toString () of class to print. C1 Simply put, as
in the program, although c1.ToString () is also valid.
Also see the use of static methods, class by accessing them directly at:
System.Out.Println ( “Sum:” + Complejo.Suma (c1, c2));
And here again we use toString (), but not bad if used Complejo.Suma (c1, c2). ToString ().
Something about the methods
Let us dwell now how to implement the class methodsComplex.
public final int intValue () (
return (int) Standard ();
)
Since we can not so easily turn into a whole complex to implement these methods have
chosen to use as the standard return value of the complex. In this case, and since the standard method ()
returns a float, use typecasting, ie we make it, preceded with (int).
public final String toString () (
if (y <0)
return x + “-i” + (-y);
else
return x + “+ i” + y;
)
Here we represent the complex as a string of characters. We used to represent the if
properly the sign of the imaginary part. Note also the amazing support that Java gives us at
variables x and y automatically convert String for concatenation (using the sign “+”)!
public static final Complex Ratio (Complex c1, Complex c2) (
float x = c1.X * c2.X + c1.Y * c2.Y;
float y =-c1.X * c2.Y + c1.Y * c2.X;
float n = c2.X * c2.X + c2.Y * c2.Y;
Complex r = new Complex (x, y);
DivEscalar return (r, n);
)
Here note that the variables x and y, defined as float, have nothing to do with the variables
(attributes) of the class that are defined at the beginning of it, but the method are local variables.
We use return DivEscalar (r, n), since DivEscalar is a proprietary method of the class is not necessary
Complejo.DivEscalar put.
What about r, the new Complex (x, y) we create? Nothing, when an object is not used more, the collector
junk automatically removes Java (eventually) of memory.
public final float Norm (Complex c) (
return (float) Math.Sqrt (ax * c.X + cy * cy);
)
Here we’re using another kind, Math, allowing us to perform various mathematical operations. This class
has the constants E and PI, and the methods:
abs (x) absolute value
acos (x) arc cosine
asin (x) arc sine
atan (x) arc tangent
atan2 (x, y) angular component of the polar representation of x, y
ceil (x) smallest integer greater than x
cos (x) cosine
exp (x) ex
floor (x) largest integer smaller than x
IEEEremainder (x, y) remainder of the division x / y according to the IEEE 754
log (x) natural logarithm
max (x, y) the greater of x and y
min (x, y) the lesser of x and y
pow (x, y) xy
random () random number between 0 and 1
rint (x) nearest integer to x (returns double)
round (x) nearest integer to x (returns an integer or a long)
sin (x) within
sqrt (x) square root
tan (x) tangent
Some of these methods trigger exceptions, such as sqrt or log of negative numbers. Later
see how to use exceptions.
Another class we’ve been using a lot is PrintStream, which owns the println method. In
System.Out.Println (…)
out is an attribute of the System class, the type (class) PrintStream:
public final class System extends Object
(
/ / Fields
public static PrintStream err;
public static InputStream in;
public static PrintStream out;
/ / Methods
………….
)
We will see other libraries (for input / output, graphics, etc.) very soon.

Java through the window
To do something a little more fun, let’s start working with the java.Awt library, which is what
contains an entire group of objects to work with windows and their contents, buttons, lists, etc..
Our first window
In Java, the Window class (descendant of Container), the java.Awt library, lets you deploy
windows “bare”, ie without edges or menus. They are the basis for any type of window (normal, popup,
dialogues, etc.).. The other descendant of Container, Panel, is simpler and still serves as space for
an application to incorporate into his other elements (including other panels).
The Java interface as directed both to one another all keyboard events, mouse and focus that affect
(immediately see how to use these events).
Window Class Dialog descend (to implement dialogues) and Frame, a window more
Full: it has edge and menu, and close buttons, maximize, and so on.
The following example creates a window that does nothing but contains several elements, you can use
directly (from the DOS or Unix window with java example7) or as an applet within an HTML page.
While elements do not fire any action, can be used with full functionality (eg
edit the text within text boxes or press the button).
/ / Save as “Ejemplo7.Java”
/ / Compile with “javac Ejemplo7.Java”
import java.Net .*;
example7 public class extends Frame (
inAnApplet boolean = true;
public static void main (String args []) (
Example7 window = new example7 ();
window.InAnApplet = false;
window.SetTitle ( “Example”);
window.Pack ();
window.Show ();
)
public example7 () (
PanelAlto Panel = new Panel ();
panelAlto.Add ( “West”, new Label ( “Cartel”, Label.CENTER));
panelAlto.Add ( “East”, new TextArea ( “Text Area”, 5, 20));
add ( “North”, panelAlto);
PanelBajo Panel = new Panel ();
panelBajo.Add (new TextField ( “Text Field”));
panelBajo.Add (new Button ( “Button”));
add ( “South”, panelBajo);
)
public boolean handleEvent (Event ev) (
if (ev.Id == Event.WINDOW_DESTROY) (
if (inAnApplet) (
dispose ();
) Else (
System.Exit (0);
)
)
super.HandleEvent return (ev);
)
)
A little detail
The Frame class extends (ie to be a window to edge, although we’re not going to put menu).
Let’s use the flag to know if inAnApplet started as an applet or as standalone application (it should be
closed in a different way in each case)
example7 public class extends Frame (
inAnApplet boolean = true;
If called as a standalone application, the first thing that runs is main (…) in which case the application creates
an instance of example7 (running the constructor example7 () through new) defines who is not a
applet, and call three methods of the “grandmother” window:
· SetTitle that defines what will be the title that appears in the window
· Pack dimensions the elements that make up the window to its preferred size
· Show that shows the window
public static void main (String args []) (
Example7 window = new example7 ();
window.InAnApplet = false;
window.SetTitle ( “Example”);
window.Pack ();
window.Show ();
)
Ojo! Do not confuse the object (instance) with the Window class window!
If you load as an applet, then run the constructor example7 () as in the previous case:
public example7 () (
PanelAlto Panel = new Panel ();
panelAlto.Add ( “West”, new Label ( “Cartel”, Label.CENTER));
panelAlto.Add ( “East”, new TextArea ( “Text Area”, 5, 20));
add ( “North”, panelAlto);
PanelBajo Panel = new Panel ();
panelBajo.Add (new TextField ( “Text Field”));
panelBajo.Add (new Button ( “Button”));
add ( “South”, panelBajo);
)
This constructor defines two panels that form the contents of the window (panelAlto and panelBajo), fills
with a couple of components and puts them inside the window (remember example7 is a window!).
To see more clearly establishing the panel (or space to hold objects) with:
PanelAlto Panel = new Panel ();
Components are added to the panel using the add method:
panelAlto.Add ( “West”, new Label ( “Cartel”, Label.CENTER));
panelAlto.Add ( “East”, new TextArea ( “Text Area”, 5, 20));
He added the panel inside our object:
add ( “North”, panelAlto);
equivalent to:
this.Add ( “North”, panelAlto);
As can be seen (although it is invalid because the class is not static) as:
Ejemplo7.Add ( “North”, panelAlto);
As our class example7 descends from Frame Window it, and this Container, the add method as
is inheriting from … Her great-grandmother! Moreover, Panel is the daughter of Container, and using the same method
add ingredients. Interesting, no? Consider the structure:
— — Object Component Container Panel –+–
|
+ – Window Frame — — example7
Note that we used two different methods to add signature:
panelAlto.Add ( “West”, new Label ( “Cartel”, Label.CENTER));
……….
panelBajo.Add (new Button ( “Button”));
The method add (Component) add a component at the end, the method add (String, Component) adds
at a location specified by a word that depends on the LayoutManager, The object that is responsible for
order the components inside the container.
LayoutManager is an interface, and as such must be implemented through abstract objects that
There are several predefined in the library java.Awt: BorderLayout, CardLayout, FlowLayout, GridBagLayout
and GridLayout.
The default layout is BorderLayout, which defines the areas in the container “North”, “South”, “West”,
“East” and “Center” and is used here. CardLayout can “stack” components such as letters and see
one at a time, FlowLayout sorts from left to right as a text, arranges them in a GridLayout
grid where each component has a fixed size and GridBagLayout puts them in a grid but
each may have the desired size.
Note that there is no need to call in case the applet, to pack () and Show ().
And the events …

Now we will see a method being the ancestor class! Needless to say, I like this the
objects?
Let’s redefine handleEvent (Event), which is the method that analyzes the events aimed at component and
take appropriate action.
The Event class defines basically a series of methods to see if a control key
down and many constants that indicate whether pushed or moved the mouse, pressing any key on
particularly if they changed the window size, etc.. In particular there are some interesting attributes:
· Id indicating the type of event
· Target component that indicates how the event occurred
· Key which key was pressed if it was a keyboard event
etc.

In the descendants of components, the handleEvent method is called automatically whenever
produces an event on the component. In this case, we simply look for an event (on our
example7 class object) was “close window”, which is identified by event.Id =
WINDOW_DESTROY (a constant static of the Event class, and as such we can use the name
of the class as Event.WINDOW_DESTROY):
public boolean handleEvent (Event ev) (
if (ev.Id == Event.WINDOW_DESTROY) (
if (inAnApplet) (
dispose ();
) Else (
System.Exit (0);
)
)
return super.HandleEvent (event);
)
In that case, if our example was fired as an application call the method System.Exit (0), which closes the
application and if it was an applet call Dispose (), implementing an interface method
ComponentPeer which is responsible for removing all components and the window itself.
Note that any other event leaves continue to return super.HandleEvent (event), which calls the
handleEvent method of the class mother and the prefix this. Refers to a method of the class itself, the
prefix super. Calls the mother class method (however redefined). In this case, the call is
back to Component.HandleEvent, which determines the type of event and calls one of the methods
action, GotFocus, LostFocus, keyDown, keyUp, MouseEnter, mouseExited, mouseMove, mouseDrag,
mouseDown or mouseUp as appropriate (and returns true). If no method is applicable, returns
false.
It’s very common to redefine a method, consider the call before or after class method
predecessor to initialize or a completed task.
A window with life
First, let’s create an HTML page to load our example8 class, who is an applet
(but also can run as standalone with “java example8”), for example:
<! – Archive Ejemplo8.Htm – HTML for example ->
<HTML>
<HEAD>
<TITLE> Example 8 – Data Window </ TITLE>
</ HEAD>
<BODY>
Here you have to open a data entry window
<applet code=”Ejemplo8.Class” width=170 height=150>
</ applet>
</ BODY>
</ HTML>
Our applet is very simple because we will use classes defined in this chapter, and start
only create a window defined in the class Ventana8:
/ / File: Ejemplo8.Java
/ / Compile with “javac Ejemplo8.Java”
import java.Net .*;
import java.Applet .*;
example8 public class extends Applet (
public static void main (String arg []) (/ / to call her “java example8”
new Ventana8 (Standalone Example “, true);
)
public void init () (/ / runs when opening an applet
new Ventana8 ( “Sample Applet”, false);
)
)
With the parameters we pass to the class indicated Ventana8 him the title of the window and if you load
as an applet or not (as the method of closing varies).

Traveling with Java

Now we will work with our class Ventana8, a window that allows us to select a date and two
cities (and from) that simulates a window to purchase tickets, for example, a terminal
bus.
The example is based on one of the book “Java Programming” by Macary and Nicolas, although somewhat improved and
expanded.
In our window we can enter a date by hand or using buttons directly Today and Tomorrow
choose city of departure and arrival of two lists, and then pressing a button that will show
services available, we will buy the tickets, etc..
As we enter the data, the button will display the detail of what was selected.
Our window will be something like:
Let’s start arming the Ventana8 class structure:
import java.Net .*;
Ventana8 class extends Frame (/ / child of Frame
/ / Here we will add later
/ / Some variables to store data
/ / (Cities of departure and arrival date)
ok button, / / also buy tickets button
enApplet boolean, / / and another to indicate whether an applet or not
Ventana8 (String title, boolean enApplet) (/ / a constructor
super (title); / / call the Frame
this.EnApplet = enApplet; / / save this
/ / Here we will create the buttons, lists, etc.
/ / With their initial values
/ / And put them in the window.
/ / For example:
ok = new Button ( “Journey: from: to: the ?/?/?”);
add ( “South”, ok);
pack (), / / size the window
show (); / / and show it!
)
public boolean handleEvent (Event e) (/ / to handle events
if (e.Id == Event.WINDOW_DESTROY) (/ / close the window
if (enApplet) dispose ();
else System.Exit (0);
)
/ / Here we will look if a button was pressed
/ / Or something was selected from a list
/ / And act accordingly
return super.HandleEvent (e), / / handle other events the Frame
)
ActualizaBoton void () (
/ / Here a method that will serve
/ / To update the button to buy tickets
/ / As the text of it is updated every
/ / Once you select a city or changes the date
)
void Activate () (
/ / And here a method when you press
/ / The button that is supposed to consult
/ / A database and open a window
/ / To sell the ticket
))
Our program it works! Although a bit incomplete, of course …
Just let’s examine a little the constructor, which is most interesting here.
First call the constructor of the class mother, who is responsible for creating the window:
Ventana8 (String title, boolean enApplet) (/ / a constructor
super (title); / / call the Frame
This would be like calling super.Frame (title) or Frame (title) as the constructor method has the
same class name. Then with:
this.EnApplet = enApplet; / / save this
enApplet attach to our class variable parameter value is passed to the constructor, which is
called the same. This prefix, which refers to the particular instance of the class, differentiating one from another
(this is true for variables to methods).
ok = new Button ( “Journey: from: to: the ?/?/?”);
add ( “South”, ok);
Here we have created a button at the bottom of the window (for now all we set), then
size the window and show:
pack (), / / size the window
show (); / / and show it!

Rosters

Now we will begin to create other objects in order to complete our application. Let’s start with the
city lists.
For that, we create an object that simply descendant Panel contains a list of cities
predefined and a title that says “Select City” and then “exit” or “arrival”.
Also add a method
import java.Net .*;
SelecPueblo class extends Panel (
private List listaPueblos;
SelecPueblo (String salidaOllegada) (
setLayout (new BorderLayout (20,20));
/ / We set the title, which will be a Label:
StringBuffer title = new StringBuffer ();
titulo.Append ( “Select City”);
titulo.Append (salidaOllegada);
titulo.Append ( “”);
add ( “North”, new Label (titulo.ToString ()));
/ / We put together a list of cities that will be a List:
listaPueblos = new List (4, false);
listaPueblos.AddItem ( “Buenos Aires”);
listaPueblos.AddItem ( “La Plata”);
listaPueblos.AddItem ( “Blue”);
listaPueblos.AddItem ( “Rosario”);
listaPueblos.AddItem ( “Cordoba”);
listaPueblos.AddItem (Bahía Blanca);
add ( “South”, listaPueblos);
)
public String getDescription () (
listaPueblos.GetSelectedItem return ();
)
)
Not much to analyze here, I think. ListaPueblos variable is private, but you can see what the
city selected by getDescription (which is public). This method calls the method
getSelectedItem of the list, which returns the selected text.
In the constructor, we set the title text as a StringBuffer. StringBuffer objects are similar to
the String class but can be modified. Instead String objects, once created, can not
be modified directly: its methods (concat, toLowerCase, etc.). Simply create a new String
with the new value.
This was done to introduce this new class of course would have been easier to, as you can
check with the same result:
Tit String = “Select City” + salidaOllegada + “:”;
add ( “North”, new Label (tit));
Moreover, we create the object listaPueblos as new List (4, false), indicating that the list will be 4
lines and you can only select one item at a time. Then add 6 items by addItem and
added to the panel.
Now we can add lists to your window and put a couple of variables to save:
Ventana8 class extends Frame (/ / child of Frame
SelecPueblo cs / / city of departure
SelecPueblo cl / / city of arrival
ok button, / / also buy tickets button
enApplet boolean, / / and another to indicate whether an applet or not
Ventana8 (String title, boolean enApplet) (/ / a constructor
super (title); / / call the Frame
this.EnApplet = enApplet; / / save this
cs = new SelecPueblo ( “EXIT”); / / DEPARTURE CITY
add ( “Center”, cs);
cl = new SelecPueblo ( “ARRIVAL”); / / CITY OF ARRIVAL
add ( “East”, cl);

ok = new Button ( “Journey: from: to: the ?/?/?”);
add ( “South”, ok);
pack (), / / size the window
show (); / / and show it!
)
………………………
You can taste how it looks, but for now we have a lot of functionality …

Adding dates

Another panel will serve to further select or enter the date:
import java.Net .*;
import java.Net .*;
DiaPartida class extends Panel (
private TextField eldia;
private Button today;
private Button nextDay;
DiaPartida () (
setLayout (new GridLayout (4.1));
eldia = new TextField ();
elDia.SetText (GetHoy ());
today = new Button ( “Today”);
nextDay = new Button ( “Tomorrow”);
add (new Label ( “Day out:”));
add (eldia);
add (today);
add (nextDay);
)
private String GetHoy () (
Date d = new Date ();
int day = d.GetDate ();
int month = d.GetMonth ();
int year = d.GetYear ();
return months +”/”+ day +”/”+ year;
)
private String GetManana () (
Date d = new Date ();
int day = d.GetDate ();
int month = d.GetMonth ();
int year = d.GetYear ();
day = day + +;
switch (month) (
case (1):
case (3):
case (5):
case (7):
case (8):
case (10): if (day> 31) (
day = 1;
month + +;
)
break;
case (12): if (day> 31) (
day = 1;
month = 1;
year + +;
)
break;
case (4):
case (6):
case (9):
case (11): if (day> 30) (
day = 1;
month + +;
)
break;
default: if (day> 28) (/ / eye must be corrected for leap!
day = 1;
month + +;
)
)
return months +”/”+ day +”/”+ year;
)
public String getDescription () (
elDia.GetText return ();
)
public boolean handleEvent (Event e) (
if (e.Target == today)
elDia.SetText (GetHoy ());
if (e.Target == nextDay)
elDia.SetText (GetManana ());
return super.HandleEvent (e);
)
)
This is a bit longer but not more complex. Come by:
DiaPartida () (
setLayout (new GridLayout (4.1));
eldia = new TextField ();
elDia.SetText (GetHoy ());
today = new Button ( “Today”);
nextDay = new Button ( “Tomorrow”);
add (new Label ( “Day out:”));
add (eldia);
add (today);
add (nextDay);
)
The constructor creates a panel with four fields on a vertical grid, which displays the text “Day
output: “, the text input field and buttons eldia today and nextDay.
The private method uses the methods getDate getHoy, getMonth getYear class and date in building a
String with the current date. GetManana The private method does the same to read the current date, and adds
1 a day to take the next day. The switch verifies that if passed next month-end and take the first day
the following month (or the first day of the year if it is in December). Note that the years were not considered
leap in February to avoid complicating the method, but it is difficult to correct.
Another way is to assemble an array of days of each month, correct days of February for the years
leap, and compare against this array instead of using a switch. The idea is always the same: to return a
String with the date of the next day.
Notice something interesting: how are you classes are loaded and executed on the client machine, the date that appears is
the client and not theserver (which may be different depending on the time and place of the world we are
both machines).
GetDescription method is public and is used to enter the date you entered from the other
classes, simply returns the field content Eldi, TextField class.
Here we have developed the method handleEvent:
public boolean handleEvent (Event e) (
if (e.Target == today)
elDia.SetText (GetHoy ());
if (e.Target == nextDay)
elDia.SetText (GetManana ());
return super.HandleEvent (e);
)
If some action on one of the buttons, the method setText (TextField class) makes the
eldia text field the value of the current day or the next.
Note that we have only considered to be some event and not a particular event type, in fact the
method will act such as pressing the mouse over the button and when released. But this does not
annoying.
super.HandleEvent handles other events directed to the panel, as the data input by keyboard
text field for example.

Putting it together up here

Well, let’s put the pieces together we have so far adding these methods to our class
Ventana8 to see how the window is full:
Ventana8 class extends Frame (/ / child of Frame
SelecPueblo cs / / city of departure
SelecPueblo cl / / city of arrival

DiaPartida dp / / day of departure

ok button / / button to purchase tickets
enApplet boolean / / to indicate if an applet or not
Ventana8 (String title, boolean enApplet) (/ / a constructor
super (title); / / call the Frame
this.EnApplet = enApplet; / / save this
dp = new DiaPartida (); / / DAY OF DEPARTURE
add ( “West”, dp);

cs = new SelecPueblo ( “EXIT”); / / DEPARTURE CITY
add ( “Center”, cs);
cl = new SelecPueblo ( “ARRIVAL”); / / CITY OF ARRIVAL
add ( “East”, cl);
ok = new Button ( “Journey: from: to: the ?/?/?”);
add ( “South”, ok);
pack (), / / size the window
show (); / / and show it!
)

Rounding out the window

Let’s start by completing our ActualizaBoton method, which will amend the text of the ok button to
As you select the cities and dates:
ActualizaBoton void () (
StringBuffer b = new StringBuffer ( “Journey: from”);
if (cs.GetDescription ()! = null) b.Append (cs.GetDescription ());
else b.Append (“?”);
b.Append ( “a”);
if (cl.GetDescription ()! = null) b.Append (cl.GetDescription ());
else b.Append (“?”);
b.Append ( “on”);
if (dp.GetDescription ()! = null) b.Append (dp.GetDescription ());
else b.Append (“?/?/?”);
ok.SetLabel (b.ToString ());
)
Our method begins by creating a StringBuffer with the words “Ride: from”, and will add the rest:
• The city of departure, calling the getDescription method of cs (departure city)
· The text constant “a”
· Arrival city, calling the getDescription method of cl (arrival city)
· The text constant “on”
• The date selected by calling the getDescription method of dp (departure day)
If in any case receive a null string, it puts a question mark (or ?/?/? To date).
SetLabel method on the object type ok Label, amending the “tag” button.
We really methods return null if no selection call made?
Here:
SelecPueblo class extends Panel (
private List listaPueblos;
……………………….
public String getDescription () (
listaPueblos.GetSelectedItem return ();
))
The method of the List class getSelectedItem returns null if no items selected, so here
walk good. As DiaPartida class, set value input from the text on the current date and
that this is not the case would never … While creating the object we are putting Ventana8 Fixed text
button, not the object that returns the dp.
It would be better, more consistent, modify the constructor of Ventana8 to assemble the text by
ActualizaBotón method:
Ventana8 (String title, boolean enApplet) (
………………………………….
ok = new Button ( “any”);
ActualizaBoton ();
add ( “South”, ok);

pack ();
show ();
)

This already looks better! And while we test the method …

A little activity

Yes, now let’s complete our event handler:
public boolean handleEvent (Event e) (
if (e.Id == Event.WINDOW_DESTROY) (
if (enApplet) dispose ();
else System.Exit (0);
)
if ((e.Target == dp) | | (e.Target == cs) | | (e.Target == cl))
ActualizaBoton ();
if (e.Target == ok)
Activate ();
)

return super.HandleEvent (e);
)
Simply put, if we detect an event on any of our panels update the button text and if
can press the button to call the Activate method is supposed to take the data base
data, indicate services available, etc..
One important thing to note is that simply moving the mouse over one of the panels and calls
ActualizaBoton (because it flashes the note text, especially on a slow machine). Also, if they click on
Today or tomorrow the button without moving the mouse, the text of the ok button is not updated as the event is aimed
the button pressed and not the panel.
One way to filter only those events that interest us would use, for example:
if ((e.Target = cs.ListaPueblos) & & (e.Id == Event.LIST_SELECT)) ActualizaBoton ();
which is addressed to the list and not the panel in general, and takes into account the type of event.
Unfortunately, listaPueblos is private within the class and therefore SelecPueblo within cs. But
is better so, because public statements and read it from the outside would be quite dirty (and we read
could write).
There are several ways to improve it without making the mistake of declaring listaPueblos public. One possibility
is to verify, using cs.GetDescription (), if the text changed (and only then change the button text).
Another is making objects SelecPueblo class parents pass on any event they, or
better only selecting a list item, that’s enough to add to SelecPueblo class:
public boolean handleEvent (Event e) (
if ((e.Target == listaPueblos) & & (e.Id == Event.LIST_SELECT)) (
e.Target = this;
)
return super.HandleEvent (e);
)
In short, if the event is a selection panel from the list (both mouse and moving the selection
with arrows), change the target of the event for showing the panel (and not the list), otherwise the way to class
predecessor.
The same can be done with class for DiaPartida handleEvent:
public boolean handleEvent (Event e) (
if (e.Target == today) (
elDia.SetText (GetHoy ());

e.Target = this;
)
if (e.Target == nextDay) (
elDia.SetText (GetManana ());
e.Target = this;
)
if (e.Target == eldia) (
e.Target = this;
)
return super.HandleEvent (e);
)
This does not go as we would expect! The text field does not behave very well …
This is because the code platform dependent processes mouse events before calling
handleEvent, but processes the keyboard after the call to handleEvent.
This means that, for the text field, handleEvent (and therefore ActualizaBotón) is called
before modifying the text!
To correct this, we should process the keystrokes (which could use for
verify that you press a valid key).
Care! In future versions of Java could be implemented the same behavior for the mouse, and
So we would have to rethink the strategy.
Worse, only events that get sent to Java platform, for example, Motif does not send events
mouse move within a text field … Which means that we could never capture that type
events.
Canvas component only passes all events.
For simplicity, only update the button text when you press Enter (Event.Key = 10):
if ((e.Target == eldia) & & (e.Id == Event.KEY_PRESS)) (
if (e.Key == 10) e.Target = this;
)
Now we modify the method in our class handleEvent Ventana8 to support all these
Events:
public boolean handleEvent (Event e) (
if (e.Id == Event.WINDOW_DESTROY) (
if (enApplet) dispose ();
else System.Exit (0);
)
if (((e.Target == == Event.ACTION_EVENT e.Id )&&(( dp) | | (e.Id == Event.KEY_PRESS)))
| | ((cs == e.Target) & & (e.Id == Event.LIST_SELECT))
| | ((e.Target == cl) & & (e.Id == Event.LIST_SELECT)))
ActualizaBoton ();
if (e.Target == ok)
Activate ();
return super.HandleEvent (e);
)
Obviously, we process all the keys would be far more complicated … Anyway, the method
DiaPartida would be something like:
if ((e.Target == eldia) & & (e.Id == Event.KEY_PRESS)) (
/ / 1 – read the contents of field with: elDia.GetText ()
/ / 2 – modified according to the key pressed: e.Key
/ / 3 – put the result on the field with: elDia.SetText (text)
/ / 4 – change the subject to the panel event: e.Target = this;
/ / 5 – send the event to the parent object (not the parent class),
/ / In this case Ventana8 by:

GetParent (). DeliverEvent (e)

/ / 6 – to prevent further processing of the event through:result (true)
)
I savings account for these last two steps, is complicated because there are enough to drive the position of
cursor inside the text field, and so on. With what we did is pretty … I!

And finally ..


Well, we can only define the method Activate (). First let’s call ActualizaBoton () in case
one last thing he did was to enter text without pressing Enter, and leave for another day of quiet consultation
a file or database so that we will show the user of our program.
For now we will simply display a window with a nice selection and OK button.
First let’s make a very small modification to ActualizaBoton () to return the value we
Button Text (not to calculate it again):
ActualizaBoton String () (
StringBuffer b = new StringBuffer ( “Journey: from”);
……………………………………….
ok.SetLabel (b.ToString ());
)
And now let’s define our method, taking into account that our button will only act if they have entered
all data:
void Activate () (
if ((cs.GetDescription ()! = null) & & (cl.GetDescription ()! = null))
/ / We could also verify that the date is valid here
Result8 result = new Result8 ( “Result” ActualizaBoton ());
ok.SetLabel else ( “Specification incomplete!”);
)
All we need to define a simple class for our window Result8 result:
/ / Result8.Java file, compile with javac Result8.Java
import java.Net .*;
Result8 class extends Frame (
Button R_OK;
Result8 (String title, String text) (/ / constructor
super (title);
R_lbl Label = new Label (text);
R_OK = new Button ( “Ok”);
add ( “Center”, r_lbl);
add ( “South”, R_OK);
pack ();
show ();
)
public boolean handleEvent (Event e) (
if ((e.Id == Event.WINDOW_DESTROY) | | (e.Target == R_OK))
dispose (); / / closes the window but not the application
return super.HandleEvent (e);
)
)
Notice that I used and not dispose System.Exit! This will close only the result window, and continue to use the
application until closing occurs to us through meta-F4, alt-F4, the system menu of the window, the cross
Windows 95 or whatever suits you for your operating system.

Finale with tutto

I hope you understand! This application took some but on the way we had the opportunity to
learn a few things … If they collect all the code and generate several classes that define all
has to travel on rails and regardless of the platform.
If not … Let me know, and also climb the sources or classes.
Just in case, can try this application as an applet loading:
http://www.Amarillas.Com/rock/java/Ejemplo8.Htm

A parenthesis Input / Output

In Java there are many classes to read and write files (or other devices I / S). They are gathered in the
java.Io library.
Let’s start as always with a small working example and then we’ll get into the
necessary way of exceptions …

First Reading

/ / File: Ejemplo9.Java – compile with “javac Ejemplo9.Java” etc.. Etc.
import java.Io. *;
example9 (public class
public static void main (String args []) throws FileNotFoundException, IOException (
FileInputStream fptr;
DataInputStream f;
String line = null;
fptr = new FileInputStream ( “Ejemplo9.Java”);
f = new DataInputStream (fptr);
do (
f.Readline line = ();
if (line! = null) System.Out.Println (line);
) While (line! = Null);
fptr.Close ();
))
(Gee, what does that throws there?)
The sample program simply reads a text file and displays it on screen, something like the type
DOS or Unix cat.
Let us for now throws FileNotFoundException, IOException and go to the code.
fptr = new FileInputStream ( “Ejemplo9.Java”);
The FileInputStream class (descendant of InputStream) we used to refer to files or connections
(sockets) of a machine. We can access by passing a String as here, an object of type File or a
FileDescriptor type, but in essence the same. By creating an object of this type are “opening” a
file, classically speaking.
If the file does not exist (eg replace “Ejemplo9.Java” by something else, like “noexiste.Txt”)
us to run an error:
C: javacurso> java example9
java.Io.FileNotFoundException: noexiste.Txt
at java.Io.FileInputStream. <init> (FileInputStream.Java: 51)
at Ejemplo9.Main (Ejemplo9.Java: 9)
(Wow! FileNotFoudException Where did I see that before?)
Just when the file you want to access does not exist, Java “throws” an exception. That is, a warning
that something went wrong and, if not taken any action, stop the program.
The FileInputStream class can be “throwing” (throws) the FileNotFoundException.
How to capture and handle exceptions? Then, first we finish with our program.
f = new DataInputStream (fptr);
The class DataInputStream allows us to read, independently of the hardware, data types, a
“current” (stream), in this case is a. He is a descendant of FilterInputStream and implements
DataInput, an interface.
When you create an object of type DataInputStream we refer to the file, we pass as parameter (fptr);
this class has a range of methods for reading data in different formats.
In our program we use one for reading lines, which returns null when it reaches the end of file or
String with the contents of the line:
do (

F.Readline line = ();


System.Out.Println (line);
) While (line! = Null);
Then read the print line, and repeat this until we return null.
Finally, we close the file:
fptr.Close ();
Both readLine as close can throw the IOException in case of error or close reading
file.
In fact, we could not have used a DataInputStream and work more directly:
import java.Io. *;
example10 (public class
public static void main (String args []) throws FileNotFoundException, IOException (
FileInputStream fptr;
int n;
fptr = new FileInputStream ( “Ejemplo9.Java”);
do (
n = fptr.Read ();
if (n! =- 1) System.Out.Println ((char) n);
) While (n! =- 1);
fptr.Close ();
)
)
Since the FileInputStream class also has methods to read the file. Only a few are
methods that allow for time to read an integer or an array of bytes. DataInputStream has methods for
read the data in many different ways, and generally more comfortable.

Catching exceptions

Yes, now let’s see how we manage to exceptions not to stop the program with us
a message so unattractive …
Instead of throwing the exceptions to the interpreter, let us process them through the catch clause:
/ / File: Ejemplo11.Java
/ / Compile with: javac Ejemplo11.Java

/ / Run with: java example11

import java.Io. *;
example11 (public class

Public static void main (String args []) (

FileInputStream fptr;
DataInputStream f;
String line = null;
try (
fptr = new FileInputStream (args [0]);

f = new DataInputStream (fptr);
do (
f.Readline line = ();
if (line! = null) System.Out.Println (line);
) While (line! = Null);
fptr.Close ();
)
catch (FileNotFoundException e) (
System.Out.Println ( “Hey, that file does not exist!”);
)
catch (Exception e) (
System.Out.Println ( “Error I / S!”);
)

))
We also made a change to choose the file to print from the command line, rather than enter it
fixed, using the argument that the method main (arg []), which consists of a list of strings with
parameters passed in the line below nombre_programa java. For example, if we call
this program:
java example11 archi.Txt otro.Xxx
arg [0] will contain “archi.Txt”, arg [1] will contain “otro.Xxx” and so on.
Of course, if we call without parameters example11 launch another exception when trying to access:
C: javacurso> java example11
java.Lang.ArrayIndexOutOfBoundsException: 0
at Ejemplo11.Main (Ejemplo11.Java: 10)
But we could also capture!
Let’s see how this is a bit of catching exceptions.
The try clause covers a part of the program where you can throw exceptions. If an exception is
produces Java looks a catch statement (nombre_de_la_excepción variable), and, if found,
executes what it contains. If there is a catch to this exception for the program and displays the error
that occurred.
For example, to avoid the latter error would be enough to add:
catch (ArrayIndexOutOfBoundsException e) (
System.Out.Println ( “You must enter a file name!”);
System.Out.Println ( “eg java example11 foo.Txt”);
)
Note that when you throw an exception as the program stops, because the code that follows the
launch of the exception is not executed. We will see how it behaves in an object that was created
the other, and how to use the finally statement to put a piece of code that runs no matter what happens.

The applets and files

Let’s see how it behaves if we modify this application for use as an applet.
/ *
/ / —– File: Ejemplo12.Java
* /
import java.Io. *;
import java.Net .*;
import java.Applet .*;
example12 public class extends Applet (
public void init () (
Ventana12 new ();
)
)
/ *
/ / ——– This class is what actually does the work
* /
Ventana12 class extends Frame (
TextArea content;
Button close;
Ventana12 () (
super ( “Example of I / S”);
content = new TextArea ();
close = new Button ( “Close”);
CargarArchivo ();
add ( “North”, content);
add ( “South”, close);
pack ();
show ();
)
public boolean handleEvent (Event e) (
if ((e.Id == Event.WINDOW_DESTROY) | | (e.Target == close))
dispose ();
return super.HandleEvent (e);
)
CargarArchivo void () (
FileInputStream fptr;
DataInputStream f;
String line = null;
try (
fptr = new FileInputStream ( “Ejemplo12.Java”);
f = new DataInputStream (fptr);
do (
f.Readline line = ();
if (line! = null)
contenido.AppendText (line + “”);
) While (line! = Null);
fptr.Close ();
)
catch (FileNotFoundException e) (
contenido.AppendText ( “Hey, that file does not exist!”);
)
catch (Exception e) (
contenido.AppendText ( “Error I / S!”);
)
))
We loaded from the page Ejemplo12.Html:
<HTML>
<HEAD>
<TITLE> Example 12 – Example file </ TITLE>
</ HEAD>
<BODY>
<applet code=”Ejemplo12.Class” width=170 height=150>
</ applet>
</ BODY>
</ HTML>
While we run it on the same machine, no problem (going very well!). But what if we try
charging from the network? For those who have not got a copy html server at:
http://www.Amarillas.Com/rock/java/Ejemplo12.Htm
The file is not listed! Instead an exception occurs, the status line in Microsoft Internet
Explorer, for example, reads:
exception: com.Ms.Applet.AppletSecurityException: security.File.Read: Ejemplo12.Java
This is due to Java security restrictions: Can not load FILES
ARE IN A MACHINE FROM DIFFERENT FROM THAT WHICH load the applet. The
applet runs on the client, and try to access a local file. That is what causes the exception (which
course, can be detected and treated with a catch …)
For security reasons, applets are more limited than local Java applications. Policies
the browsers handle security (not Java), and generally limits imposed on applets are:
· An applet can not load libraries (libraries) or define native methods
· Can not normally read or write files on the client that loads it from another server
· Can not make network connections except the server it comes from
· Can not start programs on the machine is running
· Can not read certain system properties
• In the windows of the applets shown that this is an applet
However, they can:
· Play Sounds
· They can establish connections to the server from which they come
· They can easily call HTML pages from the browser
· They can invoke public methods of other applets on the same page
· If you are loaded from the machine itself (locally) have none of the above restrictions
· They can keep running even if you change the page in the browser
In fact, the specification allows Java applets to read files on other machines giving the URL
complete, but browsers do not. We will see later how to exchange data between
machines in order to view a file server, for example.

Our modest “Editor”

To conclude this chapter, the following applet allows us to load, edit and burn files to ascii choice.
We can use actions including “cut & paste” from the windows manager (Ctrl-C and Ctrl-V in Windows)!
Load it with “appletviewer example13” after having compiled (or use an html page from a
browser):
/ *
/ / —– File: Ejemplo13.Java
* /
import java.Io. *;
import java.Net .*;
import java.Applet .*;
example13 public class extends Applet (
public void init () (
Ventana13 new ();
)
)
/ *
/ / ——– This class is what actually does the work
* /
Ventana13 class extends Frame (
TextArea content;
Botones13pieVentana;
Ventana13 () (
super ( “Example of I / S”);
content = new TextArea ();
pieVentana = new Botones13 ();
add ( “North”, content);
add ( “South”, pieVentana);
pack ();
show ();
)
public boolean handleEvent (Event e) (
if ((e.Id == Event.WINDOW_DESTROY) | | (e.Id == 2003))
dispose ();
if (e.Id == 2001) CargarArchivo (pieVentana.ToString ());
if (e.Id == 2002) GrabarArchivo (pieVentana.ToString ());
return super.HandleEvent (e);
)
CargarArchivo void (String name) (
FileInputStream fptr;
DataInputStream f;
String line = null;
contenido.SetText (“”);
try (
fptr = new FileInputStream (name);
f = new DataInputStream (fptr);
do (
f.Readline line = ();
if (line! = null) contenido.AppendText (line + “”);
) While (line! = Null);
fptr.Close ();
)
catch (FileNotFoundException e) (
new Error13 ( “The file does not exist!”);
)
catch (Exception e) (
new Error13 ( “Error reading file!”);
)
)
GrabarArchivo void (String name) (
FileOutputStream fptr;
DataOutputStream f;
try (
fptr = new FileOutputStream (name);
f = new DataOutputStream (fptr);
f.WriteBytes (contenido.GetText ());
fptr.Close ();
)
catch (Exception e) (
new Error13 ( “Error recording file!”);
)
)
)
/ *
/ / ——– This is for the buttons and the file name
* /
Botones13 class extends Panel (
TextField fname;
Button load;
Button save;
Button close;
Botones13 () (
setLayout (new GridLayout (1.4));
fname = new TextField ();
load = new Button ( “Load”);
record = new Button ( “Record”);
close = new Button ( “Close”);
add (new Label ( “File :”));
add (fname);
add (upload);
add (record);
add (close);
)
public boolean handleEvent (Event e) (
if ((e.Id == Event.ACTION_EVENT) & & (e.Target == load))
e.Id = 2001;
if ((e.Id == Event.ACTION_EVENT) & & (e.Target == record))
e.Id = 2002;
if ((e.Id == Event.ACTION_EVENT) & & (e.Target == close))
e.Id = 2003;
return super.HandleEvent (e);
)
public String toString () (
fname.GetText return ();
)
)
/ *
/ / ——- To show error …
* /
Error13 class extends Frame (
Error13 (String error) (
add ( “Center”, new Label (error));
add ( “South”, new Button ( “Ok”));
pack ();
show ();
)
public boolean handleEvent (Event e) (
dispose ();
return super.HandleEvent (e);
)
)

Returning to the AWT

To learn a little more on the graphics library (AWT), we will modify our last program
to use menus.
We will put back all the code (which expanded to use as an applet or local application) marking
the most notable differences:
/ *
/ / —– File: Ejemplo14.Java
* /
import java.Io. *;
import java.Net .*;
import java.Applet .*;
example14 public class extends Applet (
public void init () (
new Ventana14 (true), / / with “true” reporting is applet
)

Public static void main (String args [])


(/ / to use as application
Ventana14 v14 = new Ventana14 (false), / / with “false” reporting is not applet
)
)
/ *
/ / ——– This class is what actually does the work
* /
Ventana14 class extends Frame (
TextArea content;
enApplet boolean / / to indicate whether we call it as an applet
String filename / / to save the open file name
MenuItem mArchivoAbrir / / Here are the menu items
MenuItem mArchivoGrabar / /.
MenuItem mArchivoSalir / /.
MenuItem mEditCortar / /.
MenuItem mEditCopiar / /.
MenuItem mEditPegar / /.
MenuItem mEditTodo / / v
String clipboard / / buffer to cut and paste
boolean published = false, / / here if we change the file indicated
Ventana14 (enApp boolean) (
super ( “Example of I / S”);
enApplet = enApp / / remember if applet or not

MenuArchivo Menu = new Menu ( “& File”);


/ / BELIEVE THE MENUS!
mArchivoAbrir = new MenuItem ( “& Open …”);
mArchivoGrabar = new MenuItem ( “& Record …”);


mArchivoSalir = new MenuItem ( “& Quit”);
menuArchivo.Add (mArchivoAbrir);
menuArchivo.Add (mArchivoGrabar);
menuArchivo.Add (new MenuItem (“-“));
menuArchivo.Add (mArchivoSalir);
MenuEdit Menu = new Menu ( “& Edit”);
mEditCortar = new MenuItem ( “Cu & t”);
mEditCopiar = new MenuItem ( “& Copy”);
mEditPegar = new MenuItem ( “& Paste”);

mEditTodo = new MenuItem ( “& Select All”);
menuEdit.Add (mEditCortar);
menuEdit.Add (mEditCopiar);
menuEdit.Add (mEditPegar);
menuEdit.Add (new MenuItem (“-“));
menuEdit.Add (mEditTodo);
BarMenu MenuBar = new MenuBar ();
barraMenu.Add (menuArchivo);
barraMenu.Add (MenuEdit);
setMenuBar (barMenu);
content = new TextArea (); / / just put a text window
add ( “Center”, content);
pack ();
show ();

Clipboard = new String (“”);


/ / empty clipboard,

MEditPegar.Disable ()


/ / nothing to hit,
mArchivoGrabar.Disable () / / nothing to record
)
public boolean handleEvent (Event e) (
if ((e.Id == Event.WINDOW_DESTROY) | | (mArchivoSalir == e.Target))
(

If (edited) System.Out.Println ( “Ask!”)


/ / should confirm
/ / If you want
go unrecorded!
if (enApplet) dispose ();
else System.Exit (0);
)

If (e.Target == mArchivoAbrir) CargarArchivo ()


/ / selection process here
if (e.Target == mArchivoGrabar) GrabarArchivo (), / / menu
if (e.Target == mEditCortar) (
contenido.GetSelectedText clipboard = ();
mEditPegar.Enable ();
contenido.ReplaceText ( “”, contenido.GetSelectionStart (), contenido.GetSelectionEnd ());
edited = true;
)
if (e.Target == mEditCopiar) (
contenido.GetSelectedText clipboard = ();
mEditPegar.Enable ();
)

if (e.Target == mEditPegar) (
contenido.ReplaceText ( “”, contenido.GetSelectionStart (), contenido.GetSelectionEnd ());
contenido.InsertText (clipboard, contenido.GetSelectionStart ());
edited = true;
)
if (e.Target == mEditTodo) contenido.SelectAll ();
if ((e.Id == Event.KEY_PRESS) & & (e.Target == void)) edited = true;
mArchivoGrabar.Enable (edited);

return super.HandleEvent (e);
)
CargarArchivo void () (
FileInputStream fptr;
DataInputStream f;
String line = null;
if (edited) System.Out.Println ( “Ask!”);
FileDialog fd = new FileDialog (this, “Open …”, FileDialog.LOAD),
/ / choose file

Fd.Show ();


/ / Using standard dialog
system!

Filename = fd.GetFile ();


try (
fptr = new FileInputStream (filename);
f = new DataInputStream (fptr);

Contenido.SetText (“”);


/ / empty the window before loading new file
do (
f.Readline line = ();
if (line! = null) contenido.AppendText (line + “”);
) While (line! = Null);
fptr.Close ();
edited = false, / / new file -> no published
)
catch (FileNotFoundException e) (
new Error14 ( “The file does not exist!”);
)
catch (Exception e) (
new Error14 ( “Error reading file!”);
)
catch (NullPointerException e) (
;
)
)
GrabarArchivo void () (
FileOutputStream fptr;
DataOutputStream f;

FileDialog fd = new FileDialog (this, “Save …”, FileDialog.SAVE);


/ / save file

Fd.SetFile (filename);


/ / using standard system dialog!
fd.Show ();
filename = fd.GetFile ();

try (
fptr = new FileOutputStream (filename);
f = new DataOutputStream (fptr);
f.WriteBytes (contenido.GetText ());
fptr.Close ();

Edited = false;


/ / newly recorded -> unedited
)

catch (Exception e) (
new Error14 ( “Error recording file!”);
)
catch (NullPointerException e) (
;
)
)
)
/ *
/ / ——- To show error …
* /
Error14 class extends Frame (
Error14 (String error) (
add ( “Center”, new Label (error));
add ( “South”, new Button ( “Ok”));
pack ();
show ();
)
public boolean handleEvent (Event e) (
dispose ();
return super.HandleEvent (e);
)
)

Menu for Java

Well, the first thing we see are the menus.
The menu bar consists of menus, which in turn are composed of items (which may also
be menus). For example the menu bar to declare with:
BarMenu MenuBar = new MenuBar ();
and we add the File and Edit menus (which we created) to:
barraMenu.Add (menuArchivo);
barraMenu.Add (MenuEdit);
Finally, reported as the window menu (Frame):
setMenuBar (barMenu);
Each of the menus the previously declared:
MenuArchivo Menu = new Menu ( “& File”);

MenuEdit Menu = new Menu ( “& Edit”);
Note that the “&” not displayed, but the letter that follows is underlined: File, Edit. This allows
that can select the menu with the mouse as well with the alt-or meta-, followed by the pound
underlined.
In turn, the add method is also present in the class and allows us to add menu items:
mArchivoAbrir = new MenuItem ( “& Open …”);
mArchivoGrabar = new MenuItem ( “& Record …”);
mArchivoSalir = new MenuItem ( “& Quit”);
menuArchivo.Add (mArchivoAbrir);
menuArchivo.Add (mArchivoGrabar);
menuArchivo.Add (new MenuItem (“-“));
menuArchivo.Add (mArchivoSalir);
These items have declared it as the global class for use later in the events. Note also
than
menuArchivo.Add (new MenuItem (“-“));
does not add a menu item but a line of separation, and we need not create it as a permanent object.
If we look at the architecture school, both descended from MenuBar and MenuItem MenuComponent.
In turn, descends from MenuItem menu, so it implements the same methods and what we
we said before: a menu item can be a different menu, and so many sub-levels of menus
as we like.
Finally, in our event handler simply need to verify if an item was chosen by testing
if the event occurred on the specific item:
if ((e.Id == Event.WINDOW_DESTROY) | | (e.Target == mArchivoSalir))
(
if (edited) System.Out.Println ( “Ask!”);
if (enApplet) dispose ();
else System.Exit (0);
)
if (e.Target == mArchivoAbrir) CargarArchivo ();
…………….
if (e.Target == mEditTodo) contenido.SelectAll ();

In short I do is:
· If you chose File / Exit (or alt-F4 or whatever) I leave the program
· If you chose File / Open, call the CargarArchivo
· If you chose File / Record, call the method GrabarArchivo
· If you chose Edit / Cut Copy the selected text to my clipboard and delete the selection
· If you chose Edit / Copy only copies the selected text to my clipboard
· If you chose Edit / Paste delete the selected text and insert my clipboard
· If you chose Edit / Seleccionar_todo framework throughout the text
In all cases, changing the text suggests putting content edited to true, the same if
I press a key on the editing area:
if ((e.Id == Event.KEY_PRESS) & & (e.Target == void)) edited = true;
A couple of clarifications:
· GetSelectionStart () and getSelectionEnd () mark the limits of the selected text (if any,
are equal).
· GetSelectedText () returns the selected text in the TextArea.
· ReplaceText () replaces a part (or all) of the TextArea for a String.
· InsertText () inserts a string to a specific place of TextArea.
· SelectAll () selects all text in the TextArea.
· MenuItem.Enable () enables a menu item. I use this to enable Edit / Paste only after
cut or copy something to my clipboard.
• In the case of item File / Record, you enable or not depending on the variable edited, using
enable the other way: MenuItem.Enable (boolean).

Dialogues

In Java we have the Dialog class to create dialogues, ie temporary windows for entries
user, which depends on another (in fact the Dialog class inherits from the Window class).
While we can create dialogue as using the Frame class, supposed to use dialogue to be more
easy. The reality is that for now can not be used much more than the standard dialogs (and the only thing worth
the penalty is FileDialog) because current implementations of Java have a problem: in some
platforms the program that opens the dialogue continues, instead of waiting to close the dialog and return the
answer.
So we have only an indication where there should be a confirmation dialog:
if (edited) System.Out.Println ( “Ask!”);
In this place we should call such a dialogue that allows us to decide yes or no:
if (edited) (
but = new ConfirmarDlg (this, “file modified!”);
if (sino.GetResponse () == true) ….;
else ….;
)
or something. The same we can do it in other ways, for example using threads and communications
between processes, but much more complicated for this time of year. Hopefully a little later, though
Sun promised that in version 1.1 and will be corrected (out end of ’96).
For now, consider a simple case with the class FileDialog:
FileDialog fd = new FileDialog (this, “Open …”, FileDialog.LOAD);
fd.Show ();
filename = fd.GetFile ();
First declare a variable of type FileDialog, and create the new instance. As parameters
pass father (this, ie “this window”), the title of the dialog window, and a constant LOAD or SAVE
(they are static, so called directly by the name of the class and not necessarily a
instance) that indicates whether the dialog is to load or save a file (obviously the task itself to load or
Save the file to make us tenenmos, dialogue only expected to choose a name).
The show () method displays the dialogue and hoped that selected and click OK or Cancel. This is where
others fail because it is dialogue program continues without waiting.
Finally, the dialog is closed but not removed the object (possibly being implemented using the
method hide (), which hides it from view but not lost until you exit the method that created it, where act
Garbage collector memory). This means that although we can not see it call the method
getFile () on this object, which returns the selected file name (or null if pressed
Cancel).

DibuJava

Besides the standard components (buttons, lists, etc..), There is a component for drawing “free” we
allows to implement any other type of control: the Canvas class. Typically used to draw, and
corresponds to a rectangular area within a window.
The class itself does virtually nothing, the programmer must define a subclass of Canvas to which the
AWT sends all mouse and keyboard events. Redefining methodsGotFocus, LostFocus,
keyDown, keyUp, MouseEnter, mouseExited, mouseMove, mouseDrag, mouseDown
and mouseUp, the
programmer can make what is occurring within that rectangle. We will make use of a Canvas to
applet which will generate a rectangular area within which, by clicking with the mouse and
moving without releasing the button, draw a rectangle dynamically.
This allows us to see how to use a Canvas to draw, capture events, and more. The shakes a little edge
redraw, but we’ll see how to avoid that.

Canvas in action

We first put, as is becoming usual, the code of the applet (Remember that you must
uploaded from an html page to view! Here we do not create any window and we can not see it as
standalone application) and then try to explain how it works.
import java.Net .*;
import java.Applet.Applet;
example15 public class extends Applet (
public void init () (
Label label = new Label ( “chop and drag the mouse!”);
miCanvas zonaDib = new miCanvas ();
zonaDib.Resize (new Dimension (200,200));
add ( “North”, label);
add ( “Center”, zonaDib);
resize (300.250);
)
)
miCanvas class extends Canvas (
Rectangle rectActual;
public boolean mouseDown (Event e, int x, int y) (
rectActual = new Rectangle (x, y, 0, 0);
repaint ();
return false;
)
public boolean mouseDrag (Event e, int x, int y) (
rectActual.Resize (x-rectActual.X and-rectActual.Y);
repaint ();
return false;
)
public boolean mouseUp (Event e, int x, int y) (
rectActual.Resize (x-rectActual.X and-rectActual.Y);
repaint ();
return false;
)
public void paint (Graphics g) (
Dimension d = size ();
g.SetColor (Color.Red);
g.DrawRect (0, 0, d.Width-1, d.Height-1);
g.SetColor (Color.Blue);
if (rectActual! = null) (
Rectangle box = cortarRect (rectActual, d);
g.DrawRect (box.X, box.Y, box.Width-1, box.Height-1);
)
)
CortarRect Rectangle (Rectangle miRect, Dimension areaDib) (
int x = miRect.X;
int y = miRect.Y;
int width = miRect.Width;
int height = miRect.Height;
if (width <0) (
width =-width;
x = x – width + 1;
if (x <0) (
width + = x;
x = 0;
)
)
if (high <0) (
height =-height;
y = y – height + 1;
if (y <0) (
height + = y;
y = 0;
)
)
if ((x + width)> areaDib.Width) (
areaDib.Width width = – x;
)
if ((y + height)> areaDib.Height) (
high = areaDib.Height – y;
)
return new Rectangle (x, y, width, height);
)
)
The applet-container
First we have considered that an Applet is a Panel, and therefore also a Container, and
that instead of creating a separate window simply added two components: a Label and a Canvas.
zonaDib.Resize (new Dimension (200,200));

add ( “North”, label);
add ( “Center”, zonaDib);
resize (300.250);
The method rezise on miCanvas class allows us to resize it to desired size.
Similarly, we use resize the applet to give sufficient size. If you change the size of the
appletviewer window will see a strange behavior in terms of positioning
the rectangle on the poster, but for simplicity this will do.
Our Canvas as
As we will not take any special action to create the canvas, we have not defined the constructor (it
use the default constructor of the Canvas class).
We have simply redefined some methods for influencing the press, drag and drop the mouse, for
redraw the drawing area (canvas) and to cut the rectangle drawn if we go with the mouse away
the space occupied by the canvas.
The global rectActual of the Rectangle class will contain the coordinates of the rectangle are
drawing. The Paint method is called automatically whenever it is necessary to redraw the component, or if
explicitly call the method repaint ():
public void paint (Graphics g) (
Dimension d = size ();
g.SetColor (Color.Red);
g.DrawRect (0, 0, d.Width-1, d.Height-1);
g.SetColor (Color.Blue);
if (rectActual! = null) (
Rectangle box = cortarRect (rectActual, d);
g.DrawRect (box.X, box.Y, box.Width-1, box.Height-1);
)
)
First we assign to a variable d canvas size using the size () method, then choose
a color (red) to draw a border and draw a rectangle the size of the component:
Dimension d = size ();
g.SetColor (Color.Red);
g.DrawRect (0, 0, d.Width-1, d.Height-1);
Two attributes of the class Dimension, width and height, have been charged with the size of the canvas and are the
used to size the rectangle.
Then, if you’re drawing a rectangle (rectActual! = Null) simply cut out (in case
we dragged the mouse out of the canvas) and we draw.
The method that will cut the limits of the canvas, cortarRect assigns the coordinates of the four variables
rectangle (which is passed as parameter miRect to call it):
int x = miRect.X;
int y = miRect.Y;
int width = miRect.Width;
int height = miRect.Height;
If the width (or height) is negative, it just changes sign and takes as its coordinate x (y) of origin
the other vertex of the rectangle, which corresponds to x who spent less wide and more than one (recall that the
origin of coordinates start at zero and not one). If this vertex is outside the canvas (x <0), puts it in
zero and minus the cut-width (note that W + = x, as x is negative, is actually a difference).
if (width <0) (
width =-width;
x = x – width + 1;
if (x <0) (
width + = x;
x = 0;
)
)
If we leave the drawing area on the right (or below), simply cut out the width (high)
excess so as to reach to the edge of the drawing area (which we also passed to the method as
parameter):
if ((x + width)> areaDib.Width) (
areaDib.Width width = – x;
)
We have only to see the methods that respond to mouse.
When you press the mouse within the canvas, we begin creating a new rectangle width and
High zero beginning at the point where we pressed the mouse, and redraw the canvas:
public boolean mouseDown (Event e, int x, int y) (
rectActual = new Rectangle (x, y, 0, 0);
repaint ();
return false;
)
By moving the mouse, resize the rectangle with width x less the origin of drawing (and higher and less
drawing origin), and repaint:
public boolean mouseDrag (Event e, int x, int y) (
rectActual.Resize (x-rectActual.X and-rectActual.Y);
repaint ();
return false;
)
Finally, when you release the mouse, resize as before and re-drawn
public boolean mouseUp (Event e, int x, int y) (
rectActual.Resize (x-rectActual.X and-rectActual.Y);
repaint ();
return false;
)
Since there is no action to save the rectangle drawn by creating a new one (reassigning
rectActual a new rectangle), the former lost.
DibuJava II
We will restore our example15 a bit so it does not erase the boxes when we want
draw a new one. Learn something about the Vector class, part of the package java.Util.
Vectors in action
The vectors allow us to make arrangements for any type of object, and refer to any individual
vector element, but to use them (because the vector contains java generic objects)
we have to tell what kind of object is through a “cast”. Let’s see how our classes are
Ejemplo16 (ex example15) and miCanvas:
import java.Net .*;
import java.Net .*;
import java.Applet.Applet;
public classEjemplo16 extends Applet (
public void init () (
……………. (this part does not change )…………….
)
)
miCanvas class extends Canvas (
Vector v = new Vector (); / / initialize with indeterminate size
/ / Java is responsible for managing the necessary moria me!

public boolean mouseDown (Event e, int x, int y) (
v.AddElement (new Rectangle (x, y, 0, 0)) / / New Item!

repaint ();
return false;
)
public boolean mouseDrag (Event e, int x, int y) (
Rectangle r = (Rectangle) v.LastElement (); / / cast: v are rectangles
r.Resize (x – rx, y – r) / / (r created
only for clarity)
repaint ();
return false;
)
public boolean mouseUp (Event e, int x, int y) (
Rectangle r = (Rectangle) v.LastElement (); / / cast: v are rectangles
r.Resize (x – rx, y – r) / / (r created only for clarity)

repaint ();
return false;
)
public void paint (Graphics g) (
int i; / / counter of rectangles
Dimension d = size ();
g.SetColor (Color.Red);
g.DrawRect (0, 0, d.Width-1, d.Height-1);
g.SetColor (Color.Blue);
if (v.Size ()> 0)


for (i = 0, i <v.Size (); i + +) (
CortarRect Rectangle box = ((Rectangle) v.ElementAt (i), d);
g.DrawRect (box.X, box.Y, box.Width-1, box.Height-1);
)
)
…………………… (remainder unchanged) ……………………
)
I suggest you use an HTML book enough to see the whole applet, such as:
<HTML>
<HEAD>
<TITLE> Example 16 – Example canvas </ TITLE>
</ HEAD>
<BODY>
<applet code=”Ejemplo16.Class” width=300 height=250>
</ applet>
</ BODY>
</ HTML>
Here are the steps now. First we create a variable (global to the class), called v, class Vector,
and without giving a definite size:
Vector v = new Vector ();
When creating a new rectangle add an element (object) to the vector using the method add:
v.AddElement (new Rectangle (x, y, 0, 0));
To access an attribute of an object is not sufficient vector directly use the vector as:
v.LastElement (). X
(LastElement () allows us to access the last item added to the vector). It is necessary to clarify
explicitly that the component is a rectangle, since the vector can contain objects
any kind. For this we use the casting:
(Rectangle)
v.LastElement (). X
In our original code replaced with:
(Rectangle) v.LastElement (). Resize (x – (Rectangle) v.LastElement (). X, ……
But it is clearer if we use a local variable in class Rectangle, we assign the same object as
just added to the vector, and we use instead:
Rectangle r = (Rectangle) v.LastElement ();
r. resize (x – r. x, y – r. y);
Finally, in the paint () method can not assign the item to not know that there (originally the
vector was empty!). So an if we can verify that the vector size is greater than zero (it has
elements), and allows us to draw for one by one.

You can access all the elements one by one, using the method elementAt (x), which gives us the xésimo
vector element. The method size () gives the number of elements (the first is the number 0, and
well):
if (v.Size ()> 0)
for (i = 0, i <v.Size (); i + +) (
CortarRect Rectangle box = ((Rectangle) v.ElementAt (i), d);
g.DrawRect (box.X, box.Y, box.Width-1, box.Height-1);
)
Here we did not create intermediate variables and it is equally clear (I think …).
Flicker annoying!

Well, the problem left is the annoying “flicker” that is how the picture flickers when
move the mouse. This is because each time you call to paint (), the background is erased and redrawn throughout the
canvas.
Basically, the workaround is to rewrite the update () method, which is what erases the background before
call paint () to not delete it, another method (which is what we use) is to draw not on the screen
but on a “buffer” graphic, then copy that buffer onto the screen (which is much more efficient than
draw on it).
For that we create a couple of items:
miCanvas class extends Canvas (
Vector v = new Vector ();
Image imgBuff;
Graphics grafBuff;
.
……………………….
Image is an abstract class, the mother of all classes that represent graphical images. Graphics is
too abstract and allows us to obtain a context in which to draw.
What we do is modify our paint () method to simply call update (), and
redefine the update () method:
public void paint (Graphics g) (
update (g);
)

The update () method is one that does all the work and is basically like our old paint () with some
aggregates:
public void update (Graphics g) (
int i;
Dimension d = size ();
if (grafBuff == null) (
imgBuff = createImage (d.Width, d.Height);

grafBuff = imgBuff.GetGraphics ();
)
grafBuff.SetColor (getBackground ());
grafBuff.FillRect (0, 0, d.Width, d.Height);
grafBuff. setColor (Color.Red);
grafBuff. drawRect (0, 0, d.Width-1, d.Height-1);
grafBuff. setColor (Color.Blue);

if (v.Size ()> 0) for (i = 0, i <v.Size (); i + +) (
CortarRect Rectangle box = ((Rectangle) v.ElementAt (i), d);
grafBuff. drawRect (box.X, box.Y, box.Width-1, box.Height-1);
)
g.DrawImage (imgBuff, 0, 0, this);
)

We indicated in bold aggregates.
If you are not yet established (grafBuff == null), we create our buffer drawing. To create the buffer graph
(Graphics class), first create an image that in this case has the same dimensions as the
canvas (d.Width x d.Height) and then assign grafBuff the context of the image using the method
getGraphics (). CreateImage (…) Imagine that create a “virtual screen” and getGraphics () gives
a way to access that screen as if it were real.
Using this context, we chose the same color as the background color of the applet (getBackground ()) and
draw a filled rectangle (fillRect (…)), thereby erasing anything that had been drawn.
In italics we have indicated the changes to our previous method. Simply, instead of using the
context of the screen (the parameter g method), we draw on our context-virtual screen.
Finally, to visualize our design, we use the drawImage method of the context of the
actual screen (g), which copies our context imgBuff at coordinates (0,0) on the screen. It is
also referred to the canvas (… This): the fourth parameter to drawImage is an object of class
ImageObserver, an interface that helps the object is drawn within which receive messages
Asynchronous that tell you how the image is being built, and when it is ready.
Animate!

While it may be a bit more complex to understand than a direct drawing on the screen, notice that the
implementation is straightforward and brings no problem. This same approach can be used to create
animations.
In this example, to handle the execution frame by frame animation, we use Threads. No
worry about it, we’ll see soon. Only bear in mind that your applet must implement the
runnable class, and the thread is responsible for implementing the run () method that simply calls repaint () and expected
100 milliseconds between frame and frame.
The calculation and design work makes update (). They were kept for study, is not complicated and
also uses double buffering (like the example above).
import java.Net .*;
import java.Net .*;
import java.Applet.Applet;
Ejemplo18 public class extends Applet implements Runnable (
Thread animator;
Image imgBuff;
Graphics grafBuff;
double ang = 0.0;
public void init () (
resize (new Dimension (200,200));
)
public void start () (
if (animator == null) animator = new Thread (this);
animador.Start ();
)

public void run () (
while (Thread.CurrentThread () == animator) (
repaint ();
try (
Thread.Sleep (100);
)
catch (Exception e) (
break;
)
)
)
public void update (Graphics g) (
int i;
int dx, dy;
Dimension d = size ();
if (grafBuff == null) (
imgBuff = createImage (d.Width, d.Height);
grafBuff = imgBuff.GetGraphics ();
)
grafBuff.SetColor (getBackground ());
grafBuff.FillRect (0, 0, d.Width, d.Height);
grafBuff.SetColor (Color.Red);
grafBuff.DrawRect (0, 0, d.Width-1, d.Height-1);
grafBuff.SetColor (Color.Blue);
dx = (int) (50 * Math.Abs (Math.Cos (ang)));
dy = (int) (50 * Math.Abs (Math.Sin (ang)));
ang = ang + 0.1;
if (ang> 2 * Math.PI) ang = 0.0;
grafBuff.DrawRect (100-dx 100-dy, 2 * dx, 2 * dy);
g.DrawImage (imgBuff, 0, 0, this);
)
)
Java threads
The former class use, the last example, a concept that we now turn our attention:
threads.
The literal translation of thread or yarn thread is, and is also used to refer to the thread of discourse. The
concept of threads in the environments and operating systems is a bit complex to explain but easy to
understand: regardless of the system chosen, it is conceivable that a thread is like the place of
program execution.
In most of the programs we have seen, we used a single thread, ie a program
execution begins and follows a unique way: as a monologue.
Java’s multithreading. This means something like that is capable of dialogue, and even more: it can
running many threads in parallel, as if we tried multiple and simultaneous conversation.
Do not confuse this with multithreading capability to run multiple programs at once. This is a
possibility, but also the same program can use multiple threads ( “execution paths”?)
simultaneously.
This, of course, depends critically on the ability of the operating system to support
multithreading, and therefore can not run Java (at least in full) on systems that do not
bear.
The use of threads allows us, for example, running several programs simultaneously interact
them, or alternatively, a program, such as updating the screen, simultaneously perform a
series of calculations without having to wait for the user.
A simple way is to imagine that we see a group of chips that can execute,
each, a single thread, and we assign programs (or parts of programs) to each of them.
We can also imagine that these chips share a common memory and common resources,
what will emerge a number of important issues to consider when using threads.
The basic steps
There are three things to consider when using threads in a program:
• The class that we want to assign a thread must implement the Runnable interface.
· We create a variable (instance) of type Thread that will allow us to access and manage the
thread. In the applets in the start () method simply create the thread (and possibly the
will run)
· And finally we have to create a run () method that is executing program code
itself.
The Runnable interface, simply defined as:
public interface java.Lang.Runnable
(
/ / Methods
public abstract void run ();
)
assures the compiler that our class (which uses the thread to run) has run () method.
Let’s see a couple of examples, first a standalone application and then an applet.
Meeting friends
The following example (Ejemplo19.Java) uses threads to simultaneously activate three objects of the same
class, sharing processor resources scrambled to write to the screen.
Ejemplo19 class (
public static void main (String argv [])

throws InterruptedException (
Thread Juan = new Thread (new Friend ( “John”));
Luis thread = new Thread (new Friend ( “Luis”));
Nora thread = new Thread (new Friend ( “Nora”));
Juan.Start ();
Luis.Start ();
Nora.Start ();
Juan.Join ();
Luis.Join ();
Nora.Join ();
)
)
Friend class implements Runnable (
String message;
public Friend (String name) (
message = “Hi,” + name + “and this is my message”;
)
public void run () (
for (int i = 1, i <6; i + +) (
String msg = message + i;
System.Out.Println (msg);
)
)
)
As usual, compile it and run with Ejemplo19.Java javac java Ejemplo19.
In a preemptive operating system, the output is more or less like this:
Hi, I’m John and this is my message 1
Hi, I’m John and this is my message 2
Hi, Luis and this is my message 1
Hi, Luis and this is my message 2
Hi, I’m Nora and this is my message 1
Hi, I’m Nora and this is my message 2
Hi, I’m Nora and this is my message 3
Hi, I’m John and this is my message 3
……….. Etc.
Which means that an operating system is preemptive? Typical cases are Unix or Windows 95: each task
uses a portion of processor time, and then releases so they can run other tasks (other
threads). So you mix the output messages. If the operating system is not preemptive, processor
not released until it ends with the current thread, and therefore the output would be:
Hi, I’m John and this is my message 1
Hi, I’m John and this is my message 2
Hi, I’m John and this is my message 3
Hi, I’m John and this is my message 4
Hi, I’m John and this is my message 5

Hi, Luis and this is my message 1
Hi, Luis and this is my message 2
……….. Etc.
If you are using a non-preemptive operating system must explicitly indicate to the processor
when you can run (make way) to another task, for it simply modifies the run () method:
public void run () (
for (int i = 1, i <6; i + +) (
String msg = message + i;
System.Out.Println (msg);
Thread.Yield ();
)

)
In this example, both preemptive and non preemptive systems the output is:
Hi, I’m John and this is my message 1
Hi, Luis and this is my message 1
Hi, I’m Nora and this is my message 1
Hi, I’m John and this is my message 2
Hi, Luis and this is my message 2
Hi, I’m Nora and this is my message 2
Hi, I’m John and this is my message 3
Hi, Luis and this is my message 3
……….. Etc.
This is because we are printing then freeing the processor to switch to another thread (if there
one waiting). Note the difference with the first case, without using yield () for preemptive systems: the
processor divides his work as a (seemingly) unpredictable, so the order of the messages will not be
the same on any machine or operating system.
We saw this work, but we understand it would be good! We are therefore going step by step.
Creating Threads
Thread is a basic class in Java that implements the Runnable interface and offers a few methods
by default. The important thing to keep in mind that to use Threads, we must create them as instances and
them to “walk”:
Thread Juan = new Thread (new Friend ( “John”));
…………..
Juan.Start ();
…………..
Juan.Join ();
A thread has four possible states:
created:
created using new (), but has not started yet.
active:
running, either because they started with start () or was “awakened” to resume ().
sleep:
its implementation has been temporarily suspended by wait (), sleep () or suspend ().
dead has definitely stopped, either because the program was completed or by the call tostop ().
In this example we have created a thread simultaneously assigning an object that is used (new
Friend ( “John”)), then we set, by calling start () method. This method is responsible for
initialize the thread and finally call the method run () were implemented.

Thus, it is as if the run () method of each object is executed in parallel,
concurrently. The way to handle this depends on the operating system.
The join () method is called at the end makes the program wait until the main thread is
“dead” (finished execution). This method can trigger the exception InterruptedException, so
We have taken into account at the top of the class.
In our example, each instance simply to Friend (…) we believe we have linked to a thread and
place to walk. Are all parallel until they die a natural death, and also the main program
ends.
When we use Thread.Yield () (which really should be Thread.CurrentThread (). Yield (), but still some
common use of Java developers have simplified), simply allows the current thread
dedicated processor to another (if there is any desire to utilize their services).
Friend Class () is very simple and with what we’ve seen so far do not think we need to explain
nothing more.
And applets …?

We may also use these concepts in applets. Here is an example to finish today’s class, very
similar to above, where three counters have (in a preemptive system) simultaneously. Remember
create an HTML page with the tag
<applet code=”Ejemplo20.Class” width=300 height=100> </ applet>
to see it in action with the appletviewer or your favorite browser (I guess that already supports Java!
😉
The program is fiendishly simple, and can see it in action if they wish via the Internet loading
page:
http://www.Amarillas.Com/rock/java/Ejemplo20.Htm
/ / Example of applet that uses multithreading
import java.Net .*;
import java.Applet .*;
public class extends Applet (Ejemplo20
TextField tfa, tfb, tfc;
public void init () (
setLayout (new GridLayout (3.2));
tfa = new TextField ( “0”);
tfb = new TextField ( “0”);
tfc = new TextField ( “0”);
add (new Label ( “Counter A”));
add (TFA);
add (new Label ( “Counter B”));
add (tfb);
add (new Label ( “Counter B”));
add (tfc);
)
public void start () (
Thread a = new Thread (new Counter (tfa));
Thread B = new Thread (new Counter (tfb));
Thread C = new Thread (new Counter (TFC));
A.Start ();
B.Start ();
C.Start ();
)
)
class Counter implements Runnable (
TextField text;
String s;
public Counter (txtf TextField) (
text = txtf;
)
public void run () (
for (int i = 0, i <1000; i + +) (
texto.SetText (s.ValueOf (i));
)
)
)

The hare and the tortoise (and cheetah)

Java has a mechanism of priorities for threads, so you can allocate more CPU time
a thread to another. Typically is assigned a priority of 1 to 10 (10 is the highest priority) by
setPriority, as in the example below:
public class Ejemplo21 (
Animal static turtle;
Animal static hare;
Animal cheetah static;
public static void main (String argv [])
throws InterruptedException (
turtle = new Animal (2, “T”);
hare = new Animal (3, “L”);
cheetah = new Animal (4, “G”);
tortuga.Start ();
liebre.Start ();
guepardo.Start ();
tortuga.Join ();
liebre.Join ();
guepardo.Join ();
)
)
class Animal extends Thread (
String name;
public Animal (int priority, String name) (
this.Name = name;
setPriority (priority);
)
public void run () (
for (int x = 0, x <30; x + +) (
System.Out.Println (name);
yield ();
)
System.Out.Println ( “comes” + name);
)
)
The output of this program, implemented with java Ejemplo21 is for example:
C: javacurso> java Ejemplo21
GGGGGGGGGGGGGGGGGGGGGGGGGGGGGG
Reaches G
L T LLLLLLLLLLLLLLLLLLLLLLLLLLLLL
Llega L
TTTTTTTTTTTTTTTTTTTTTTTTTTTTT
Reaches T

As shown, despite having started before the turtle, almost all the CPU time the first use
Cheetah, then the hare (although anything is for the poor turtle, as seen in the marked T) and
finally to the Tortoise. It all runs and all systems are equal output, because it depends
processor load and the particular Java implementation.
This program simply creates three animals (Animal class), allocates to each thread and executes them. This
example is done based on one of the book “Java Programming” by Macary and Nicolas.
Synchronize your watches
A basic problem of multithreading is when several programs (or, for that matter, several threads) access
the same data: how do we know if one of them does not change while you are using another?.
An example, where we assume multiple threads use the variable valorImportante:
if (valorImportante> 0) (
….. Something is processed here ……..
valorImportante = valorImportante – 1;
.
…. Continues …………………
)
How do we ensure that valorImportante did not change between the if and the highlighted line? Other threads can
have changed in the meantime. It can happen that two threads are running the same
portion of code, and to lose one of the decreases. Imagine something like this:
(before) valorImportante = 10
(thread 1) reads valorImportante = 10
(thread 2) reads valorImportante = 10
(thread 1) 10 -1 = 9
(thread 2) 10 -1 = 9
(thread 2) allocates 9 valorImportante
(thread 1) assigns 9 to valorImportante
(after) valorImportante = 9
As we see, despite being deducted twice, we lost one of subtraction. Though we may use instead -=
subtraction is the same, because the code also resolves several steps (several operations
atom).
To avoid this, Java gives us the Synchronized keyword, blocking access to a variable at all
minus the threads that you are using.
Let’s see a specific case, there are two counters that use the same adder for addition of one
an amount to. Supposedly between the two should carry adder (a) to 20000.
/ / File Ejemplo22.Java, Ejemplo22.Java compile with javac, run with java Ejemplo22
public class Ejemplo22 (
public static void main (String argv []) (
Adder a = new Adder (); / / a single adder
Counter c1 = new Counter (A), / / two threads that use it …
C2 = new Contador Contador (A); / / … To add
C1.Start ();
C2.Start ();
try (
C1.Join ();
C2.Join ();
)
catch (Exception e) (
System.Out.Println (e);
)
)
)
class Counter extends Thread (
Adder s;
Accountant (Adder adder) (
s = adder; / / I assign an adder to use
)
public void run () (
s.Sumar () / / execute the sum
)
)
class Adder (
int a = 0;
public void add () (
for (int i = 0, i <10000; i + +) (
if ((i% 5000) == 0) (/ / “%” gives the rest of the division:
System.Out.Println (a); / / print every 5000
)
a + = 1;
)
System.Out.Println (a); / / print the final
)
)
Running this gives us something like (each run is different, depending on how they “collide” the
threads and CPU load):
C: javacurso> java Ejemplo22
0
87
8926
10434
14159
17855
This is precisely what we explained the principle: sometimes the two threads try to execute a + = 1
simultaneously, so that some increases are lost.
We can solve this by modifying the run () method:
public void run () (
synchronized (s) (
s.Sumar ();
)
)

With this, only one of the two threads are allowed to implement s.Sumar () at a time and avoids the problem. By
course, the other thread is waiting, so better not use it very long methods because
the program may slow or even to crash.
The output now is:
C: javacurso> java Ejemplo22
0 <
5000 <first thread
10000 <
10000 (
15000 (second thread
20000 (
So we (and more correctly) declared to be synchronized to the method add ():
public synchronized void add () (………….
This is better because the class that calls the add () does not need to know it has to synchronize the object before
calling the method, and if other objects (in other threads) call, no need to worry.
More synchronization
Another way to synchronize threads to access methods, is to make them agree
each other, waiting one to another place any given task. For this, use the methods wait () and
notify (). When a thread calls wait () on a method of a given object is held until another
thread call notify () method in some of the same object.
For example, assume four employees who are with your boss and waves, but only after
that it’s health first.
public class Ejemplo23 (
public static void main (String argv []) (
Greeting hello = new Greeting ();
Staff pablo = new Staff (hello, “Paul”, false);
Staff luis = new Staff (hello, “Luis”, false);
Andrea staff = new Staff (hello, “Andrea”, false);
Staff pedro = new Staff (hello, “Peter”, false);
Staff head = new Staff (hello, “BOSS”, true);
pablo.Start ();
luis.Start ();
andrea.Start ();
pedro.Start ();
jefe.Start ();
try (
pablo.Join ();
luis.Join ();
andrea.Join ();
pedro.Join ();
jefe.Join ();
)
catch (Exception e) (
System.Out.Println (e);
)
)
)
class Greeting (
synchronized void esperarJefe (String employee) (
try (
wait ();
System.Out.Println (employee + “> Good morning boss!”);
)
catch (Exception e) (
System.Out.Println (e.ToString ());
)
)
saludoJefe synchronized void () (
System.Out.Println ( “HEAD> Buenos dias!”);
notifyAll ();
)
)
class Staff extends Thread (
String name;
Greeting greeting;
esJefe boolean;
Staff (Salutation s, String n, boolean j) (
name = n;
greeting = s;
esJefe = j;
)
public void run () (
System.Out.Println (“(“+ name + “comes)”);
if (esJefe)
saludo.SaludoJefe ();
else
saludo.EsperarJefe (name);
)
)
I use notifyAll () instead of notify (), because in the second case only notify the first thread (the first
taken to arrive) and not others, which would remain in the wait ().
As seen in the output, even though employees are able to greet not do so until
does not reach the boss:
C: javacurso> java Ejemplo23
(Paul arrives)
(Luis arrives)
(Andrea arrives)
(Pedro arrives)
(CHIEF arrives)
CHIEF> Buenos dias!
Luis> Good morning boss!
Peter> Good morning boss!
Andrea> Good morning boss!
Paul> Good morning boss!
Here, I cheated: Sometimes, the boss comes in and greets before any of the employees, so that employee
waits indefinitely. Try to modify the classes to greet the boss until it
current employees are all …

Chapter XV – Solving the problem
proposed
In simple way, changing only the kind staff, we can solve the problem that the chief
arrive before an employee:
class Staff extends Thread (
…………….
static int arrived = 0;
.
……………
public void run () (
System.Out.Println (“(“+ name + “comes)”);
if (esJefe) (
while (arrived <4) (
System.Out.Println ( “(Esperando. ..)”);
)
saludo.SaludoJefe ();
)
else (
synchronized (this) (
arrived + +;
)

saludo.EsperarJefe (name);
)
)
)
Prepare a static variable (class) for all employees who have passed through here, the
increment just before executing saludo.EsperarJefe (synchronizing the thread on the increase for
to spare them the problems we saw in the chapter).
In the case of the head, just hopes that the counter reaches 4. We may change this a little,
from the number of employees as a parameter to be more flexible.
Even we can use two different manufacturers (one for employees and one for the boss, and in this
latter case the number of employees spent waiting). I leave an example for study.
public class Ejemplo23 (
public static void main (String argv []) (
Greeting hello = new Greeting ();
Staff head = new Staff (hello, “CHIEF”, 3);
Staff pablo = new Staff (hello, “Paul”);
Staff luis = new Staff (hello, “Luis”);
Andrea staff = new Staff (hello, “Andrea”);
jefe.Start ();
pablo.Start ();
luis.Start ();
andrea.Start ();
try (
pablo.Join ();
luis.Join ();
andrea.Join ();
jefe.Join ();
)
catch (Exception e) (
System.Out.Println (e);
)
)
)
class Greeting (
synchronized void esperarJefe (String employee) (
try (
wait ();
System.Out.Println (employee + “> Good morning boss!”);
)
catch (Exception e) (
System.Out.Println (e.ToString ());
)
)
saludoJefe synchronized void () (
System.Out.Println ( “HEAD> Buenos dias!”);
notifyAll ();
)
)
class Staff extends Thread (
String name;
Greeting greeting;
esJefe boolean;
static int arrived = 0;
int numEmp;
Staff (Salutation s, String n) (
esJefe = false;
name = n;
greeting = s;
)
Staff (Salutation s, String n, int x) (
esJefe = true;
name = n;
greeting = s;
numEmp = x;
)
public void run () (
System.Out.Println (“(“+ name + “comes)”);
if (esJefe) (
while (arrived <numEmp) (System.Out.Println ( “(Esperando. ..)”);)
saludo.SaludoJefe ();
)
else (
synchronized (this) (arrived + +;)
saludo.EsperarJefe (name);
)
)
)

Multimedia!

Java allows you to load and display GIF or JPEG image and audio AU (only in mono, 8 bits,
8000Hz sampling rate).
In the case of sound, an audio file is loaded by a class object AudioClip, by
getAudioClip method (URL, file), runs with the methods play () or loop () and stops with stop ().
Note this! While we assert that an applet can not access the disk of the client machine, if you can read
server files from where it was loaded. Therefore, passing it the URL of the machine from which the loaded
the applet, we can read any type of file over the network.
The safest way to indicate the URL is using the method getDocumentBase (), which gives us the URL
suitable.
For example, I load and play audio with only two lines:
……..
AudioClip sound = getAudioClip (getDocumentBase (), “sonido.Au”);
sonido.Play ();
………
Moreover, a picture can be loaded by a class object image by the method
getImage (URL, file). After the show in a Graphics object for the applet (or the area
drawing) using drawImage (image, x, y, observer). Observer is an object that implements the
ImageObserver interface, applets, to descend from Component (which implements that interface) also
implement it. Typically, the image is displayed in the paint (…) method of the applet:
………….
someMethod (…) (
……….
Image image = getImage (getDocumentBase (), “image.Gif”);
……….
)
………..
public void paint (Graphics g) (
g.DrawImage (image, xoffset, yOffset, this); / / “this” represents the applet
)
……………
The problem with images is to make sure it was loaded before displaying it. For that is used
MediaTracker (also should serve to audio files, but this version is not yet
implemented).
By addImage (image, group) is added an image to the list of MediaTracker and there are methods
to expect to be charged (as waitForAll () or waitfor (group)) to verify it is loaded
correctly (as checkAll (), check (group), isErrorAny () …), and so on.
The following applet uses these concepts to upload an image and an audio file and show:
/ / Ejemplo24.Java
import java.Net .*;
import java.Applet .*;
public class extends Applet (Ejemplo24
MediaTracker supervisor;
String Archmage, archAudio;
Image image;
AudioClip audio;
Label title;
Panel painting;
public void init () (
supervisor = new MediaTracker (this);
Archmage = “javacero.Gif”;
archAudio = “tada.Au”;
/ / Load image
image = getImage (getDocumentBase (), Archmage);
supervisor.AddImage (image, 0);
try (
supervisor.WaitForID (0) / / I hope
load
)
catch (Exception e) (
System.Out.Println ( “Error loading image!”);
)
showStatus ( “Image loaded”);
/ / Load sound
audio = getAudioClip (getDocumentBase (), archAudio);
/ / Weapon layout
setLayout (new BorderLayout ());
title = new Label (Archmage);
setFont (new Font ( “Helvetica”, Font.BOLD, 18));
add ( “South”, title);
)
public void start () (
repaint ();
audio.Play ();
)
public void paint (Graphics g) (
if (supervisor.IsErrorAny ()) (
g.SetColor (Color.Black);
g.FillRect (0, 0, size (). Width, size (). Height);
return;
)
g.DrawImage (image, 0, 0, this);
)
)
To display it, as always, we create an HTML:
<HTML>
<HEAD>
<TITLE> Example 24 – Example Multimedia </ TITLE>
</ HEAD>
<BODY>
code=”Ejemplo24.Class” <applet width=150 height=200>
</ applet>
</ BODY>
</ HTML>
Parameterize a applet
Let’s take this example, modified a little to indicate from which files to HTML
load, using parameters. Our HTML modified are:
<HTML>
<HEAD>
<TITLE> Example 24 – Multimedia </ TITLE>
</ HEAD>
<BODY>
code=”Ejemplo24.Class” <applet width=150 height=200>
<param name=”imagen” value=”javacero.Gif”>
<param name=”sonido” value=”tada.Au”>
</ applet>
</ BODY>
</ HTML>
To read the parameters from the applet, use the method getParameter (nombreParámetro), so
we modify our applet simply by changing a few lines:
Archmage = getParameter ( “image”);
archAudio = getParameter ( “sound”);
Voila! They can try to load this applet http://www.Amarillas.Com/rock/java/Ejemplo24.Htm.
This way we can pass any value as a parameter for an applet, making it more flexible.
And that’s it for today!
With this we have seen a large part of what is Java. We did not dwell too much on each point,
but we have working examples to illustrate each item.
However, we have made an important and very strong Java, which is the communication between
applications and, especially, the use of sockets programming and client / server applications.
Strolling through the Network
It’s easy to access files on the network using Java. The java.Net package provides several classes and
interfaces for this purpose.
First, the URL class allows us to define a resource in the network in several ways, including:
URL url1 = new URL ( “http://www.Rockar.Com.Ar/index.Html“);
URL url2 = new URL ( “http”, “www.Rockar.Com.Ar”, “sbits.Htm”);
Moreover, we can establish a connection to a URL given by openConnection:
URLConnection connection = url.OpenConnection ();
Once connection is achieved, we can read and write data using streams (data streams), as in
For common file management (see Chapter X). A DataInputStream allows us to read data
arrive through the network, and a DataOutputStream allows us to send data to the host.
For example:
DataInputStream data = new DataInputStream (corrienteEntrada);
In our case, the influx of data comes from the connection to the URL. The method
getInputStream () URLConnection object that gives us power:
DataInputStream data = new DataInputStream (conex.GetInputStream ())
Thus we can write a small program, for example, read an HTML page from a
arbitrary Internet address. The program then be compiled by javac Ejemplo25.Java, runs
<url> Ejemplo25 with java, for example: java Ejemplo25 http://www.Rockar.Com.Ar/index.Html.
import java.Io. *;
import java.Net .*;
public class Ejemplo25 (
public static void main (String argv []) (
String s;
try (
URL url = new URL (argv [0]);
URLConnection url.OpenConnection conex = ();
System.Out.Println ( “Loading” + argv [0]);
DataInputStream data = new DataInputStream (conex.GetInputStream ());
do (
s = datos.ReadLine ();
if (s! = null) System.Out.Println (s);
) While (s! = Null);
)
catch (ArrayIndexOutOfBoundsException e) (
System.Out.Println ( “Syntax: java Ejemplo25 <url>”);
)
catch (UnknownHostException e) (
System.Out.Println ( “The host does not exist or is not responding”);
)
catch (Exception e) (
e.PrintStackTrace ();
)
)
)
This program displays the HTML as text on the screen, but you could burn them to a file for
save it. Even, we could process it as you receive, identifying tags <A HREF=url>,
store them in a vector, and then connect and download the links that appear on the original to
download a complete site.
Note that this not only serves to establish links to HTML pages. In reality, a URL can
refer also to other protocols such as gopher, ftp, etc., although according to the implementation of Java
may have problems connecting to some types of URLs.
To see what kinds of URL possible I recommend reading the page:
http://www.Ncsa.Uiuc.Edu/demoweb/url-primer.Html
The Sockets
The sockets (sockets, referring to the connection sockets cables) are communication mechanisms between
programs through a TCP / IP. In fact, while establishing a connection via the Internet we are using
sockets: sockets made the interface between the application and the TCP / IP.
These mechanisms may take place within the same machine or across a network. They are used as
Client-server: When a client and server establish a connection, make it through a socket. Java
provides for this ServerSocket and Socket classes.
The sockets have an associated port (port). In general, Internet connections can establish a
particular port (for example, http://www.Rockar.Com.Ar:
80 / index.Html the port is 80). This almost never
specified because there are already defined default port for different protocols: 20 for ftp-data, 21 for
ftp, 79 for finger, etc.. Some servers may define other ports and even ports can be used
available for special connections.
Precisely, one of the ways to create a URL class object to specify also the port:
Url3 URL = new URL ( “http”, “www.Rockar.Com.Ar”, 80, “sbits.Htm”);
To establish a connection through a socket, we must schedule at the server side and on the other
customers.
On the server, create an object of class ServerSocket and then we expect a customer (class
Socket) using the method accept ():
ServerSocket connection = new ServerSocket (5000); / / 5000 is the port in this case
Socket client = conexion.Accept (), / / I hope the customer
From the customer standpoint, we need a Socket we tell the server address and
port number to use:
Socket connection = new Socket (address, 5000);
Once the connection is established, we can exchange data using streams as in the example above.
As the URLConnection class, the Socket class has methods getInputStream and getOutputStream
respectively give us an InputStream and an OutputStream through which data transfer.
An attentive server
We will create a Ejemplo26a.Java server (which can run in a window) that will serve a client
the same machine (we’ll run into another window). To put it simply, the server only sends you a
this message to the client and terminate the connection. The server will then be available for another client.
It is important to note that for the socket to function, TCP / IP services must be active (though both
programs to run on the same machine). Windows users be sure that there is a connection
TCP / IP active, either to a local network or the Internet.
The server will run “forever”, so to stop it press Control-C.
/ / Server
import java.Io. *;
import java.Net .*;
public class Ejemplo26a (
public static void main (String argv []) (
ServerSocket server;
Socket client;
numCliente int = 0;
try (
server = new ServerSocket (5000);
do (
numCliente + +;
servidor.Accept customer = ();
System.Out.Println ( “Customer Comes” + numCliente);
PrintStream ps = new PrintStream (cliente.GetOutputStream ());
ps.Println ( “You are my client” + numCliente);
cliente.Close ();
) While (true);
)
catch (Exception e) (
e.PrintStackTrace ();
)
)
)
We use a PrintStream to send the data to the client, as it is simple to use to send String s.
The method as PrintStream.Println System.Out.Println handles data, you simply tell the
stream through which send them to create it (in this case, the client OutputStream that we obtain through
cliente.GetOutputStream ()).
The satisfied customer
Now we create the client class, Ejemplo26b.Java. The customer simply sets the connection, reads
through a DataInputStream (using the method readLine ()) what the server sends, shows and
short.
/ / Client:
import java.Io. *;
import java.Net .*;

public class Ejemplo26b (
public static void main (String argv []) (
InetAddress address;
Socket server;
numCliente int = 0;
try (
address = InetAddress.GetLocalHost (), / / local address
server = new Socket (address, 5000);
DataInputStream data =
new DataInputStream (servidor.GetInputStream ());
System.Out.Println (datos.ReadLine ());
servidor.Close ();
)
catch (Exception e) (
e.PrintStackTrace ();
)
)
)
To test this, make sure that TCP / IP services are active, run in a window java Ejemplo26a
and run several times in another Ejemplo26b java. The outputs will be more or less like this:
Window server:

C: javacurso> java Ejemplo26a
Customer 1 arrives
Customer 2 arrives
Comes customer 3
(—– Cut with control-C —–)
Client window:

C: javacurso> java Ejemplo26b
You are my client 1
C: javacurso> java Ejemplo26b
You are my client 2
C: javacurso> java Ejemplo26b
You are my client 3
Here we close the server (—– —–)
C: javacurso> java Ejemplo26b
java.Net.SocketException: connect
at java.Net.PlainSocketImpl.DoConnect (PlainSocketImpl.Java: 223)
at java.Net.PlainSocketImpl.ConnectToAddress (PlainSocketImpl.Java: 128)
at java.Net.PlainSocketImpl.Connect (PlainSocketImpl.Java: 115)
at java.Net.Socket. <init> (Socket.Java: 125)
at java.Net.Socket. <init> (Socket.Java: 101)
at Ejemplo26b.Main (Ejemplo26b.Java: 12)
That’s all for now. The example was as simple as possible, but by the same method the server and
customers can exchange data by writing in both directions. Even the server can run
on one machine and other clients in addition, although in this case we used standalone applications are
applets can use.
For example, a server application can run continuously in an Internet server (eg for
Search Data in a database) and customers in different machines, Java applets posioblemente,
can connect to and query.