Sei sulla pagina 1di 443

 1 hora  Figura 1.2.

o Convertirse en un Programador  Taller: Instalación del JDK


 Elegir un idioma  Documentación oficial
 Decir la computadora qué hacer  Resumen
 Figura 1.1.  Q&A
 Cómo funcionan los programas  Quiz
 ¿Cómo Programas No trabajo  Preguntas
 : Java Próxima parada  Respuestas
 Actividades

Hour 1 1 hora

Becoming a Programmer Convertirse en un


Programador
Computer programming is insanely difficult. Programación de computadoras es
increíblemente difícil. It requires a four-year degree in computer science, thousands of
dollars in computer hardware and software, a keen analytical intellect, the patience of Job,
and a strong liking for caffeinated drinks. Se requiere un grado de cuatro años en ciencias
de la computación, miles de dólares en hardware y software, un intelecto agudo análisis, la
paciencia de Job, y un gusto fuerte de las bebidas con cafeína. If you're a programming
novice, this is probably what you've heard about computer programming. Si usted es un
principiante de programación, esto es probablemente lo que has oído hablar de la
programación de computadoras. Aside from the part about caffeine, all of the rumors are
greatly exaggerated. Además de la parte de la cafeína, todos los rumores son muy
exageradas.

Programming is a lot easier than most people think. La programación es mucho más fácil
que la mayoría de la gente piensa. There are several reasons why you might believe
otherwise: Hay varias razones por las que puede pensar lo contrario:
 Computer programmers have been telling people for years that programming is hard. Los
programadores de computadoras han estado diciendo a la gente durante años que la
programación es difícil. This belief makes it easier for us to find high-paying jobs (or so I've
heard) and gives us more leeway to goof off during business hours. Esta creencia hace que
sea más fácil para nosotros encontrar empleos bien remunerados (o eso he oído) y nos da
más margen para perder el tiempo durante el horario comercial.
 Computer programming manuals are often written in a language that only a Scrabble
player could appreciate. manuales de equipo de programación se escriben a menudo en
un idioma que sólo un jugador de Scrabble podía apreciar. Strange acronyms like OOP,
RAD, COM, and MUMPS are used frequently along with newly invented jargon like
instantiation, bytecode, and makefile. siglas extrañas como programación orientada a
objetos, RAD, COM, y la parotiditis se utilizan con frecuencia junto con la jerga de nueva
invención, como la creación de instancias, código de bytes, y makefile.
 Many computer programming languages have been available only with software packages
costing $200 or more, which is a lot of cabbage. Muchos lenguajes de programación han
estado disponibles sólo con paquetes de software que cuesta $ 200 o más, que es un
montón de repollo.
Because of the growth of the Internet and other factors, this is a great time to learn
programming. Debido al crecimiento de Internet y de otros factores, este es un buen
momento para aprender a programar. Useful programming tools are being made available
at low cost (or no cost), often as downloads from World Wide Web sites. Herramientas
útiles de programación se están haciendo disponibles a bajo costo (o sin costo alguno), a
menudo como descargas en la World Wide Web. The goal of this book is to teach
programming to the person who has never tried to program before or the person who tried
programming but hated it with an intense passion. El objetivo de este libro es enseñar
programación a la persona que nunca ha tratado de programa de antes o la persona que trató
de programación, pero odiaba con una intensa pasión. The English language will be used as
much as possible instead of jargon and obscure acronyms, and all new programming terms
will be thoroughly explained as they are introduced. El idioma Inglés se utiliza tanto como
sea posible en lugar de la jerga y siglas oscuras, y todos los términos de la nueva
programación será explicado a fondo a medida que se introducen.

If I've succeeded, you will finish Teach Yourself Java 1.1 Programming in 24 Hours with
enough programming skill to be a danger to yourself and others. Si he tenido éxito, usted
terminará Aprendiendo Java 1.1 de programación de 24 horas de programación con
habilidad suficiente como para ser un peligro para sí mismo ya otros. You'll be able to write
programs, dive into other programming books with more confidence, and learn
programming languages more easily. Usted será capaz de escribir programas, sumergirse en
los libros de programación con más confianza, y aprender los lenguajes de programación
con más facilidad. You also will have developed skills with Java, the most exciting
programming language to be introduced in a decade. También se han desarrollado las
habilidades con Java, el lenguaje de programación más emocionante que se introducirá en
una década.

The first hour of this book provides some introductory material about programming and
gives you instructions on how to set up your computer so you can write Java programs. La
primera hora de este libro proporciona un material introductorio acerca de la programación
y le da instrucciones sobre cómo configurar su ordenador para poder escribir programas
Java. The following topics will be covered: Los siguientes temas serán cubiertos:
 Choosing which programming language to learn first Elegir qué lenguaje de programación
para conocer de primera
 What Java is ¿Qué es Java
 Using programs to boss your computer around Uso de programas para el jefe de su equipo
en torno a
 How programs work ¿Cómo los programas de trabajo
 How program errors called bugs are fixed ¿Qué errores programa llamado errores se
corrigen
 Acquiring the free Java Developer's Kit La adquisición de la libre circulación de Java
Developer's Kit
 Installing the Kit Instalación del kit
 Getting ready to write programs Prepararse para escribir programas

Choosing a Language Elegir un idioma

As you might have surmised at this point, computer programming is not as hard as it's
cracked up to be. A medida que podría haber supuesto en este punto, la programación de
computadoras no es tan difícil como la pintan. If you're comfortable enough with a
computer to create a nice-looking resume, balance a checkbook with software such as Intuit
Quicken, or create your own home page on the Web, you can write programs. Si usted es lo
suficientemente cómodo con una computadora para crear una hoja de vida bonita, el
balance de un talonario de cheques con software como Intuit Quicken, o crear su propia
página en la Web, usted puede escribir programas.
The key to learning how to program is to start with the right language. La clave para
aprender a programar es empezar con el lenguaje adecuado. The programming language
that you choose to use often depends on the tasks you want the computer to accomplish. El
lenguaje de programación que usted elige utilizar a menudo depende de las tareas que desea
que el equipo para llevar a cabo. Each language has things that it is well-suited for and
things that are difficult, or perhaps impossible, to do with the language. Cada idioma tiene
cosas que se adapta bien y cosas que son difíciles, o tal vez imposible, que ver con el
idioma. For example, many people use some form of the BASIC language when they are
learning how to program because BASIC is good for learning how to write programs. Por
ejemplo, muchas personas usan alguna forma del lenguaje BASIC cuando están
aprendiendo a programar porque BASIC es buena para aprender a escribir programas.

The BASIC language was invented in the '60s to be easy for students and beginners to learn
(the B in BASIC stands for Beginner's). El lenguaje BASIC fue inventado en los años 60 a
ser fácil para los estudiantes y principiantes para aprender (el B en BASIC es sinónimo de
principiante). The downside to using some form of BASIC is that it's easy to fall into some
sloppy programming habits with the language. La desventaja de usar alguna forma de
BASIC es que es fácil caer en algunos hábitos de programación descuidada con el lenguaje.
Those habits can make it much more difficult to write complex programs and improve them
later on. Los hábitos pueden hacer que sea mucho más difícil escribir programas complejos
y mejorarlas más adelante.

Microsoft Visual Basic combines the ease of BASIC with some powerful features to aid in
the design of Windows software. Microsoft Visual Basic combina la facilidad de BASIC
con algunas características de gran alcance para ayudar en el diseño de software de
Windows. (VBScript, which is short for Visual Basic Script, offers the simplicity of BASIC
for small programs that run in conjunction with World Wide Web pages.) Visual Basic has
been used to write thousands of sophisticated programs for commercial, business, and
personal use. (VBScript, que es la abreviatura de Visual Basic Script, ofrece la simplicidad
de BASIC para pequeños programas que se ejecutan en colaboración con la World Wide
Web pages.) Visual Basic se ha utilizado para escribir miles de programas sofisticados para
la actividad comercial, y uso personal. However, Visual Basic programs can be slower than
Windows programs written in other languages such as Borland C++. Sin embargo, los
programas de Visual Basic puede ser más lento que los programas de Windows escrito en
otros idiomas como el Borland C + +. This difference is especially noticeable in programs
that use a lot of graphics--games, screen savers, and the like. Esta diferencia es
especialmente notable en los programas que utilizan una gran cantidad de gráficos - juegos,
protectores de pantalla, etc. Because of that, game programmers and other multimedia
developers don't use Visual Basic to create graphical programs such as Doom. Por eso, los
programadores y desarrolladores de juegos multimedia no utilizan Visual Basic para crear
programas gráficos como Doom.

This book uses the Java programming language. Este libro utiliza el lenguaje de
programación Java. Though Java is more difficult to learn than a language such as Visual
Basic, it is a good starting place for several reasons. Aunque Java es más difícil de aprender
que un lenguaje como Visual Basic, es un buen punto de partida por varias razones. One of
the biggest advantages of learning Java is that you can use it on the World Wide Web. Una
de las mayores ventajas del aprendizaje de Java es que se puede utilizar en la World Wide
Web. If you're an experienced Web surfer, you have seen numerous Java programs in
action. Si usted es un internauta con experiencia, que ha visto numerosos programas Java
en acción. They can be used to create animated graphics, present text in new ways, play
games, and help in other interactive efforts. Se pueden utilizar para crear gráficos
animados, texto actual de formas nuevas, jugar y ayudar en otras actividades interactivas.

Another important advantage is that Java requires an organized approach in order for
programs to work. Otra ventaja importante es que Java requiere un enfoque organizado para
que los programas de trabajo. The language is very particular about the way that programs
must be written, and it balks if programmers do not follow all of its rules. El lenguaje es
muy particular sobre la forma en que los programas deben ser por escrito, y se resiste si los
programadores no sigue todas sus reglas. When you start writing Java programs, you might
not see the language's choosy behavior as an advantage. Cuando empieza a escribir
programas Java, es posible que no vea el comportamiento selectivo de la lengua como una
ventaja. You'll write a program and will have several errors to fix before the program will
be finished. Usted escribe un programa y tendrá varios errores para corregir antes de que el
programa se terminó. Some of your fixes might not be correct, and they will have to be
redone. Algunos de sus puntos de referencia no puede ser correcta, y que tendrán que ser
hechos de nuevo. If you don't structure a program correctly as you are writing it, other
errors will result. Si no la estructura de un programa correctamente como lo está por
escrito, los errores de otros resultados. In the coming hours, you'll learn about these rules
and the pitfalls to avoid. En las próximas horas, usted aprenderá acerca de estas reglas y las
trampas a evitar. The positive side of this extra effort is that your programs will be more
reliable, useful, and error-free. El lado positivo de este esfuerzo adicional es que los
programas serán más fiables, útiles y libres de errores.
Java was invented by Sun Microsystems developer James Gosling as a better way to create
computer programs. Java fue inventado por Sun Microsystems desarrollador James Gosling
como una mejor manera de crear programas de ordenador. Gosling was unhappy with the
way that the C++ programming language was working on a project he was doing, so he
created a new language that did the job better. Gosling estaba descontento con la forma en
que el C + + lenguaje de programación estaba trabajando en un proyecto que estaba
haciendo, así que creó un nuevo lenguaje que hizo el trabajo mejor. It's a matter of
contentious debate whether Java is superior to other programming languages, of course, but
the amount of attention paid to the language today shows that it has a large number of
adherents. Es un tema de debate polémico si Java es superior a otros lenguajes de
programación, por supuesto, pero la cantidad de atención prestada a la lengua de hoy
muestra que tiene un gran número de seguidores. Book publishers obviously dig it--more
than 89 books have been published about the language since its introduction. Los editores
de libros, obviamente, cavar - más de 89 libros han sido publicados sobre el lenguaje desde
su introducción. (This is my second book about Java. Teach Yourself SunSoft Java
WorkShop in 21 Days was the first, and I will write more of them until prohibited from
doing so by municipal, state, or federal law.) Regardless of whether Java is the best
language, it definitely is a great language to learn today. (Este es mi segundo libro sobre
Java. Teach Yourself SunSoft Java WorkShop en 21 días fue la primera, y voy a escribir
más de ellos hasta prohibido hacerlo por el municipal, estatal o federal.)
Independientemente de que Java es el mejor lenguaje, que sin duda es un gran lenguaje para
aprender hoy. There are numerous resources for Java programmers on the Web, Java job
openings are increasing, and the language has become a major part of the Internet's future.
Existen numerosos recursos para los programadores de Java en la Web, las aberturas de
Java el desempleo está aumentando, y la lengua se ha convertido en una parte importante
del futuro de Internet. You'll get a chance to try out Java during Hour 2, "Writing Your
First Program." Usted tendrá la oportunidad de probar durante horas de Java 2,
"Escribiendo tu primer programa."
Learning Java or any other programming language makes it much easier to learn other
languages. Aprender Java o cualquier otro lenguaje de programación hace que sea mucho
más fácil aprender otros idiomas. Many languages are similar to each other, so you won't be
starting from scratch when you dive into a new one. Muchas lenguas son similares entre sí,
por lo que no va a empezar desde cero cuando te sumerjas en una nueva. For instance,
many C++ programmers find it fairly easy to learn Java because Java borrows a lot of its
structure and ideas from C++. Por ejemplo, C + + muchos programadores les resulta
bastante fácil de aprender Java, porque Java toma mucho de su estructura y las ideas de C +
+. Many programmers are comfortable using several different languages and learn new
ones as needed. Muchos programadores se sienten cómodos utilizando varios idiomas y
aprender otros nuevos cuando sea necesario.
C++ has been mentioned several times in this hour, and you might be tripping over the term
wondering what it means and, more importantly, how it's pronounced. C + + ha sido
mencionado varias veces en esta hora, y es posible que se tropiece con el término
preguntando lo que significa y, más importante aún, cómo se pronuncian. C++ is
pronounced C-plus-plus, and it's a programming language that was developed by Bjarne
Stroustrop and others at Bell Laboratories. C + + se pronuncia C-plus-plus, y es un lenguaje
de programación que fue desarrollado por Bjarne Stroustrop y otros en los Laboratorios
Bell. C++ is an enhancement of the C programming language, hence the plus-plus part of
the name. C + + es una mejora del lenguaje de programación C, por lo tanto, la parte más-
además del nombre. Why not just C+, then? ¿Por qué no C +, entonces? The plus-plus part
is a computer programming joke you'll understand later on. La parte más-plus es una broma
de programación de computadoras que lo entenderás más tarde.

Telling the Computer What to Do Decirle a la computadora qué hacer

A computer program, also called software, is a way to tell a computer what to do. Un
programa de computadora, también llamado software, es una manera de decirle a un
ordenador qué hacer. Everything that the computer does, from booting up to shutting down,
is done by a program. Todo lo que el equipo hace, desde el arranque hasta el cierre, se
realiza por un programa. Windows 95 is a program. Windows 95 es un programa. Ms. Pac-
Man is a program. Ms. Pac-Man es un programa. The command used in MS-DOS to
display file names also is a program. El comando dir utiliza en MS-DOS para mostrar los
nombres de archivo también es un programa. Even the Michaelangelo virus is a program.
Aunque el virus es un programa de Miguel Ángel.
If you're a science fiction fan, you're probably familiar with the concept of household
robots. Si eres un fan de la ciencia ficción, probablemente estás familiarizado con el
concepto de los robots domésticos. If not, you might be familiar with the concept of
henpecked spouses. Si no, usted puede estar familiarizado con el concepto de los cónyuges
calzonazos. In either case, someone gives very specific instructions telling the robot or
spouse what to do, something like the following: Dear Theobald, En cualquier caso, alguien
le da instrucciones muy específicas diciendo que el robot o el cónyuge que hacer, algo
como lo siguiente: Estimado Theobald,
Please take care of these errands for me while I'm out lobbying members of Congress:Por
favor, tenga cuidado de estos recados para mí mientras yo estoy fuera de cabildeo de los
miembros del Congreso:
Item 1: Vacuum the living room. Tema 1: El vacío de la sala de estar.
Item 2: Go to the store. Tema 2: Ir a la tienda.
Item 3: Pick up butter, lozenges, and as many SnackWells Devil's Food Cakes as you can
carry. Tema 3: Levantar la mantequilla, pastillas, y como muchos alimentos Diablo
SnackWells de Pasteles como se puede llevar.
Item 4: Return home. Tema 4: Regreso a casa.
Love, Amor,

Snookie Lumps Snookie Terrones

If you tell a loved one or artificially intelligent robot what to do, there's a certain amount of
leeway in how your requests are fulfilled.Si le dices a un ser querido o artificialmente robot
inteligente que hacer, hay un cierto margen de maniobra en la forma en que se cumplan sus
peticiones. If lozenges aren't available, cough medicine might be brought to you instead. Si
las pastillas no se dispone de medicamentos para la tos puede ser presentada a usted en su
lugar. Also, the trip to the store can be accomplished through a variety of routes. Además,
el viaje a la tienda se puede lograr a través de una variedad de rutas. Computers don't do
leeway. Las computadoras no hacen margen de maniobra. They follow instructions
literally. Siguen las instrucciones de la letra. The programs that you write will be followed
precisely, one statement at a time. Los programas que lo que escriba será estrictamente
respetada, una declaración a la vez.
The following is one of the simplest examples of a computer program, written in BASIC.
El siguiente es uno de los ejemplos más simples de un programa de computadora, escrito en
BASIC. Take a look at it, but don't worry yet about what each line is supposed to mean:
Tome una mirada en ella, pero no se preocupe todavía acerca de lo que cada línea se supone
que significa:
1 PRINT "Shall we play a game?" 1 PRINT "Vamos a jugar un
juego?"
2 INPUT A$ 2 ENTRADA A $

Translated into English, this program is equivalent to giving a computer the following to-do
list: Dear personal computer, Traducido al Inglés, este programa es equivalente a dar una
computadora a la siguiente lista de tareas pendientes: Querido ordenador personal,
Item 1: Display the question, "Shall we play a game?" Tema 1: Muestra la pregunta:
"¿Vamos a jugar un juego?"
Item 2: Give the user a chance to answer the question. Tema 2: Dar al usuario la
oportunidad de responder a la pregunta.
Love, Amor,

Snookie Lumps Snookie Terrones

Each of the lines in the computer program is a statement. Cada una de las líneas en el
programa de computadora es una declaración. A computer handles each statement in a
program in a specific order, in the same way that a cook follows a recipe or Theobald the
robot followed the orders of Snookie Lumps when he vacuumed and shopped at the market.
Un ordenador controla cada declaración en un programa en un orden específico, de la
misma manera que un cocinero sigue una receta o Teobaldo el robot siguió las órdenes de
Snookie bultos cuando la aspiradora y compras en el mercado. In BASIC, the line numbers
are used to put the statements in the correct order. En BASIC, los números de línea se
utilizan para poner las declaraciones en el orden correcto. Other languages, such as Java, do
not use line numbers, favoring different ways to tell the computer how to run a program.
Otros lenguajes, como Java, no utilice los números de línea, favoreciendo formas de decirle
a la computadora cómo ejecutar un programa.

Figure 1.1 shows the sample BASIC program running on the Bywater BASIC interpreter,
which is available for free in several shareware file repositories on the World Wide Web
and can run on any DOS or UNIX platform. Figura 1.1 muestra el programa de ejemplo
Basic que se ejecuta en el intérprete de Bywater BASIC, el cual está disponible de forma
gratuita en varios repositorios de shareware de archivos en el World Wide Web y puede
ejecutarse en cualquier plataforma de DOS o UNIX. Bywater BASIC is among many free
BASIC interpreters that can be found on the Internet for Microsoft Windows, Apple
Macintosh, UNIX, and Linux systems. Bywater BASIC es libre entre muchos intérpretes de
BASIC que se pueden encontrar en Internet para Microsoft Windows, Apple Macintosh,
UNIX y Linux.

Figura 1.1. An example of a BASIC program running on the Bywater BASIC shell and
interpreter developed by Ted A. Campbell. Un ejemplo de un programa BASIC que se
ejecutan en el BASIC cáscara Bywater y el intérprete desarrollado por Ted A. Campbell.

The quote "Shall we play a game?" La frase "Vamos a jugar un juego?" is from the 1983
movie WarGames, in which a young computer programmer (Matthew Broderick) saves
mankind after nearly causing global thermonuclear war. es de la película Juegos de guerra
de 1983, en el que un joven programador de computadoras (Matthew Broderick) salva la
humanidad después de casi causa la guerra termonuclear global. You'll learn how to do that
in the next book of this series, Teach Yourself to Create International Incidents with Java in
24 Hours. Usted aprenderá cómo hacer que en el próximo libro de esta serie, Aprendiendo a
Crear incidentes internacionales con Java en 24 horas.

Because of the way programs operate, it's hard to blame the computer when something goes
wrong while your program runs.Debido a la forma operan los programas, es difícil culpar a
la computadora cuando algo sale mal, mientras que su programa se ejecuta. After all, the
computer was just doing exactly what you told it to do. Después de todo, el equipo estaba
haciendo exactamente lo que le dijo que hiciera. Unless your hardware is on the fritz or a
pesky virus is attacking your system, both rare occurrences, the blame for program errors
lies with the programmer. A menos que su hardware está en el fritz o un virus molestos está
atacando el sistema, tanto en casos raros, la culpa de los errores del programa recae en el
programador. That's the bad news. Esa es la mala noticia. The good news is that you can't
do any permanent harm to your computer with the programming errors you make. La buena
noticia es que usted no puede hacer ningún daño permanente a su equipo con los errores de
programación que hacen. No one was harmed during the making of this book, and no
computers will be injured as you learn how to program with Java. Nadie resultó herido
durante la realización de este libro, y ningún equipo se lesiona como a aprender a
programar con Java.

How Programs Work Cómo funcionan los programas

Most computer programs are written in the same way that you write a letter--by typing each
statement into a word processor. La mayoría de los programas de ordenador se escriben de
la misma manera que escriba una carta - escribiendo cada frase en un procesador de textos.
Some programming tools come with their own word processor, and others can be used with
any text-editing software. Algunas herramientas de programación vienen con su propio
procesador de textos, y otros se pueden utilizar con cualquier software de edición de texto.
You can use the Java Developer's Kit, which you will learn about later in this hour, with
any of your favorite editors. Usted puede utilizar el Kit de Desarrollo Java, que usted
aprenderá más adelante en esta hora, con cualquiera de sus editores favoritos.
When you have finished writing a computer program, you save the file just as you would
save any other document to disk. Cuando haya terminado de escribir un programa de
ordenador, guardar el archivo como lo haría cualquier otro documento que guarde en el
disco. Computer programs often have their own file extension to indicate what type of file
they are. Los programas de ordenador a menudo tienen su propia extensión de archivo para
indicar qué tipo de archivo que son. Java programs have the extension ; an example of a
Java program file name is . los programas de Java tienen la extensión;. java un ejemplo
de un archivo de nombre del programa Java es Calculator.java.

If you use a fancy word processing program that has features such as boldfaced text,
different font sizes, and other stylistic touches, do not use those features while writing a
computer program. Si utiliza un programa de procesamiento de textos de fantasía que tiene
características tales como texto en negrita, diferentes tamaños de fuente y otros toques
estilísticos, no uso esas características al escribir un programa informático. Programs
should be prepared as text files with no special formatting. Los programas deben estar
preparados como archivos de texto sin formato especial. For example, when using
Microsoft Word to write a program, save the file in Text Only mode instead of saving it as
a Word document. Por ejemplo, cuando se utiliza Microsoft Word para escribir un
programa, guarde el archivo en modo de sólo texto en lugar de guardarlo como un
documento de Word. Notepad, a word processor that comes with Windows, saves all files
as unformatted text. Bloc de notas, un procesador de textos que viene con Windows, guarda
todos los archivos como texto sin formato.

To run a program, you need some help. Para ejecutar un programa, usted necesita un poco
de ayuda. The kind of help that's needed depends on the programming language you're
using. El tipo de ayuda que se necesita depende del lenguaje de programación que está
utilizando. Some languages require an interpreter to run their programs. Algunos lenguajes
requieren un intérprete para ejecutar sus programas. The interpreter is a program that
interprets each line of a computer program and tells the computer what to do. El intérprete
es un programa que interpreta cada línea de un programa de ordenador y le dice al
ordenador qué hacer. Most versions of BASIC are interpreted languages. La mayoría de
versiones de BASIC son los lenguajes interpretados. The advantage of interpreted
languages is that they are faster to test. La ventaja de los lenguajes interpretados es que son
más rápidos de la prueba. When you are writing a BASIC program, you can try it out
immediately, spot any errors, fix them, and try again. Cuando usted está escribiendo un
programa BASIC, puede probarlo de inmediato, in situ los posibles errores, corregirlos, y
vuelve a intentarlo. The primary disadvantage is that interpreted languages run more slowly
than other programs. La principal desventaja es que los lenguajes interpretados se ejecutan
más lentamente que otros programas.

Other programming languages require a compiler. Otros lenguajes de programación


requieren un compilador. The compiler takes a computer program and translates it into a
form that the computer can understand. El compilador realiza un programa de ordenador y
lo traduce en una forma que la computadora pueda entender. It also does what it can to
make the program run as efficiently as possible. También hace lo que puede hacer que el
programa ejecute lo más eficientemente posible. The compiled program can be run directly,
without the need for an interpreter. El programa compilado se puede ejecutar directamente,
sin la necesidad de un intérprete. Compiled programs run more quickly than interpreted
programs, but they take more time to test. Los programas compilados correr más rápido que
los programas de interpretación, pero toma más tiempo para probar. You have to write your
program and compile it before trying it out. Tienes que escribir tu programa y compilarlo
antes de probarlo. If you find an error and fix it, you must compile the program again to
verify that the error is gone. Si usted encuentra un error y corregirlo, debe compilar el
programa de nuevo para verificar que el error ha desaparecido.

Java is unusual because it requires a compiler and an interpreter. Java es inusual, ya que
requiere un compilador y un intérprete. You'll learn more about this later as you write Java
programs. Usted aprenderá más sobre esto más adelante a medida que escribe los
programas de Java.

How Programs Dont Work ¿Cómo Programas No trabajo

Many new programmers become discouraged when they start to test their programs.
Muchos nuevos programadores se desaniman cuando empiezan a probar sus programas.
Errors appear everywhere. Los errores aparecen en todas partes. Some of these are syntax
errors, which are identified by the computer as it looks at the program and becomes
confused by what you wrote. Algunos de estos son errores de sintaxis, que son identificados
por el equipo como se ve en el programa y se confunde con lo que escribió. Other errors are
logic errors, which are only noticed by the programmer as the program is being tested, if
they are noticed at all. Otros errores son errores de lógica, que sólo cuenta por el
programador como el programa está siendo probado, si se notan en absoluto. Logic errors
sneak by the computer unnoticed, but they will cause it to do something unintended. Los
errores lógicos colarse por la computadora desapercibida, pero que hará que hacer algo no
deseado.
As you start to write your own programs, expect to encounter errors. Al empezar a escribir
sus propios programas, espero encontrar errores. They're a natural part of the process. Ellos
son una parte natural del proceso. Programming errors are called bugs, a term that dates
back a century or more to describe errors in technical devices. Los errores de programación
se llaman errores, un término que se remonta un siglo o más para describir los errores en los
dispositivos técnicos. The process of fixing errors has its own term also-- debugging. El
proceso de corrección de errores tiene su propio plazo también - depuración. Whether you
want to or not, you'll get a lot of debugging experience as you learn how to write computer
programs. Ya sea que usted quiera o no, tendrás un montón de depuración de la experiencia
a medida que aprende a escribir programas de ordenador.

Next Stop: JavaJava Próxima parada

Before you can start writing Java programs, you need to acquire and set up some kind of
Java programming software. Antes de poder empezar a escribir programas Java, es
necesario adquirir y establecer algún tipo de software de programación Java. Although
several different products are available for the development of Java programs, including
many terrific ones that make programming much easier, the starting place for most new
Java programmers is the Java Developer's Kit. Aunque varios productos diferentes para el
desarrollo de programas en Java, incluyendo muchos estupendo que hacen la programación
mucho más fácil, el lugar de partida para la mayoría de los nuevos programadores de Java
es el Kit de Desarrollo Java. All of the examples in this book use the Kit, and you are
encouraged to forsake all other Java programming tools as you go through the remaining 23
hours of tutelage. Todos los ejemplos en este libro el uso del kit, y se le anima a abandonar
todas las otras herramientas de programación Java a medida que avanza a través de los
restantes 23 horas de tutoría. The material will make more sense to programmers using the
Kit, and using the Kit builds experience that will be beneficial no matter which
development software you use later on. El material tendrá más sentido para los
programadores que utilizan el kit, y utilizando el kit se basa la experiencia que será
beneficiosa, no importa de desarrollo de software que se utiliza más adelante.

The Java Developer's Kit (also referred to as the JDK) is in version 1.1 as of this writing. El
Kit de Desarrollo Java (también conocido como el JDK) es en la versión 1.1 de este escrito.
It is a set of tools that enable you to write and test Java programs. Se trata de un conjunto
de herramientas que le permiten escribir y probar programas en Java. Users of Microsoft
Windows systems may be dismayed to learn that the Kit is not graphical. Los usuarios de
sistemas Microsoft Windows se asombraría al saber que el juego no es gráfica. You run
programs from a command line (the familiar prompt on Windows systems) instead of
using a mouse and a point-and-click environment. Ejecutar programas desde una línea de
comandos (C familiar: \ del sistema> en los sistemas Windows) en lugar de utilizar un
ratón y un-clic en el medio ambiente y punto. Figure 1.2 shows the Kit in use in an MS-
DOS window on a Windows 95 system. Figura 1.2 muestra el kit en uso en una ventana de
MS-DOS en un sistema Windows 95. The Java program is compiled, and then it is run. El
programa Java PlayGame.java se compila, y luego se ejecuta.
Caution: The examples of this book were prepared on a Microsoft Windows system, and some
references in the text are specific to Windows users. Atención: Los ejemplos de este libro fueron
preparados en un sistema Windows de Microsoft, y algunas referencias en el texto son específicos
para los usuarios de Windows. However, all of the material is intended for users of the Java
Developer's Kit on any of the platforms it is currently available for, and all of the tutorials will work
regardless of the system you're using. Sin embargo, todo el material está destinado a usuarios del
Kit de Desarrollo Java en cualquiera de las plataformas que actualmente está disponible para, y
todos los tutoriales de trabajo independientemente del sistema que está utilizando.

At the time of this writing, the Java Developer's Kit is available directly from JavaSoft for
the following systems:
En el momento de escribir esto, el Kit de Desarrollo Java está disponible directamente
desde JavaSoft para los siguientes sistemas:
 Microsoft Windows NT or Windows 95 systems Microsoft Windows NT o Windows 95
sistemas
 SPARC Solaris systems with version 2.3 or later SPARC Solaris sistemas con la versión 2.3 o
posterior
 Intel x86 Solaris systems Intel x86 sistemas Solaris
According to JavaSoft, the Apple Macintosh version of the Kit also should be available by
the time this book is published.
Según JavaSoft, la versión de Apple Macintosh del juego también estará disponible por el
momento de la publicación de este libro.

Figura 1.2. A program being compiled and run with the Java Developer's Kit version 1.1.
Un programa que se compila y se ejecuta con Java Developer Kit versión 1.1.
The Windows 95/NT version of the Kit is provided in two versions. El Windows 95/NT
versión del Kit se presenta en dos versiones. One version is listed as an EXE file, which
means that you can install it by clicking on the file's icon when you download it. Una
versión aparece como un archivo EXE, lo que significa que se puede instalar haciendo clic
en el icono del archivo cuando se descarga. This version is the easiest to set up. Esta
versión es la más fácil de configurar.
The World Wide Web page to download versions of the Kit is the following: La World
Wide página Web para descargar las versiones del juego es la siguiente:
http://www.javasoft.com/products/JDK/1.1/
Although JavaSoft has not announced plans to make version 1.1 of the Kit available for
other systems, other companies can create their own implementations of Java development
tools. A pesar de JavaSoft no ha anunciado planes para hacer la versión 1.1 de las
disponibles para otros sistemas de juego, otras compañías pueden crear sus propias
implementaciones de herramientas de desarrollo Java. Details about these tools will be
listed in the section of the JavaSoft site. Detalles acerca de estas herramientas se mostrarán
en la sección de Preguntas Frecuentes del sitio JavaSoft. Visit the following Web page:
Visite la página Web siguiente:
http://www.javasoft.com/nav/read/faqindex.html

If your system can handle the Java Developer's Kit, download it from the Web and save it
on your system in a newly created directory called or something similar. Si el sistema
puede manejar Java Developer Kit el, puede descargarlo desde la Web y guardarlo en su
sistema en un directorio recién creado llamado jdk11 o algo similar. The file is several
megabytes in size, so you'll have time during the download to make coffee, knit an afghan,
or gnaw your foot off to escape any bear traps it might be caught in. El archivo es de varios
megabytes de tamaño, por lo que tendrá tiempo durante la descarga para hacer el café, tejer
una manta o roer el pie para escapar de las trampas oso podría ser capturado in

Although the JavaSoft Web site always will have the most current edition of Java
Developer's Kit 1.1, you can find the a version of the Kit on the CD-ROM that
accompanies this book. Aunque el sitio Web de JavaSoft siempre tendrá la edición más
reciente del Java Developer Kit 1.1, usted puede encontrar la versión de uno de los kit en el
CD-ROM que acompaña a este libro. Go to the subdirectory of the CD and choose the
folder for your system: , , or . Vaya al subdirectorio de Java del CD y elija la carpeta de
su sistema: Win95NT, SparcSol o IntelSol. This version of the Kit will work with all
sample programs in the book. Esta versión del kit de trabajo con todos los programas de
ejemplo en el libro. Copy this installation file from the CD to your hard drive. Copie este
archivo de instalación desde el CD a su disco duro.

Workshop: Installing the JDK Taller: Instalación del JDK

After the Java Developer's Kit has been downloaded or copied to your hard drive, you can
install the software. Después de el Kit de Desarrollo Java se ha descargado o copiado en el
disco duro, puede instalar el software. The Windows 95 or Windows NT version provides
the easiest means of setting up the Kit because you can start the installation process by
double-clicking on the downloaded file's name or icon. La versión de Windows 95 o
Windows NT proporciona la manera más fácil de crear el kit, ya que puede iniciar el
proceso de instalación haciendo doble clic sobre el nombre del archivo descargado o icono.
This action will install the Kit in a subdirectory of the current directory, so make sure the
file is in the place you want before beginning the installation. Esta acción va a instalar el kit
en un subdirectorio del directorio actual, así que asegúrese de que el archivo está en el lugar
que desee antes de comenzar la instalación. If you put the downloaded file into the
directory, a subdirectory called will be created with the Java Developer's Kit and related
files. Si coloca el archivo descargado en el directorio jdk11, un subdirectorio llamado
java se creará con Java Developer Kit y archivos relacionados.
Other versions of the Kit are packed as an archive file that has been compressed to reduce
its size. Otras versiones del Kit se envasarán en un archivo histórico que se ha comprimido
para reducir su tamaño. These versions will have a file extension such as , , or in the
name. Estas versiones tendrán una extensión de archivo como. Zip,. Z, o. Alquitrán en
el nombre. To use these, you must use decompressing software such as WinZip, , , or
PKZip. Para utilizar estos, debe utilizar software de descompresión como WinZip,
descomprimir gzip, o PKZip.
If you don't own any software that can handle archive files, you can find programs for all
common archive types on the Web. Si usted no tiene ningún programa que pueda manejar
archivos comprimidos, se pueden encontrar programas para todos los tipos de archivo
comunes en la Web. Windows, DOS, and OS/2 users can find some of these programs at
the Coast to Coast Web site ( ). Windows, DOS y OS / 2 los usuarios pueden encontrar
algunos de estos programas en la Costa a Costa de sitio Web (
http://www.coast.net/SimTel/ ). The CNET Web site at offers access to file
collections for all popular operating systems. El sitio web de CNET en
http://www.shareware.com ofrece acceso a las colecciones de archivos para todos los
sistemas operativos más populares. Both of these sites are searchable, so you can type text
such as unzip or untar and find several programs that handle these archive formats. Ambos
de estos sitios se pueden buscar, para que pueda escribir texto como descomprimir o
descomprimir y encontrar varios programas que se ocupan de estos formatos de archivo.
The Kit comes with any special installation instructions that are needed and also includes a
Web page that links directly to help pages on Sun's Java site. El kit viene con las
instrucciones de instalación especiales que se necesitan y también incluye una página web
que vincula directamente a las páginas de ayuda en el sitio de Sun Java. If you need more
help on the installation of the Java Developer's Kit, visit the following page: Si necesita
más ayuda sobre la instalación del Kit de Desarrollo Java, visite la siguiente página:
http://www.javasoft.com/products/JDK/1.1/
Several different programs come with the Kit; the main ones you will use are the following:
Varios programas diferentes vienen con el kit, los principales que va a utilizar son los
siguientes:
 The compiler, , takes a Java program's file and translates it into a form that the computer
knows how to run. El compilador, javac, toma de Java programa de un archivo y lo
traduce en una forma que el equipo sabe cómo ejecutar.
 The interpreter, , runs programs that are created by the compiler. El intérprete, java,
ejecuta programas que son creados por el compilador.
 The Java Web browsing tool, , enables you to run Java programs that are designed to run
on the Web. La herramienta de navegación por Internet Java, appletviewer, que
permite ejecutar programas de Java que están diseñados para funcionar en la Web.
Two of these programs are being used in Figure 1.2. Dos de estos programas se están
utilizando en la Figura 1.2. Look at the command prompts to see and commands being
typed in to compile and run the program. Busque en el directorio C: \> comando
JavaExamples instrucciones para ver los comandos javac y java se escribe para compilar
y ejecutar el programa PlayGame.
Windows systems require two additions to the file in order to use the Java Developer's Kit.
los sistemas de Windows requieren dos adiciones en el archivo Autoexec.bat para poder
usar Java Developer Kit del. You have to tell your system where to find the Kit's programs
and where to find a file called . Usted debe decirle a su sistema en el que encontrar kit de
programas, y en caso de encontrar un archivo llamado classes.zip. If you installed the
kit in the directory, add the following to your statement in the file: Si ha instalado el kit
en el directorio C: \ \ directorio java jdk11, agregar lo siguiente a la instrucción
PATH en el archivo Autoexec.bat:
c:\jdk11\java\bin c: \ jdk11 \ Java \ bin

Also, add a line to after the line: Además, agregar una línea al Autoexec.bat después de
la línea PATH:
SET CLASSPATH=.;c:\jdk11\java\lib\classes.zip JUEGO
CLASSPATH =.; c: \ jdk11 \ Java \ lib \ classes.zip

When you're done, your file should include something like the following: Cuando haya
terminado, su archivo AUTOEXEC.BAT debería incluir algo como lo siguiente:
PATH=c:\windows;c:\windows\command;c:\jdk11\java\bin PATH
= c: \ windows c: \ windows \ command, c: \ jdk11 \ \ bin
java

SET CLASSPATH=.;c:\jdk11\java\lib\classes.zip JUEGO


CLASSPATH =.; c: \ jdk11 \ Java \ lib \ classes.zip

Official Documentation Documentación oficial


In addition to the Developer's Kit, JavaSoft offers documentation for the Java language in
Web page format. Además de Kit del Desarrollador, JavaSoft ofrece la documentación para
el lenguaje Java, en formato de página Web. You don't need this information to use this
book because each topic is discussed fully as it is introduced, but these pages will come in
handy when you write your own programs. Usted no necesita esta información para utilizar
este libro, porque cada tema es un debate completo, ya que se introduce, pero estas páginas
son útiles al escribir sus propios programas.
You can download the entire documentation, but it might be more convenient to browse it
as needed from JavaSoft's Web site. Usted puede descargar toda la documentación, pero
podría ser más conveniente para buscar como sea necesario desde el sitio Web de JavaSoft.
The most up-to-date Java documentation is available from the following address: El más al
día la documentación de Java está disponible en la siguiente dirección:
http://www.javasoft.com/products/JDK/1.1/docs/index.html
Summary Resumen
During this hour, you were introduced to the concept of programming a computer--giving it
a set of instructions that tell it what to do. Durante esta hora, que fueron introducidos en el
concepto de la programación de una computadora - le da un conjunto de instrucciones que
le indican qué hacer. You also downloaded and installed the Java Developer's Kit that will
be used as you write sample programs throughout the book. También descargado e
instalado el Kit de Desarrollo Java que se utiliza como escribir programas de ejemplo en
todo el libro.
If you are still confused about programs, programming languages, or Java in general, that's
understandable at this point. Si todavía está confundido acerca de los programas, lenguajes
de programación, o Java en general, que es comprensible en este momento. Everything will
make more sense to you in the next hour, "Writing Your First Program," which takes a slow
trip through the process of creating a Java program. Todo va a tener más sentido que en la
próxima hora, "Escribiendo tu primer programa," que tiene un viaje lento a través del
proceso de creación de un programa Java.

Q&A Q & A
Q What does the Internet have to do with making it easier to learn programming? Q ¿Qué
significa el Internet tienen que ver con lo que es más fácil de aprender a programar?

A Because of the dramatic growth of the World Wide Web, companies such as Microsoft,
Netscape, and Sun Microsystems are trying to attract as many programmers as possible to their
languages and related technology. A causa del dramático crecimiento de la World Wide Web, las
empresas como Microsoft, Netscape y Sun Microsystems están tratando de atraer a muchos
programadores como sea posible a sus lenguas y tecnología relacionada. To do this, they are
offering many programming tools for free over the Web, such as the Java Developer's Kit and the
beta release of the Microsoft Visual Basic 5 Control Creation Edition. Para ello, se ofrecen muchas
herramientas de programación de forma gratuita a través de Internet, tales como el Kit de
Desarrollo Java y la versión beta de Microsoft Visual Basic 5 Edición de Creación de Control. They
are offering others, such as SunSoft Java WorkShop for free 30- or 90-day trial periods. Ellos están
ofreciendo otros, como SunSoft Java WorkShop de forma gratuita 30 - o los períodos de prueba de
90 días. There also are numerous free products distributed over the Internet for programmers.
También son numerosos los productos distribuidos gratuitamente a través de Internet para los
programadores. To find out where these products are, visit Yahoo! at and search for a language
you're interested in. It's much cheaper today to learn programming than it was five years ago. Para
saber donde estos productos son, visite Yahoo! en http://www.yahoo.com y la búsqueda de un
lenguaje que usted está interesado pulg Es mucho más barato hoy para saber la programación de
lo que era hace cinco años.
Q What is it about BASIC that makes it easier to fall into bad habits while writing programs in it?
Q ¿Qué es lo básico que hace que sea más fácil caer en malos hábitos al escribir programas en
él?

A One thing you'll learn as you start writing Java programs is that you have to be organized. Una
cosa Vas a aprender como empezar a escribir programas Java es que tienes que ser organizado. If
you don't structure your program in the correct way, it won't work. Si no la estructura de su
programa en la forma correcta, no funcionará. BASIC doesn't have this kind of requirement. BASIC
no tiene este tipo de requisito. You can write in a disorganized manner and still get the program to
work successfully. Usted puede escribir de una manera desorganizada y aún así obtener el
programa funcione correctamente. Later on, however, you'll have a much harder time figuring out
the program if you try to fix a bug or add an improvement. Más tarde, sin embargo, tendrá un
tiempo mucho más difícil averiguar si el programa intenta corregir un error o agregar una mejora.

Q BASIC? Q Basic? C++? C + +? Java? Java? What are the names of these languages supposed to
mean? ¿Cuáles son los nombres de estas lenguas supone que significa eso?

A Like many programming languages, BASIC is an acronym that describes what it is: Beginner's All
Symbolic Instruction Code. A igual que muchos lenguajes de programación, BASIC es un acrónimo
que describe lo que es: principiante Todas Código de Instrucciones Simbólicas. C++ is a
programming language that was created to be an improvement on the C language, which itself
was an improvement of the B programming language. C + + es un lenguaje de programación que
fue creado para ser una mejora en el lenguaje C, que a su vez era una mejora del lenguaje de
programación B. Java goes against the tradition of naming a language with an acronym or other
meaningful term. Java va en contra de la tradición de nombrar a una lengua con una sigla o
término significativo otros. It's just the name that Java's developers liked the best when
brainstorming for possible monikers--beating out WebRunner, Silk, Ruby, and others. Es sólo el
nombre que los desarrolladores de Java gustaba la lluvia de ideas para apodos cuando sea posible
- superando a WebRunner, seda, Ruby y otros.

Q There are 89 books about Java programming? Q Hay 89 libros sobre programación con Java?

A Actually, as of this writing, there are 89 Java-related books now available in English, and another
171 are being prepared for publication. Una realidad, a partir de este escrito, hay 89 libros
relacionados con Java ya está disponible en Inglés, y otros 171 están siendo preparados para su
publicación. These figures come from a World Wide Web site by Steve Pietrowicz that lists all of
the known books and upcoming ones. Estas cifras provienen de un sitio World Wide Web por
Steve Pietrowicz que las listas de todos los libros conocidos y los próximos. Visit the following page
for details: Visita la siguiente página para más detalles:
http://lightyear.ncsa.uiuc.edu/ ~ srp / java /
javabooks.html
Q Why are interpreted languages slower than compiled ones? Q ¿Por qué los lenguajes
interpretados más lento que los compilados?

A For the same reason that a person interpreting a live speech is a lot slower than a translator
interpreting the printed speech later on. A Por la misma razón que una persona interpretar un
discurso en vivo es mucho más lento que un traductor interpretar el discurso impreso más tarde.
The live interpreter has to think about each statement that's being made as it happens, while the
other interpreter can work on the speech as a whole and take some shortcuts to speed up the
process. El intérprete en vivo tiene que pensar en cada declaración que se está haciendo como es
el caso, mientras que el otro intérprete puede trabajar en el discurso en su conjunto y tomar
algunos atajos para acelerar el proceso. Compiled languages can be much faster than interpreted
languages because they can do things to make the program more efficient. lenguajes compilados
pueden ser mucho más rápido que lenguajes interpretados, ya que pueden hacer cosas para que
el programa sea más eficiente.

Q Is C++ harder to learn than Java? Q es C + + más difícil de aprender que Java?

A It's a matter of personal opinion, but Java does seem more approachable for beginners than C++.
R Es una cuestión de opinión personal, pero Java parece más accesible para los principiantes de C
+ +. C++ and its predecessor, C, are widely regarded as "programmer's languages," meaning that
they were designed for the needs of experienced programmers. C + + y su predecesor, el C, son
ampliamente consideradas como "lenguas programador," lo que significa que fueron diseñados
para las necesidades de los programadores experimentados. There are a lot of features in C and C+
+ that make them faster--and more powerful--during program creation, but these features often
come at the expense of understandability. Hay un montón de funciones en C y C + + que los hacen
más rápido - y más poderosos - durante la creación del programa, pero estas características vienen
a menudo a expensas de claridad. Java takes a more simplified approach to programming than C++
and is probably a better place to start. Java tiene un enfoque más simplificado para la
programación de C + + y es probablemente un mejor lugar para empezar.

Quiz Quiz

Test your knowledge of the material covered in this chapter by answering the following
questions. Pon a prueba tus conocimientos sobre el material tratado en este capítulo,
respondiendo a las siguientes preguntas.
Questions
Preguntas
1. Which of the following is not a reason that people think computer programming is
painfully difficult? 1. ¿Cuál de los siguientes no es una razón que la gente piensa de
programación de computadoras es dolorosamente difícil?

(a) (A) Programmers spread that rumor to improve their employment prospects. Los
programadores propagación ese rumor para mejorar sus perspectivas de empleo.
(b) Jargon and acronyms are all over the place. (B) la jerga y las siglas son por todo el lugar.

(c) Mind-control waves are sent out by the CIA promoting this belief. (C) el control de las
ondas de la mente son enviados por la CIA, la promoción de esta creencia.

2. What kind of tool runs a computer program by figuring out one line at a time? 2. ¿Qué
tipo de herramienta se ejecuta un programa de ordenador por averiguar una línea a la
vez?

(a) A slow tool (A) Una herramienta lenta


(b) An interpreter (B) Un intérprete
(c) A compiler (C) Un compilador
3. Why did James Gosling hole up in his office and create Java? 3. ¿Por qué James Gosling
agujero en su oficina y crear Java?
(a) He was unhappy with the language he was using on a project. (A) Él no estaba contento
con el lenguaje que estaba utilizando en un proyecto.
(b) His rock band wasn't getting any gigs. (B) Su banda de rock no estaba recibiendo
ninguna de conciertos.
(c) When you can't download any image files at work, the World Wide Web is pretty dull.
(C) Cuando no se puede descargar cualquier archivo de imagen en el trabajo, la World
Wide Web es bastante aburrido.

Answers Respuestas
1. c. 1. C. Of course, the CIA could have forced me to say this. Por supuesto, la CIA podría
haber me obligó a decir esto.

2. b. 2. B. Compilers figure out the instructions beforehand so the program can run faster.
Los compiladores de averiguar las instrucciones de antemano lo que el programa puede
correr más rápido.

3. a. 3. A. The Web was still a little-known idea when Gosling wrote Java. La web era
todavía una idea poco conocida cuando Gosling escribió Java.
Activities

Actividades
If you'd like to better acquaint yourself with Java before you create your first program, do
the following activity: Si desea familiarizarse mejor con Java antes de crear su primer
programa, haga lo siguiente actividad:
 Visit the JavaSoft site at and read some of the introductory articles that are presented in
the section Visite el sitio JavaSoft en http://java.sun.com y leer algunos de los
artículos introductorios que se presentan en el ¿Qué es Java? sección

 2 horas
o
o Escribiendo tu primer programa  Almacenamiento de información en
 Lo que usted necesita para escribir la variable de la deuda
programas  Cambio de la información
 Creación del Programa BigDebt almacenada en la deuda
 A partir del Programa  Viendo el contenido de la deuda
 Listado 2.1. El programa BigDebt.  Guardar el producto terminado
 Figura 2.1.  Listado 2.2. La versión acabada del
 La Declaración de la clase programa BigDebt.
 Lo que la Declaración principal no  Listado 2.3. Una línea por línea de
 Los serpenteante Marcas Soporte desglose del programa BigDebt.
 Compilar el programa en un archivo  Resumen
de clase  Q&A
 Corregir errores  Quiz
 Figura 2.2.  Preguntas
 Ejecución del programa de  Respuestas
 Taller: La modificación del Programa  Actividades
 Listado 2.4. La versión modificada
del programa BigDebt.

Hour 2 2 horas
Writing Your First Program Escribiendo tu primer
programa
As you learned during Hour 1, "Becoming a Programmer," a computer program is a set of
instructions that tell a computer what to do. Como ha aprendido durante 1 hora,
"Convertirse en un programador," un programa de computadora es un conjunto de
instrucciones que indican a un ordenador qué hacer. These instructions are prepared in the
same way instructions could be given to a person: You type them into a word processor.
Estas instrucciones están dispuestos en las instrucciones de la misma manera se podría dar a
una persona: que se escriben en un procesador de textos. However, that's where the
similarity ends. Sin embargo, ahí es donde la semejanza termina. Instructions given to a
computer must be written using a programming language. Instrucciones dadas a un
ordenador debe estar escrito con un lenguaje de programación. Dozens of computer
programming languages have been created; you might have heard of some of them, such as
BASIC or Pascal. Docenas de lenguajes de programación se han creado, es posible que
haya oído hablar de algunos de ellos, tales como BASIC o Pascal.

During this hour, you will create your first Java program by entering it using any word
processor you like. Durante esta hora, va a crear su primer programa en Java por entrar en
ella utilizando cualquier procesador de texto que te gusta. When that's done, you will save
the program, compile it, and test it out. Cuando haya terminado, podrás guardar el
programa, compilarlo y probarlo. The following topics will be covered during this hour:
Entre los temas que se tratarán durante esta hora:
 Entering a program into a word processor Introducción de un programa en un procesador
de textos
 Naming a Java program with the statement Nombrar a un programa en Java con la
declaración de clase
 Organizing a program with bracket marks La organización de un programa de soporte con
las marcas
 Storing information in a variable Almacenamiento de información en una variable
 Changing the value of a variable Cambiar el valor de una variable
 Displaying the information stored in a variable Visualización de la información almacenada
en una variable
 Saving a program Ahorro de un programa
 Compiling a program Compilar un programa
 Running a program Ejecutar un programa de
 Fixing errors Corrección de errores
 Modifying a program Modificación de un programa de
What You Need to Write Programs Lo que usted necesita para escribir programas

As explained in Hour 1, you should have installed the current version of the Java
Developer's Kit on your system. Como se explica en 1 hora, usted debe tener instalada la
última versión del Kit de Desarrollo Java en su sistema. The kit contains tools that enable
you to compile and test Java programs. El kit contiene herramientas que le permiten
compilar y probar los programas de Java. You also need a word processor to write
programs. También se necesita un procesador de textos para escribir programas.
With most programming languages, computer programs are written by entering text into a
word processor (also called a text editor). Con la mayoría de los lenguajes de
programación, los programas informáticos son escritos por la introducción de texto en un
procesador de textos (llamado también un editor de texto). Some programming languages,
such as Visual C++ from Microsoft, come with their own word processor. Algunos
lenguajes de programación, como Visual C + + de Microsoft, vienen con su propio
procesador de textos. SunSoft Java WorkShop, an advanced programming tool from Java's
developers, also comes with its own editor. SunSoft WorkShop de Java, una herramienta de
programación avanzada de los desarrolladores de Java, también viene con su propio editor.
Java programs are simple text files without any special features such as centered text,
boldface text, or other enhancements. los programas Java son archivos de texto simple sin
ningún tipo de características especiales, tales como texto centrado, el texto en negrita, o de
otras mejoras. They can be written with any word processing program that can create text
files. Se puede escribir con cualquier programa de procesamiento de textos que puede crear
archivos de texto. Microsoft Windows systems have several word processors you can use,
including Notepad, WordPad, and the DOS program . Los sistemas de Microsoft Windows
tienen la palabra varios procesadores que puede utilizar, incluyendo el Bloc de notas,
WordPad, y DOS editar el programa. Apple Macintosh users can create programs with
Simple Text or other editors such as BBEdit Lite. Los usuarios de Apple Macintosh pueden
crear programas con texto simple o de otros editores, como BBEdit Lite. Any of these
programs will work fine. Cualquiera de estos programas no tendrán ningún problema.
Some word-processing programs are available on the CD-ROM that accompanies this
book, including BBEdit Lite. Algunos programas de procesamiento de textos están
disponibles en el CD-ROM que acompaña a este libro, incluyendo BBEdit Lite.
You also can use more sophisticated word processors, such as Microsoft Word, if you
remember to save the programs as text. También puede utilizar los procesadores de texto
más sofisticados, tales como Microsoft Word, si no olvide guardar los programas en forma
de texto. This option has different names depending on the program you are using. Esta
opción tiene diferentes nombres en función del programa que esté utilizando. In Word, the
file should be saved as a file of type Text Only. En Word, el archivo debe ser guardado
como un archivo de texto único tipo. Other programs call these files DOS text, ASCII text,
or something similar. Otros programas de llamar a estos archivos de texto DOS, texto
ASCII, o algo similar.

Caution: If you're in doubt as to whether a word processor can save files as text files, you can
always use one of the simple programs that comes with your operating system. Precaución: Si
estás en duda sobre si un procesador de textos puede guardar archivos como archivos de texto,
siempre puedes utilizar uno de los programas sencillos que viene con el sistema operativo.
Windows users can use Notepad to create Java programs because text files created with Notepad
are always saved as text-only files. Los usuarios de Windows pueden utilizar el Bloc de notas para
crear programas en Java porque los archivos de texto creado con el Bloc de notas siempre se
guardan como archivos de sólo texto.

After you have decided which word processor you will use to write Java programs, go
ahead and load it so you can start writing a program. Después de haber decidido qué
procesador de textos que utilizará para escribir programas Java, siga adelante y que la carga
para que pueda empezar a escribir un programa.
Windows 95 users must take one extra step before saving any Java-related files to disk: The
file extension must be associated with the selected word processor. Usuarios de Windows
95 deben dar un paso adicional antes de guardar los archivos relacionados con Java en el
disco:. La extensión de archivo java debe estar asociado con el procesador de textos
seleccionados. To do this, you need to create a new file and load it into the word processor
you'll be using during this book. Para ello, es necesario crear un nuevo archivo. Java y lo
cargan en el procesador de textos que va a utilizar en este libro.
To create the file, open up any file folder on your system and press the right-click button on
your mouse. Para crear el archivo, abra cualquier carpeta de archivos en su sistema y pulse
el botón derecho del ratón sobre el ratón. A pop-up menu will appear that will enable you to
choose the option. Una en el menú emergente aparecerá que le permitirá elegir la Nueva |
Texto opción Documento. Choose this option and a file named will appear. Elegir esta
opción y un archivo llamado Nuevo Documento de texto.txt aparecerá. Change the
name of this file to and confirm that you really want to choose the new name. Cambiar el
nombre de este archivo al Anything.java y confirmar que realmente desea para elegir el
nuevo nombre.
If you have never written Java programs on your computer, the file extension should not be
associated with any programs yet. Si usted nunca ha escrito programas de Java en su
equipo, el archivo java de extensión. No debe estar asociado con ningún programa
todavía. Double-click the file with the left mouse button and a dialog box will appear,
enabling you to choose a program for opening the file. Haga doble clic en el archivo
Anything.java con el botón izquierdo del ratón y un cuadro de diálogo aparecerá, lo que
le permite elegir un programa para abrir el archivo java.. Choose your preferred word
processor, first making sure to click the option . Elija el procesador de textos preferido, en
primer lugar asegurarse de hacer clic en la opción Utilizar siempre este programa
para abrir este archivo.
Creating the BigDebt Program Creación del Programa BigDebt
One of the things that computers are best at is math, a task that most humans are happy to
pass off to someone else (or something else, in this case). Una de las cosas que los
ordenadores son mejores en matemáticas es, una tarea que la mayoría de los seres humanos
son felices de hacer pasar a alguien (o algo más, en este caso). For your first Java program,
you will use the computer to determine a depressing fact about the financial condition of
the United States. Para su primer programa en Java, que va a utilizar el equipo para
determinar un hecho deprimente sobre la condición financiera de los Estados Unidos. Your
program will be called . Su programa se llama BigDebt. The program figures out how
much the national debt increases in an average minute. El programa se da cuenta de hasta
qué punto el aumento de la deuda nacional en un minuto promedio. In order to determine
this amount, the computer will be told how much the debt increases in an average day. Para
determinar esta cantidad, el equipo se le dirá la cantidad de la deuda aumenta en un día
normal.
The national debt is the amount the United States government has borrowed to compensate
for budget deficits over the years. La deuda nacional es la cantidad que ha prestado el
gobierno de Estados Unidos para compensar los déficit presupuestarios en los últimos años.
It was approaching $5.25 trillion at last count, which equals $19,700 in indebtedness for
each resident of the United States. Se aproxima $ 5250000000000 en el último recuento, lo
que equivale a 19.700 dólares en endeudamiento para cada residente de los Estados Unidos.
The following table shows the debt since 1960: La siguiente tabla muestra la deuda desde
1960:

1960: $290.2 billion $ 290


1960: 200 000 000
1965: $320.9 billion $ 320
1965: 900 000 000
1970: $389.2 billion $
1970: 389,200,000,000
1975: $576.6 billion $
1975: 576,600,000,000
1980: $930.2 billion $ 930
1980: 200 000 000
1985: $1.946 trillion $
1985: 1,946,000,000,000
1990: $3.365 trillion $
1990: 3365000000000
1995: $4.989 trillion $
1995: 4,989,000,000,000
Ed Hall maintains a Web page with the current national debt, updated continuously. Ed
Hall mantiene una página Web con la deuda nacional actual, actualizado continuamente.
It's available at the following location: Está disponible en la siguiente ubicación:
http://www.brillig.com/debt_clock/
Beginning the Program A partir del Programa
Using your word processor, begin your Java programming career by entering each line
from Listing 2.1. Utilizando el procesador de textos, comenzar su carrera de programación
Java mediante la introducción de cada línea del listado 2.1. Don't enter the line number and
colon at the beginning of each line--these are used in this book so that specific line numbers
can be referred to. No ingrese el número de línea y los dos puntos al principio de cada línea
- éstos se utilizan en este libro para que los números de línea específica se puede
denominar.
Listing 2.1. Listado 2.1. The BigDebt program. El programa BigDebt.

1: class BigDebt { 1: BigDebt clase {


2: public static void main (String[] arguments) { 2:
public static void main (String [argumentos]) {
3: // My first Java program goes here 3: / / Mi primer
programa en Java va aquí
4: } 4:}
5:}

Make sure to capitalize everything exactly as shown, and use your Tab key or space bar to
insert the blank spaces in front of some lines. Asegúrese de aprovechar todo exactamente
como se muestra, y utilizar el tabulador o la barra espaciadora para insertar los espacios en
blanco en frente de algunas líneas. When you're done, save the file with the file name .
Cuando haya terminado, guarde el archivo con el nombre de archivo BigDebt.java.
Figure 2.1 shows the full text of Listing 2.1 entered using the Zeus for Windows word
processor and saved as . Figura 2.1 muestra el texto completo del listado 2.1 especificar
con el procesador de textos de Windows para Zeus y guarda como BigDebt.java.
You have created the bare-bones form of a Java program. Se ha creado la forma desnuda
huesos de un programa Java. You will create several programs that start off exactly like this
one, except for the word on Line 1. Usted creará varios programas que comienzan
exactamente como esta, a excepción de la BigDebt palabra en la Línea 1. This word
represents the name of your program and changes with each program that you write. Esta
palabra representa el nombre de su programa y cambia con cada programa que usted
escribe. Line 3 also should make sense--it's a sentence in actual English. La línea 3 también
debe tener sentido - es una frase en Inglés reales. The rest is completely new, however, and
each part is introduced in the following sections. El resto es completamente nuevo, sin
embargo, y cada parte se introduce en las siguientes secciones.
Figura 2.1. Entering using the Zeus for Windows word- processing program. Introducción
BigDebt.java con el Zeus de tratamiento de textos programa de Windows.
The class Statement La Declaración de la clase
The first line of the program is the following: La primera línea del programa es el siguiente:
class BigDebt { clase BigDebt {

Translated into English, this line means, "Computer, give my Java program the name ."
Traducido al Inglés, esta línea de medios, "Informática, doy mi programa Java BigDebt el
nombre."
As you might recall from Hour 1, each instruction that you give a computer is called a
statement. Como se puede recordar de una hora, cada instrucción que le dan un equipo que
se llama un comunicado. The statement is the way you give your computer program a
name. La declaración de clase es la forma de dar a su programa de ordenador un nombre.
It also is used to determine other things about the program, as you will see later. También
se utiliza para determinar otras cosas sobre el programa, como se verá más adelante. The
significance of the term is that Java programs also are called classes. La importancia de la
clase plazo es que los programas Java también son llamadas clases.
In this example, the program name matches the file name you gave your document, . En
este ejemplo, el BigDebt nombre del programa coincide con el nombre de archivo que le
dio el documento, BigDebt.java. Java programs must have a name that matches the first
part of their file names, and these names always must be capitalized in the same way. los
programas de Java debe tener un nombre que coincide con la primera parte de sus nombres
de archivo, y sus nombres deben estar siempre en mayúsculas de la misma manera. If the
name doesn't match, you will get an error when you try to compile the program. Si el
nombre no coincide, obtendrá un error al intentar compilar el programa.
What the main Statement Does Lo que la Declaración principal no
The next line of the program is the following: La siguiente línea del programa es el
siguiente:
public static void main (String[] arguments) { public
static void main (String [argumentos]) {

This line tells the computer, "The main part of the program begins here." Esta línea le dice
a la computadora, "La parte principal del programa comienza aquí". Java programs are
organized into different sections, so there needs to be a way to identify the part of a
program that will be handled first. los programas de Java se organizan en diferentes
secciones, por lo que es necesario que haya una manera de identificar la parte de un
programa que se manejará en primer lugar. All of the programs that you will write during
the next several hours use as the starting point. Todos los programas que va a escribir
durante las próximas horas de uso principal como punto de partida.
Those Squiggly Bracket Marks Los serpenteante Marcas Soporte
In the program, every line except Line 3 contains a squiggly bracket of some kind--either
an or an . En el programa BigDebt.java, todas las líneas excepto la línea 3 contiene un
soporte torcido de algún tipo - ya sea un {o} una. These brackets are a way to group parts
of your program (in the same way that parentheses are used in this sentence to group
words). Estos soportes son una manera de agrupar partes de su programa (de la misma
manera que los paréntesis se utilizan en esta frase a las palabras del grupo). Everything
between the opening bracket, , and the closing bracket, , is part of the same group. Todo lo
que entre el corchete de apertura, {, y el paréntesis de cierre,}, es parte del mismo
grupo.
These groupings are called blocks. Estos grupos se denominan bloques. In Listing 2.1, the
opening bracket on Line 1 is associated with the closing bracket on Line 5, which makes
your entire program a block. En el listado 2.1, el soporte de la apertura de la línea 1 está
asociado con el paréntesis de cierre en la línea 5, que hace todo el programa un bloque. You
will always use brackets in this way to show the beginning and end of your programs.
Siempre se utilizan soportes de esta manera para mostrar el principio y el final de sus
programas.
Blocks can be located inside other blocks (just as parentheses are used here (and a second
set is used here)). Los bloques pueden estar situados dentro de otros bloques (como
paréntesis se utilizan aquí (y un segundo sistema se usa aquí)). The program has brackets
on Line 2 and Line 4 that establish another block. El programa ha BigDebt.java paréntesis
en la Línea 2 y Línea 4 que establecer otro bloque. This block begins with the statement.
Este bloque comienza con la afirmación principal. Everything inside the statement
block is a command for the computer to handle when the program is run. Todo el interior
del bloque de instrucciones principal es un símbolo para el equipo de manejar cuando se
ejecuta el programa.
The following statement is the only thing located inside the block: La siguiente declaración
es lo único que está situado dentro del bloque:
// My first Java program goes here / / Mi primer programa
en Java va aquí

This line is a placeholder. Esta línea es un marcador de posición. The at the beginning of
the line tells the computer to ignore this line--it is put in the program solely for the benefit
of humans who are looking at the program's text. El / / al principio de la línea le dice a la
computadora hacer caso omiso de esta línea - que se pone en el programa únicamente para
el beneficio de las personas que están buscando en el texto del programa. Lines that serve
this purpose are called comments. Las líneas que sirven a este propósito son llamados
comentarios.
Right now, you have written a complete Java program. En este momento, usted ha escrito
un completo programa Java. It can be compiled, but if you run it, nothing will happen.
Puede ser compilado, pero si lo haces, no pasará nada. The reason for this is that you have
not told the computer to do any-thing yet. La razón de esto es que no han dicho a la
computadora para hacer cualquier cosa todavía. The statement block contains only a line of
comments, which is ignored. El bloque de instrucciones principal contiene sólo una línea
de comentarios, que se ignora. If the program is going to provide sobering details about the
United States Treasury, you will have to add some commands inside the opening and
closing brackets of the statement block. Si el programa BigDebt.java va a proporcionar
detalles sobre la preocupante Tesoro de los Estados Unidos, usted tendrá que agregar
algunos comandos en el interior del paréntesis de cierre y apertura del bloque de
instrucciones principal.
Storing Information in the debt Variable Almacenamiento de información en la variable
de la deuda
The national debt is increasing at a present rate of $59 million per day. La deuda nacional
aumenta a un ritmo actual de $ 59 millones por día. To put this number into perspective,
overpaid sports athletes could donate their salaries to the United States Treasury and barely
make a dent in it. Para poner este número en perspectiva, exceso deportes los atletas
podrían donar sus sueldos a la Tesorería de los Estados Unidos y apenas hacen mella en él.
Chicago White Sox slugger Albert Belle's five-year, $50 million deal stops the debt from
increasing for about 20 hours. Medias Blancas de Chicago toletero Albert Belle de cinco
años, 50 millones de dólares deja de aumentar la deuda por cerca de 20 horas.
Aside from the publishers of computer books, most of us don't make the same kind of
money as pro athletes. Además de los editores de libros de informática, la mayoría de
nosotros no hacen el mismo tipo de dinero como atletas profesionales. If we want to slow
down the growing debt ourselves, a place to start is by breaking it down into minutes. Si
queremos frenar la creciente deuda de nosotros mismos, un lugar para empezar es lo
descomponen en minutos. Your Java program will figure this out for you. Su programa
Java resolver esto para usted.
The first step is to tell the computer what you were just told: The national debt goes up $59
million per day. El primer paso es decirle al ordenador lo que le dijeron simplemente: La
deuda nacional se eleva 59 millones dólares por día. Load the file into your word processor
if it's not still loaded, and replace Line 3 with the following: Cargue el archivo
BigDebt.java en su procesador de textos si no es aún cargado, y reemplazar la línea 3 por
el siguiente:
int debt = 59000000; la deuda int = 59000000;

This statement tells the computer to store the value 59,000,000 into a variable called . Esta
declaración le dice a la computadora para almacenar el valor de 59 millones en un crédito
variable llamada. Variables are special storage places where a computer program can store
information. Las variables son lugares especiales de conservación en un programa de
ordenador puede almacenar información. The value of variables can be changed. El valor
de las variables se puede cambiar.
Variables can be used to hold several different types of information, such as integers,
floating-point numbers, lines of text, and characters of text. Las variables pueden ser usados
para sostener varios tipos diferentes de información, como números enteros, números en
coma flotante, las líneas de texto y caracteres de texto. In a Java program, you must tell the
computer what type of information a variable will hold. En un programa Java, debe decirle
al ordenador qué tipo de información que una variable se espera. In this program, is an
integer. En este programa, la deuda es un número entero. Putting in the statement sets up
the variable to hold integer values. Poner int en la declaración de la deuda int =
59000000; establece la variable para almacenar valores enteros.
The variable type can store values from -2.1 billion to 2.1 billion in Java programs. El tipo
de variable int puede almacenar valores de -2.1 mil millones a 2,1 mil millones en los
programas de Java. There are other variable types for different types of numbers and other
types of information. Existen otros tipos variables para los distintos tipos de números y
otros tipos de información.
When you entered this statement into the computer program, a semi-colon should have
been included at the end of the line. Cuando entró esta declaración en el programa de
ordenador, un punto y coma se deberían haber incluido al final de la línea. Semi-colons are
used at the end of each command in your Java programs. Punto y coma se utiliza al final de
cada comando en los programas Java. They're like periods at the end of a sentence; the
computer uses them to determine when one command ends and the next command begins.
Son como puntos al final de una oración, el equipo utiliza para determinar cuándo termina
un comando y comienza el siguiente comando.
Changing the Information Stored in debt Cambio de la información almacenada en la
deuda
As it stands, the program you have written does one thing: It uses the variable to hold the
value 59,000,000--a day's worth of growing debt. En la actualidad, el programa que he
escrito hace una cosa: Se utiliza la variable de la deuda para mantener el valor de 59
millones - día la pena de la deuda cada vez mayor. However, you want to determine the
amount of debt per minute, not per day. Sin embargo, desea determinar el importe de la
deuda por minuto, no por día. To determine this amount, you need to tell the computer to
change the value that has been stored in the variable. Para determinar esta cantidad, es
necesario decirle a la computadora para cambiar el valor que se ha almacenado en la
variable de la deuda. There are 1,440 minutes in each day, so tell the computer to divide
the value in by 1,440. Hay 1.440 minutos en cada día, por lo que indican a la computadora
de dividir el valor de la deuda por 1.440.
Insert a blank line after the statement. Insertar una línea en blanco después de la deuda
int = 59000000; comunicado. In the blank line, enter the following: En la línea en
blanco, escriba lo siguiente:
debt = debt / 1440; deuda = Deuda / 1440;

If you haven't been able to suppress all memories of new math, this statement probably
looks like an algebra problem to you. Si no ha sido capaz de suprimir todos los recuerdos
de la nueva matemática, esta afirmación probablemente se ve como un problema de álgebra
para usted. It gives the computer the following assignment: "Set the variable equal to its
current value divided by 1,440." Le da al equipo la siguiente asignación: "Establecer la
variable de la deuda igual a su valor actual, dividido por 1440."
You now have a program that does what you wanted it to do. Ahora tiene un programa que
hace lo que usted quería que hiciera. It determines the amount the national debt grows in an
average minute. Se determina el importe de la deuda nacional crece en un medio por
minuto. However, if you ran the program at this point, it wouldn't display anything. Sin
embargo, si se ejecutó el programa en este momento, no muestra nada. The two commands
you have given the computer in the program occur behind the scenes. Los dos comandos
que le han dado el equipo en el programa BigDebt ocurren detrás de las escenas. To show
the computer's result, you have to display the contents of the variable. Para mostrar el
resultado de la computadora, usted tiene que mostrar el contenido de la variable de la
deuda.
Displaying the Contents of debt Viendo el contenido de la deuda
Insert another blank line in the program after the statement. Insertar otra línea en blanco
en el programa BigDebt después de la deuda de la deuda = / 1440; comunicado. Use
that space to enter the following statement: Utilizar este espacio para entrar en la siguiente
declaración:
System.out.println("A minute's worth of debt is $" +
debt); System.out.println ("Un minuto de valor de la deuda
es de $" + deuda);

This statement tells the computer to display the text followed by the value stored in the
variable. Esta declaración le dice a la computadora para mostrar el texto vale la pena un
minuto de la deuda es de $ seguido por el valor almacenado en la variable de la
deuda. The command means "display a line on the system output device." El comando
System.out.println significa "mostrar una línea en el dispositivo de salida del sistema."
In this case, the system output device is your computer monitor. En este caso, el dispositivo
de salida del sistema es el monitor del ordenador. Everything within the parentheses is
displayed. Todo dentro de los paréntesis se muestra.
Saving the Finished Product Guardar el producto terminado
Your program should now resemble Listing 2.2. Su programa debería ser ahora similar de
venta 2.2. Make any corrections that are needed and save the file as . Haga las correcciones
necesarias y guardar el archivo como BigDebt.java. Keep in mind that all Java programs
are created as text files and are saved with the file extension. Tenga en cuenta que todos
los programas de Java se crean como archivos de texto y se guardan con el archivo java de
extensión..
Listing 2.2. Listado 2.2. The finished version of the BigDebt program. La versión
acabada del programa BigDebt.

1: class BigDebt { 1: BigDebt clase {


2: public static void main (String[] arguments) { 2:
public static void main (String [argumentos]) {
3: int debt = 59000000; ; 59000000: 3 int deuda =
4: debt = debt / 1440; 4: la deuda de la deuda = / 1440;
5: System.out.println("A minute's worth of debt is $" +
debt); 5: System.out.println ("Un minuto de valor de la
deuda es de $" + deuda);
6: } 6:}
7:}

When the computer runs this program, it will run each of the statements in the statement
block on lines 3 through 5. Cuando el equipo se ejecuta este programa, se ejecutará cada
una de las declaraciones en el bloque de instrucciones principal en las líneas 3 a 5.
Listing 2.3 shows what the program would look like if it were written in the English
language instead of Java. Listado 2.3 muestra lo que el programa se vería como si fuera
escrito en el idioma Inglés en vez de Java.
Listing 2.3. Listado 2.3. A line-by-line breakdown of the BigDebt program. Una línea por
línea de desglose del programa BigDebt.

1: The BigDebt program begins here: 1: El programa BigDebt


comienza aquí:
2: The main part of the program begins here: 2: La parte
principal del programa comienza aquí:
3: Store the value 59000000 in an integer variable called
debt 3: Guarde el valor de 59 millones en una variable
entera llamada deuda
4: Set debt equal to its current value divided by 1440 4:
Seleccionar 1440 la deuda igual a su valor actual, dividido
por
5: Display "A minute's worth of debt is $" and the new
value of debt 5: Pantalla "Un minuto de valor de la deuda
es de $" y el nuevo valor de la deuda
6: The main part of the program ends here. 6: La parte
principal del programa termina aquí.
7: El programa BigDebt termina aquí.
Compiling the Program into a Class File Compilar el programa en un archivo de clase
Before you can try out the program, it must be compiled. Antes de que pueda probar el
programa, éste debe ser compilado. The term compile might be unfamiliar to you now, but
you will become quite familiar with it in the coming hours. El término de compilación
puede ser desconocido para usted ahora, pero será bastante familiarizado con él en las
próximas horas. When you compile a program, you take the instructions you have given the
computer and convert them into a form the computer can better understand. Cuando se
compila un programa, usted toma las instrucciones que ha dado el equipo y los convierten
en una forma que el ordenador pueda entender mejor. You also make the program run as
efficiently as possible. También que el programa de ejecución más eficiente posible. Java
programs must be compiled before you can run them. los programas de Java se debe
compilar antes de ejecutarlos. With the Java Developer's Kit, programs are compiled with
the tool. Con Java Developer Kit, los programas se compilan con la herramienta javac.
To compile the program, go to the directory on your system where the file is located, and
type the following command: Para compilar el programa BigDebt, vaya al directorio en su
sistema en el archivo que se encuentra es la BigDebt.java, y escriba el siguiente
comando:
javac BigDebt.java javac BigDebt.java

When the program compiles successfully, a new file called is created in the same directory
as . Cuando el programa se compila con éxito, un nuevo archivo llamado BigDebt.class
se crea en el mismo directorio que BigDebt.java. (If you have any error messages, refer
to the following section, "Fixing Errors.") The extension was chosen because all Java
programs also are called classes. (Si usted tiene algún mensaje de error, consulte la
siguiente sección, "corregir errores.") La extensión de clase. Fue elegido por todos los
programas Java también se denominan clases. A Java program can be made up of several
classes that work together, but in a simple program such as only one class is needed. Un
programa Java puede estar compuesta de varias clases que trabajan juntas, pero en un
programa sencillo como BigDebt una sola clase es necesaria.
Do you have a relative, spouse, or other loved one who only says something when things go
wrong? ¿Tiene un cónyuge pariente, u otro ser querido que sólo dice algo cuando las cosas
van mal? (Me neither.) The tool only speaks up when there's an error to complain about.
(Yo tampoco). La herramienta javac sólo habla cuando hay un error de que quejarse. If
you compile a program successfully without any errors, nothing happens in response. Si
compila un programa de éxito sin ningún error, no pasa nada en respuesta.
Fixing Errors Corregir errores
If errors exist in your program when you compile it, the tool displays a message explaining
each error and the lines they occurred on. Si existen errores en el programa cuando se
compila, se muestra la herramienta javac un mensaje que explica todos los errores y las
líneas que se produjo el. Figure 2.2 shows an attempt to compile a program that has errors,
and the error messages that are displayed as a result. Figura 2.2 muestra un intento de
compilar un programa que tiene errores, y los mensajes de error que se muestra como un
resultado.
Error messages displayed by the tool include the following information: Mensajes de error
mostrados por la herramienta javac incluir la siguiente información:
 The name of the Java program El nombre del programa en Java
 The number of the line where the error was found El número de la línea donde se
encontró el error
 The type of error El tipo de error
 The line where the error was found La línea donde se encontró el error
Figura 2.2. Compiling a version of the program that has errors. Compilación de una
versión del programa BigDebt que tiene errores.
As you learned during the past hour, errors in programs are called bugs. Como ha
aprendido durante la última hora, los errores en los programas se llaman errores. Finding
those errors and squashing them is called debugging. Encontrar los errores y aplastar ellos
se llama depuración. The following is an example of an error message from Figure 2.2: El
siguiente es un ejemplo de un mensaje de error de la figura 2.2:
BigDebt.java:4: Invalid type expression. BigDebt.java: 4:
tipo de expresión no válida.
debt = debt / 1440 deuda = Deuda / 1440
In this example, the that follows the file name indicates that the error is on Line 4. En este
ejemplo, el 4, que sigue al nombre de archivo BigDebt.java indica que el error está en la
línea 4. The actual error message, in this case, can often be con-fusing to new
programmers. El mensaje de error real, expresión de tipo no válido en este caso, a
menudo puede ser con-fusión para los nuevos programadores. In some cases, the message
can be confusing to any programmer. En algunos casos, el mensaje puede ser confuso para
cualquier programador. When the error message doesn't make sense to you, take a look at
the line where the error occurred. Cuando el mensaje de error no tiene sentido para usted,
eche un vistazo a la línea donde se produjo el error.
For instance, can you determine what's wrong with the following statement? Por ejemplo,
puede determinar lo que está mal con la siguiente afirmación?
debt = debt / 1440 deuda = Deuda / 1440

The problem is that there's no semi-colon at the end of the statement, which is required in
Java programs. El problema es que no hay punto y coma al final de la declaración, que se
requiere en los programas de Java.
If you get error messages when compiling the program, double-check that your program
matches Listing 2.2, and correct any differences you find. Si recibe mensajes de error al
compilar el programa BigDebt, compruebe que su programa de partidos de venta 2.2, y
corregir las diferencias que encuentre. Make sure that everything is capitalized correctly,
and all punctuation (such as , , and ) is included. Asegúrese de que todo está
correctamente capitalizado, y todos los puntuacion (por ejemplo, {,}, y, principalmente).
Often, a close look at the statement included with the error message is enough to reveal the
error, or errors, that need to be fixed. A menudo, una mirada cercana a la declaración se
incluye con el mensaje de error es suficiente para revelar el error o errores, que deben ser
fijos.
Running the Program Ejecución del programa de
The Java Developer's Kit provides a Java interpreter so that you can try the program you
have created. El Kit de Desarrollo Java proporciona un intérprete de Java, para que pueda
probar el programa que ha creado. The interpreter makes the computer follow the
instructions you gave it when you wrote the program. El intérprete hace que el ordenador
siga las instrucciones que le dio cuando se escribió el programa. To see whether the
program does what you want, go to the directory that contains the file, and type the
following: Para ver si el programa BigDebt hace lo que quiere, vaya al directorio que
contiene el archivo BigDebt.class, y escriba lo siguiente:
java BigDebt java BigDebt

When the program runs, it should state the following: Cuando se ejecuta el programa, se
debe indicar lo siguiente:
A minute's worth of debt is $40972 Un minuto de valor de
la deuda es $ 40,972

The computer has provided the answer you wanted! El equipo ha dado la respuesta que
quería! With this information, you now know that if you want to donate your salary to slow
one minute's growth of the national debt, you need to make more than $40 grand per year.
Con esta información, ahora sabemos que si usted desea donar su sueldo para frenar el
crecimiento de un minuto de la deuda nacional, es necesario hacer más de $ 40 grandes por
año. You also have to avoid paying any taxes. También tienes que evitar el pago de los
impuestos.

Caution: Neither the author nor Sams.net Publishing makes any guarantees express or implied
that the Internal Revenue Service will accept the excuse that you spent all your money on the
national debt. Precaución: Ni el autor ni la editorial Sams.net hace ninguna garantía expresa o
implícita de que el Servicio de Rentas Internas aceptará la excusa de que ha gastado todo su
dinero en la deuda nacional.

Workshop: Modifying the Program Taller: La modificación del Programa


The program calculated the amount the national debt increases in a minute. El programa
BigDebt calculó el importe de la deuda nacional aumenta en un minuto. If you'd like to
make a dent in the debt but can't spare $40,000, you might want to see how much a
second's worth of debt would cost you. Si desea hacer mella en la deuda, pero no puede
prescindir de $ 40,000, usted podría querer ver cuánto vale un segundo de la deuda le
costaría.
Load the file into your word processor again. Cargue el archivo BigDebt.java en su
procesador de textos de nuevo. You need to change the following statement: Es necesario
cambiar la siguiente declaración:
debt = debt / 1440; deuda = Deuda / 1440;

This line divided the value in the variable by 1,440 because there are 1,440 minutes in a
day. Esta línea divide el valor de la variable de la deuda por 1.440 porque hay 1.440
minutos en un día. Change the line in the program so that it divides the variable by 86,400,
the amount of seconds in a day. Cambie la línea en el programa BigDebt modo que se
divide la variable de la deuda por 86.400, la cantidad de segundos en un día.

Caution: When you change the line of code, don't include a comma in the number (as in ).If you
do, you will get an error message when you compile the program. Precaución: Cuando se cambia
la línea de código, no incluya una coma en el número (como en 86 400) del programa. Si lo hace,
obtendrá un mensaje de error al compilar el. Commas may make it easier for people to read the
numbers in your code, but the compiler doesn't appreciate the gesture. Las comas pueden hacer
más fácil para la gente a leer los números en el código, pero el compilador no aprecia el gesto.

You also need to change the following line: También es necesario cambiar la siguiente
línea:
System.out.println("A minute's worth of debt is $" +
debt); System.out.println ("Un minuto de valor de la deuda
es de $" + deuda);

Now that you're calculating a second's worth of debt, you need to replace the word with .
Ahora que eres el cálculo de la pena un segundo de la deuda, es necesario sustituir el
minuto palabra con el segundo. Make the change and save the file . Hacer el cambio y
guardar el archivo BigDebt.java. Your version of should match Listing 2.4. Su versión
de BigDebt.java debe coincidir de venta 2.4.
Listing 2.4. Listado 2.4. The modified version of the BigDebt program. La versión
modificada del programa BigDebt.

1: class BigDebt { 1: BigDebt clase {


2: public static void main (String arguments[]) { 2:
static public void principal (String argumentos []) {
3: int debt = 59000000; ; 59000000: 3 int deuda =
4: debt = debt / 86400; 4: la deuda de la deuda = / 86400;
5: System.out.println("A second's worth of debt is $" +
debt); 5: System.out.println ("en segundo lugar la pena de
la deuda es de $" + deuda);
6: } 6:}
7:}

Compile the file with the same command that you used previously: Compilar el archivo con
el mismo comando que utilizó anteriormente:
javac BigDebt.java javac BigDebt.java

When you run the program, you should get the following output: Cuando se ejecuta el
programa, usted debe obtener el siguiente resultado:
A second's worth of debt is $682 Un segundo valor de la
deuda es $ 682

Summary Resumen
During this hour, you got your first chance to create a Java program. Durante esta hora, que
obtuvo su primera oportunidad de crear un programa Java. You learned that to create a Java
program you need to complete these three basic steps: Usted aprendió que para crear un
programa Java que necesitas para completar estos tres pasos básicos:
1. Write the program with a word processor. 1. Escribe el programa con un procesador de
textos.

2. Compile the program. 2. Compilar el programa.

3. Tell the interpreter to run the program. 3. Dile a la intérprete para ejecutar el programa.
Along the way, you were introduced to some basic computer programming concepts such
as compilers, interpreters, blocks, statements, and variables. En el camino, que se
introdujeron a algunos conceptos básicos de programación informática, tales como
compiladores, intérpretes, bloques, declaraciones, y las variables. These things will become
more clear to you in successive hours. Estas cosas se harán más claras para que en las horas
sucesivas. As long as you got the program to work during this hour, you're ready to
proceed. Mientras usted tiene el programa para trabajar durante esta hora, ya está listo para
proceder.
Q&A Q & A
Q Is SunSoft Java WorkShop another programming language like Java, or is it something
else? Q es SunSoft Java WorkShop otro lenguaje de programación como Java, o es algo
más?

A Java WorkShop is a way to write Java programs in a graphical, point-and-click


environment. Un Taller de Java es una forma de escribir programas Java en una gráfica, de
apuntar y hacer clic con el medio ambiente. It was produced by a division of Sun
Microsystems, the developer of Java, as an improvement upon the Java Developer's Kit.
Fue producido por una división de Sun Microsystems, el desarrollador de Java, como una
mejora en el Kit de Desarrollo Java. Other products in the market offer similar features,
such as Symantec Café, Microsoft J++, and RogueWave JFactory. Otros productos en el
mercado ofrecen características similares, tales como Symantec Café, Microsoft J + +, y
JFactory RogueWave. For more information on these products, see Appendix B, "Java
Programming Tools." Para obtener más información sobre estos productos, consulte el
Apéndice B, "Herramientas de programación en Java."

QI have several word processing programs on my system. P Tengo varios programas de


procesamiento de texto en mi sistema. Which should I use to write Java programs? ¿Qué
debo usar para escribir programas Java?

A Any of them will suffice, as long as it can save files as text without any special
formatting. A cualquier de ellos será suficiente, siempre que pueda guardar archivos como
texto sin formato especial. A word processor that shows the line number your cursor is
located on is especially useful. Un procesador de texto que muestra el número de línea el
cursor se encuentra en es especialmente útil. (Microsoft Word, for example, shows the
line number at the bottom edge of the window along with the column number.) Because
the compiler lists line numbers with its error messages, the line-numbering feature helps
you debug a program more quickly. (Microsoft Word, por ejemplo, muestra el número de
línea en el borde inferior de la ventana, junto con el número de columna.) Debido a que el
compilador javac listas de números de línea con sus mensajes de error, la función de
numeración de línea le ayuda a depurar un programa con mayor rapidez.

Q How important is it to put the right number of blank spaces on a line in a Java
program? Q ¿Qué tan importante es para poner el número correcto de los espacios en
blanco en una línea en un programa Java?

A Spacing is strictly for the benefit of people looking at a computer program. Un


espaciamiento es estrictamente para el beneficio de la gente que busca en un programa
de ordenador. You could have written the program without using blank spaces or the Tab
key to indent lines, and it would compile successfully. Usted podría haber escrito el
programa BigDebt sin utilizar espacios en blanco o la tecla Tab para líneas de guión, y
sería compilar correctamente. Although the number of spaces in front of the lines isn't
important, you should use spacing in your Java programs. Aunque el número de espacios
en el frente de las líneas no es importante, usted debe utilizar espacio en sus programas
Java. Spacing indicates how a program is organized and which programming block a
statement belongs to. Espaciado indica cómo un programa está organizado y que la
programación del bloque una declaración pertenece. When you start writing more
sophisticated programs, you'll find it much more difficult to do without spacing. Cuando
empieza a escribir programas más sofisticados, lo encontrará mucho más difícil de hacer
sin espacio.

QA Java program has been described as a class, and it also has been described as a group
of classes. GC programa Java ha sido descrita como una clase, y también ha sido descrita
como un grupo de clases. Which is it? ¿Qué es?

A Both. A dos. The simple Java programs that you create during the next few hours will
create a single file with the extension . Los sencillos programas de Java que se crea
durante las próximas horas va a crear un único archivo con la extensión. Clase. You
can run these programs with the interpreter. Puede ejecutar estos programas con el
intérprete Java. Java programs also can consist of a set of classes that work together. los
programas de Java también puede consistir en un conjunto de clases que trabajan juntas.
In fact, even simple programs like use other Java classes behind the scenes. De hecho,
incluso los programas simples como BigDebt utilizar otras clases de Java detrás de las
escenas. This topic will be fully explored during Hour 10, "Creating Your First Object." Este
tema será explorado a fondo durante la hora 10, "Creación de su primer objetivo."

Q If semi-colons are needed at the end of each statement, why does the comment
line // My first Java program goes here not end with a semi-colon? Q Si un punto y coma
son necesarios al final de cada afirmación, ¿por qué la línea de comentario / / Mi primer
programa en Java va aquí no termina con un punto y coma?

A Comments are completely ignored by the compiler. Una comentarios son


completamente ignorados por el compilador. If you put on a line in your program, this
tells the Java compiler to ignore everything to the right of the on that line. Si coloca / /
en una línea en su programa, este le dice al compilador de Java hacer caso omiso de todo
a la derecha de la / / en esa línea. The following example shows a comment on the same
line as a statement: El siguiente ejemplo muestra un comentario en la misma línea como
una declaración:
debt = debt / 86400; // divide debt by the number of
seconds deuda = Deuda / 86400 / / la deuda se divide por el
número de segundos

In this example, the compiler will handle the statement and ignore the comments
afterward. En este ejemplo, el compilador se encargará de la declaración de la deuda
de la deuda = / 86400, e ignorar los comentarios después.

Q What is a character? Q ¿Qué es un personaje?

A A character is a single letter, number, punctuation mark, or other symbol. Un personaje


A es una sola letra, número, signo de puntuacion, u otro símbolo. Examples are T, 5, and
%. Ejemplos de ello son T, 5 y%. Characters are stored in variables as text. Los caracteres
se almacenan en las variables de texto.

QI get an Invalid argument error message when I use the javac tool to compile the
BigDebt program. MC obtener un argumento no válido mensaje de error cuando se
utiliza la herramienta javac para compilar el programa BigDebt. What can I do to correct
this? ¿Qué puedo hacer para corregir esto?

A You are probably leaving off the extension and typing the following command: A Usted
probablemente está dejando fuera el comando java. Extensión y escribiendo lo
siguiente:
javac BigDebt javac BigDebt

Make sure that you are in the same directory as the file , and type the following command
to compile the program: Asegúrese de que usted está en el mismo directorio que el
archivo BigDebt.java, y escriba el comando siguiente para compilar el programa:

javac BigDebt.java javac BigDebt.java

QI couldn't find any errors in the line where the compiler noted an error. P No se han
encontrado errores en la línea donde el compilador tomó nota de un error. What can I
do? ¿Qué puedo hacer?

A The line number displayed with the error message isn't always the place where an error
needs to be fixed in your program. Un número de línea Los que aparecen con el mensaje
de error no es siempre el lugar donde un error debe ser corregido en su programa.
Examine the statements that are directly above the error message to see whether you can
spot any typos or other bugs. Examinar las declaraciones que están directamente sobre el
mensaje de error para ver si puede detectar cualquier erratas o errores. The error usually
is within the same programming block. El error suele ser en el mismo bloque de
programación.
Quiz Quiz
Test your knowledge of the material covered in this chapter by answering the following
questions. Pon a prueba tus conocimientos sobre el material tratado en este capítulo,
respondiendo a las siguientes preguntas.
Questions Preguntas
1. When you compile a Java program, what are you doing? 1. Cuando se compila un
programa Java, ¿qué estás haciendo?
(a) Saving it to disk (A) Guardar en el disco
(b) Converting it into a form the computer can better understand (B) para convertirlo en
una forma que el ordenador pueda entender mejor
(c) Adding it to your program collection (C) Añadir a tu colección de programa

2. What is a variable? 2. ¿Qué es una variable?

(a) Something that wobbles but doesn't fall down. (A) Algo que se tambalea, pero no se
caiga.
(b) Text in a program that the compiler ignores. (B) el texto de un programa que el
compilador ignora.
(c) A place to store information in a program. (C) Un lugar para almacenar información en
un programa.

3. What is the process of fixing errors called? 3. ¿Cuál es el proceso de fijación de los
errores de llamada?

(a) Defrosting (A) Descongelación


(b) Debugging (B) Depuración
(c) Decomposing (C) Descomposición
Answers Respuestas
1. b. 1. B. Compiling converts a file into a file or set of files. Compilar convierte un archivo
java. En un archivo. Archivo de clase o un conjunto de archivos. Class.

2. c. 2. C. Variables are one place to store information; later you'll learn about others such
as arrays and constants. Las variables son un lugar para almacenar información, más tarde
usted aprenderá acerca de otros, tales como matrices y constantes. Weebles wobble but
they don't fall down, and comments are text in a program that the compiler ignores.
Weebles bamboleo, pero no se caen, y los comentarios son de texto en un programa que
el compilador ignora.

3. b. 3. B. Because errors in a computer program are called bugs, fixing those errors is
called debugging. Debido a errores en un programa de computadora son llamados bugs,
que se fijan los errores se denomina depuración. Some programming tools come with a
feature called a debugger that helps you fix errors. Algunas herramientas de programación
vienen con una función llamada un depurador que ayuda a corregir los errores.
Activities Actividades
If you'd like to explore the topics covered in this hour a little more fully, try the following
activities: Si desea explorar los temas tratados en esta hora un poco más a fondo, pruebe las
siguientes actividades:
 Write a program for megamillionaires: Calculate the amount the national debt increases in
a week. Escribir un programa para megamillionaires: Calcular la cantidad que el aumento
de la deuda nacional en una semana.
 Go back to the program and add one or two errors. Ir de nuevo al programa BigDebt y
añadir uno o dos errores. For example, take a semi-colon off the end of a line, or change
the line that reads into . Por ejemplo, tomar un punto y coma fuera de la final de una
línea, o cambiar la línea que dice BigDebt clase {{en bigDebt clase. Save the
program and try to compile it. Guarde el programa y tratar de compilar. Compare the
error messages you get to the errors you caused. Comparación de los mensajes de error
que llegue a los errores que causaron.
 3 horas
o De vacaciones en Java
 Primera parada: JavaSoft
 Figura 3.1.
 Una breve historia de Java
 Ir a la escuela con Java
 Figura 3.2.
 Almuerzo en JavaWorld
 Figura 3.3.
 Teniendo en un partido de béisbol en el estadio instantánea
 Figura 3.4.
 Hablemos de negocios
 Figura 3.5.
 Venir a Gamelan para hacerle llegar
 Figura 3.6.
 Un gran final con castañuelas
 Figura 3.7.
 Taller: Poner Java en el escritorio
 Figura 3.8.
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades
Hour 3 3 horas

Vacationing in Java De vacaciones en Java

" Java is a huge opportunity for all of us ." "Java es una gran oportunidad para todos
nosotros."

--Marc Andreesen of Netscape at the JavaOne Conference, May 31, 1996 - Marc
Andreesen de Netscape en la Conferencia JavaOne, 31 de mayo 1996

Before you venture further into Java programming, it's worthwhile to learn more about the
language and see what Java programmers are doing today. Antes de aventurarse más en la
programación Java, vale la pena aprender más sobre la lengua y ver lo que los
programadores de Java están haciendo hoy. One of the reasons that Java has become
popular quickly is that it can be used to offer programs on the World Wide Web. Una de las
razones por las que Java se ha convertido rápidamente popular es que puede ser utilizado
para ofrecer programas en el World Wide Web. Because of this capability, the best
examples of how to use Java are also on the Web. Debido a esta capacidad, los mejores
ejemplos de cómo usar Java también se encuentran en la Web. During this hour, we'll take
a look at some sites that feature Java programs and talk about the history and development
of the language. Durante esta hora, vamos a echar un vistazo a algunos sitios que ofrecen
programas en Java y hablar sobre la historia y el desarrollo de la lengua.

To go on this vacation, you need a Web browser that can handle Java programs. Para ir en
estas vacaciones, usted necesita un navegador web que puede manejar los programas de
Java. Most current versions of Netscape Navigator and Microsoft Internet Explorer can run
Java programs that are found on Web pages. La mayoría de las versiones actuales de
Netscape Navigator y Microsoft Internet Explorer puede ejecutar programas Java que se
encuentran en las páginas Web.

If you're using a current version of Netscape Navigator or Microsoft Internet Explorer and
it isn't working with Java programs, check your setup configuration from one of the
program's pull-down menus (select | in Internet Explorer or | | in Navigator). Si está
utilizando una versión actual de Netscape Navigator o Microsoft Internet Explorer y no
funciona con los programas Java, revise su configuración de la instalación de un programa
de tirar hacia abajo el menú (seleccione Ver | Opciones de Internet Explorer o en Opciones
| Red Preferencias | Idiomas en el Navegador). Make sure your browser software is
configured to run Java programs. Asegúrese de que su navegador está configurado para
ejecutar programas Java.
Load your browser software of choice, put on your best Hawaiian shirt, and get ready to
vacate. Cargue el software del navegador de su elección, se puso su mejor camisa
hawaiana, y prepárate para desalojar. Because you won't be leaving your house, you won't
get a chance to experience the simpler pleasures of tourism: odd driving rituals, exotic food,
exotic members of the opposite sex, exotic members of the opposite sex with food, and so
on. Debido a que no se salir de su casa, usted no tendrá la oportunidad de experimentar los
placeres más simples del turismo: los rituales extraños de prácticas, comida exótica, los
miembros exóticos del sexo opuesto, los miembros exóticos del sexo opuesto con la
comida, y así sucesivamente. But look on the bright side: no antibacterial shots, traveler's
checks, or passports are required either. Pero mira el lado bueno: no hay vacunas
antibacterianas, cheques de viaje o pasaportes se requieren tampoco.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 A definition of the Java language Una definición del lenguaje Java


 The benefits of using Java Las ventajas de usar Java
 Some examples of Java at work Algunos ejemplos de Java en el trabajo
 An explanation of object-oriented programming Una explicación de la programación
orientada a objetos
 Sites of note for Java programmers Sitios de la nota para los programadores de Java

The Web site-seeing examples that you visit during this hour's vacation are just a small
sampling of the Java programs in use on the Web. Los ejemplos ver sitio Web que usted
visita durante las vacaciones de esta hora son sólo una pequeña muestra de los programas
de Java en uso en la Web. A search of the AltaVista Web search database finds more than
4,900 pages that have included a Java program as of this writing. Una búsqueda en la base
de datos de búsqueda de AltaVista Web encuentra más de 4.900 páginas que han incluido
un programa Java a partir de este escrito.

First Stop: JavaSoft Primera parada: JavaSoft


The Java vacation begins at a place you'll be visiting regularly now that you're a Java
programmer: the Web site of JavaSoft, the group that developed the Java language. Las
vacaciones de Java comienza en un lugar que va a visitar con regularidad ahora que usted
es un programador de Java: el sitio Web de JavaSoft, el grupo que desarrolló el lenguaje
Java. To get there, go to the following address: Para llegar allí, ir a la siguiente dirección:

http://java.sun.com

JavaSoft is the division of Sun Microsystems that is responsible for the advancement of the
Java language and the development of related software. JavaSoft es la división de Sun
Microsystems, que es responsable de la promoción del lenguaje Java y el desarrollo de
software relacionado. To see a simple example of Java in action, choose the hyperlink on
the JavaSoft main page that offers a "Java version" of the site. Para ver un ejemplo sencillo
de Java en acción, elija el enlace en la página de JavaSoft principal que ofrece una "versión
de Java" del sitio. If you can't find one, you can reach the Java front page by visiting the
following Web address: Si no puede encontrar uno, se puede llegar a la página principal de
Java, visite la siguiente página web:

http://java.sun.com:81/index.html?

A Java program is used on this page to add pull-down menus on top of the page. Un
programa Java se utiliza en esta página para agregar menús desplegables en la parte
superior de la página. Drag your mouse across the different section titles on the page to see
the pull-down menus that appear. Arrastra el ratón a través de los títulos de sección
diferente de la página para ver los menús desplegables que aparecen. Figure 3.1 shows a
pull-down menu that appears when the mouse is over the text. Figura 3.1 muestra un menú
desplegable que aparece cuando el ratón está sobre el ¿Dónde puedo leer sobre ...?
Texto.

Figura 3.1. The JavaSoft Web site uses a Java program to add pull-down menus on top of
a Web page. El sitio Web de JavaSoft utiliza un programa Java para agregar menús
desplegables en la parte superior de una página Web.

This Web site is the place to find the latest released versions of the Java Developer's Kit, as
well as other programmer's resources. Este sitio Web es el lugar para encontrar las últimas
versiones del Kit de Desarrollo Java, así como los recursos de otro programador. This site
also has press releases about Java-related products, full documentation for Java, and sample
Java programs that run on the Web. Este sitio también tiene notas de prensa acerca de los
productos relacionados con Java, la documentación completa para Java, y muestra los
programas de Java que se ejecutan en la Web. Sun Microsystems made Java available for
free via this Web site in late 1995. Sun Microsystems hace de Java disponible de forma
gratuita a través de este sitio Web a finales de 1995.

A Brief History of Java Una breve historia de Java

Company cofounder Bill Joy called Java the end result of 15 years of work to produce a
better, more reliable way to write computer programs. Cofundador de la empresa de Bill
Joy llamado Java el resultado final de 15 años de trabajo para producir una forma mejor y
más fiable para escribir programas de ordenador. Java's creation was a little more
complicated than that. la creación de Java fue un poco más complicado que eso.

Java was invented five years ago by Sun engineer James Gosling as a language to use as the
brains for smart appliances (interactive TVs, omniscient ovens, and the like). Java fue
inventado hace cinco años por Sun ingeniero James Gosling como un lenguaje que se
utiliza como cerebros de electrodomésticos inteligentes (TV interactiva, hornos
omnisciente, y similares). Gosling was unhappy with the results he was getting by writing
programs with C++, another programming language, so he holed up in his office and wrote
a new language to better suit his needs. Gosling no estaba contento con los resultados que
se estaba escribiendo programas en C + +, otro lenguaje de programación, por lo que
encerrado en su despacho y escribió un nuevo lenguaje para satisfacer mejor sus
necesidades.

Most people who are holed up in their office aren't producing new programming languages
or other achievements. La mayoría de las personas que están atrincherados en sus oficinas
no están produciendo nuevos lenguajes de programación o de otros logros. They're playing
Quake. Están jugando Quake. How many lasting contributions to mankind have been lost
because of Id Software? ¿Cuántas contribuciones duraderas a la humanidad se han perdido
a causa de Id Software?

At the time, Gosling named his language Oak after a tree he could see from his office
window. En ese momento, Gosling nombró a su idioma de roble de un árbol que podía ver
desde la ventana de su oficina. The language was part of Sun's strategy to make millions
when interactive TV became a multimillion-dollar industry. El lenguaje era parte de la
estrategia de Sun para hacer millones, cuando la televisión interactiva se convirtió en una
industria multimillonaria. That still hasn't happened today (five years down the road), but
something completely different took place. Que aún no ha sucedido hoy (cinco años en el
camino), sino algo completamente diferente se llevó a cabo. Just as Sun was ready to scrap
Oak development and scatter its workers to other parts of the company, the World Wide
Web became popular. Al igual que Sol era listo para el desguace de desarrollo de Roble y la
dispersión de sus trabajadores a otras partes de la empresa, la World Wide Web se hizo
popular.

In a fortuitous circumstance, many of the qualities that made Gosling's language good on its
appliance project made it suitable for adaptation to the World Wide Web. En una
circunstancia fortuita, muchas de las cualidades que hicieron un buen lenguaje de Gosling
en su proyecto aparato hizo propicio para la adaptación a la World Wide Web. Sun
developers devised a way for programs to be run safely from Web pages and chose a catchy
new name to accompany the language's new focus: Java. desarrolladores de Sun ideado una
manera para que los programas se ejecutan de forma segura desde las páginas web y elegir
un nombre pegadizo nuevo para acompañar a la lengua de nuevo enfoque: Java.

You might have heard that Java is an acronym that stands for Just Another Vague
Acronym. Usted puede haber oído que Java es un acrónimo que significa Acrónimo de Just
Another Vague. You also might have heard that it was named for the developers' love of
coffee, especially the percolating product of a shop near Sun's offices. Es posible que
también han oído que fue nombrado por el amor de los desarrolladores de café, sobre todo
el producto se filtre de una tienda cerca de las oficinas de Sun. Actually, the story behind
Java's naming contains no secret messages or declarations of liquid love. En realidad, la
historia detrás de nombres de Java no contiene mensajes secretos o declaraciones de amor
líquido. Instead, Java was chosen for the same reason that comedian Jerry Seinfeld likes to
say the word salsa. En cambio, Java fue elegido por la misma razón que el comediante Jerry
Seinfeld le gusta decir la palabra salsa. It sounds cool. Suena genial.

Although Java can be used for many other things, the Web provided the showcase that it
needed to capture international attention. Aunque Java puede ser usado para muchas otras
cosas, la Web siempre que el escaparate que es necesario para captar la atención
internacional. A programmer who puts a Java program on a Web page makes it instantly
accessible to the entire Web-surfing planet. Un programador que pone a un programa Java
en una página web hace que sea accesible al instante a todo el planeta navegar en la web.
Because Java was the first tool that could offer this capability, it became the first computer
language to receive as much press as Dennis Rodman, Madonna's baby, and the alien
autopsy. Debido a que Java es la primera herramienta que puede ofrecer esta capacidad, se
convirtió en el lenguaje de programación primeros en recibir tanta publicidad como Dennis
Rodman, el bebé de Madonna, y la autopsia alienígena. In 1996, you had to be in solitary
confinement or a long-term orbital mission to avoid hearing about Java. En 1996, había que
ser en régimen de aislamiento o de una misión orbital a largo plazo para evitar escuchar
acerca de Java.

Going to School with Java Ir a la escuela con Java


As a medium that offers a potential audience of millions, the World Wide Web includes
numerous resources for educators and schoolchildren. Como un medio que ofrece una
audiencia potencial de millones, la World Wide Web incluye numerosos recursos para los
educadores y los escolares. Because Java programs can offer a more interactive experience
than standard Web pages, some programmers have used the language to write learning
programs for the Internet. Dado que los programas Java pueden ofrecer una experiencia
más interactiva que páginas Web estándar, algunos programadores han utilizado el lenguaje
para escribir los programas de aprendizaje para Internet.

For one of the strongest examples of this use of Java, visit the following address: Para uno
de los principales ejemplos de este uso de Java, visite la siguiente dirección:

http://www.npac.syr.edu/projects/vishuman/VisibleHuman.html

This Web site uses data from the National Library of Medicine's Visible Human Project.
Este sitio Web utiliza los datos de la Biblioteca Nacional de Medicina visible del proyecto
Humanos. The project is a database of thousands of cross-sectional images of human
anatomy. El proyecto es una base de datos de miles de imágenes de cortes transversales de
la anatomía humana. A Java program is being used to enable users to search the collection
and view images. Un programa Java se utiliza para permitir a los usuarios buscar en la
colección de imágenes y ver. Instead of making requests by text commands, users make the
requests to see different parts of the body graphically, and the results are shown
immediately in graphic detail. En lugar de hacer peticiones de comandos de texto, los
usuarios que las solicitudes para ver las diferentes partes del cuerpo gráfica, y los resultados
se muestran inmediatamente en detalle gráfico. The Java program is shown in Figure 3.2.
El programa Java se muestra en la Figura 3.2.

Figura 3.2. Images from the National Library of Medicine's Visible Human Project can be
viewed interactively on the Web using a Java program. Imágenes de la Biblioteca Nacional
de Medicina del Proyecto Humano Visible se puede ver de forma interactiva en la Web
mediante un programa Java.

Numerous educational programs are available for many different computer systems, but
what makes this program remarkable is its versatility. Numerosos programas educativos
están disponibles para muchos sistemas informáticos diferentes, pero lo que hace este
programa destacable es su versatilidad. The Visible Human Project tool is similar in
function and performance to CD-ROM software that users might run on their computer
systems. El Proyecto Humano Visible herramienta es similar en funcionalidad y desempeño
con el software de CD-ROM que los usuarios pueden ejecutar en sus sistemas informáticos.
However, it is run directly from a Web page. Sin embargo, se ejecuta directamente desde
una página Web. No special installation is needed, and unlike most CD-ROM software, it
isn't limited to PC-compatible and Macintosh systems. Ninguna instalación especial que se
necesita, ya diferencia de la mayoría del software de CD-ROM, no se limita a los sistemas
compatibles con PC y Macintosh. Just like Web pages, Java programs can be run on any
computer system that can handle them. Al igual que las páginas Web, programas de Java se
puede ejecutar en cualquier sistema informático que puede manejar.

In order to handle Java programs, a Web browser must have a Java interpreter. Con el fin
de manejar los programas de Java, un navegador de Internet debe tener un intérprete de
Java. The interpreter included with a browser serves a similar function as the interpreter
that you used to run the program during Hour 2, "Writing Your First Program." El
intérprete incluye un navegador cumple una función similar a la del intérprete que utilizó
para ejecutar el programa BigDebt durante horas 2, "Escribiendo tu primer programa." The
difference is that a browser's interpreter can only run Java programs that are set up to run
on Web pages and cannot handle programs set up to run from the command line. La
diferencia es que el intérprete de un navegador sólo pueden ejecutar programas Java que
están preparados para funcionar en las páginas Web y no puede manejar programas creados
a partir de la línea de comandos. Currently, Java-enabled browsers are available for most
common systems, including PCs running a version of Microsoft Windows, Apple
Macintosh systems, SPARC workstations, and computers running the Linux operating
system. En la actualidad los navegadores, Java están disponibles para la mayoría de los
sistemas comunes, incluyendo PCs ejecutando una versión de Microsoft Windows, sistemas
Apple Macintosh, estaciones de trabajo SPARC, y los equipos que ejecutan el sistema
operativo Linux.

A Java program such as the Visible Human Project database does not have to be written for
a specific computer system. Un programa Java como la base de datos Visible Human
Project no tiene que ser por escrito para un sistema informático específico. This advantage
is called platform independence. Esta ventaja se llama independencia de la plataforma. Java
was created to work on multiple systems. Java fue creado para trabajar en varios sistemas.
Originally, Java's developers believed it needed to be multiplatform because it would be
used on a variety of appliances and other electronic devices. Originalmente, los
desarrolladores de Java creía que necesitaba para ser multiplataforma, ya que sería utilizado
en una variedad de aparatos y otros dispositivos electrónicos.

The programs that you write using Java can be run on a variety of computer systems
without requiring any extra work from you. Los programas que se escribe en Java se puede
ejecutar en una variedad de sistemas informáticos sin necesidad de ningún trabajo adicional
de usted. This advantage is one of the primary reasons that so many people are learning to
write Java programs and are using them on software projects. Esta ventaja es una de las
principales razones de que tantas personas están aprendiendo a escribir programas Java y
los están utilizando en proyectos de software. Many professional software companies are
using Java for the same reason. Muchas compañías de software profesional están usando
Java por la misma razón. Under the right circumstances, Java can remove the need to create
specific versions of a program for different computer systems. Bajo las circunstancias
adecuadas, Java puede eliminar la necesidad de crear versiones específicas de un programa
para los sistemas informáticos diferentes. The potential audience for software grows with a
multiplatform solution such as Java. El público potencial para el software crece con una
solución multiplataforma como Java.

Lunch in JavaWorld Almuerzo en JavaWorld


If you didn't lose your appetite after searching through the innards of a visible human, take
a lunch break with JavaWorld, an online magazine for Java programmers and other Internet
developers. Si usted no pierde el apetito después de buscar a través de las entrañas de un ser
humano visible, tome un descanso para almorzar con JavaWorld, una revista en línea para
los programadores de Java y otros desarrolladores de Internet. The JavaWorld Web site is
available at the following address: El sitio JavaWorld Web está disponible en la siguiente
dirección:

http://www.javaworld.com
JavaWorld offers how-to articles, news stories related to Java development, and other
features in each monthly edition. JavaWorld ofrece artículos sobre procedimientos, las
noticias relacionadas con el desarrollo de Java, y otras características en cada edición
mensual. One of the advantages of the publication's Web format is that it can display
functional Java programs in conjunction with articles. Una de las ventajas del formato Web
de la publicación es que se puede mostrar funcional de los programas de Java, en relación
con los artículos. Figure 3.3 shows a working example from a tutorial on Java animation
programming. Figura 3.3 muestra un ejemplo práctico de un tutorial sobre la programación
de animación Java.

Figura 3.3. A JavaWorld how-to article on Java animation programming includes a


working example of a program. Un JavaWorld cómo-al artículo sobre la programación de
animación Java incluye un ejemplo práctico de un programa.

In addition to offering information of benefit to Java programmers, JavaWorld publishes


articles and commentary about the language and its development. Además de ofrecer la
información en beneficio de los programadores de Java, JavaWorld publica artículos y
comentarios acerca del lenguaje y su desarrollo. One issue that has been hotly debated since
Java's release is whether the language is secure. Un tema que ha sido muy debatido desde el
lanzamiento de Java es si el lenguaje es seguro. Security is important because of the way
Java programs work when they are placed on a Web page. La seguridad es importante
debido a la forma de programas Java funcionan cuando se colocan en una página Web. The
Java programs that you have tried during this hour were downloaded to your computer first.
Los programas Java que se han tratado durante esta hora se han descargado en su
ordenador. When the program was finished downloading, it ran on your computer. Cuando
el programa fue terminado la descarga, que corrió en el equipo. It was as though someone
sat down at your computer, popped in a disk, and ran his own program. Era como si alguien
se sentó a su computadora, apareció en un disco, y corrió su propio programa.

Unless you know a whole lot of people, most of the Web pages you visit will be published
by strangers. A menos que usted sabe un montón de personas, la mayoría de las páginas
Web que visita será publicado por extraños. In terms of security, running their programs
isn't a lot different than letting the general public use your computer on weekends. En
términos de seguridad, la gestión de sus programas no es muy diferente a dejar que el
público en general utilizar el ordenador los fines de semana. If the Java language did not
have safeguards to prevent abuse, its programs could introduce viruses onto your system,
delete files, and do other malicious things. Si el lenguaje Java no tienen garantías para
evitar abusos, sus programas pueden introducir virus en su sistema, borrar archivos, y hacer
otras cosas maliciosas. Java includes several different types of security to make sure that its
programs are safe when run from Web pages. Java incluye varios tipos diferentes de
seguridad para asegurarse de que sus programas son seguros cuando se ejecuta desde las
páginas Web.

The main security is provided by the following restrictions on Java programs running over
the Web: La principal es la seguridad proporcionada por las siguientes restricciones sobre
los programas de Java que se ejecuta a través de Internet:

 No program can open, read, write, or delete files on the user's system. Ningún programa
puede abrir, leer, escribir o borrar archivos en el sistema del usuario.
 No program can run other programs on the user's system. Ningún programa puede
ejecutar otros programas en el sistema del usuario.
 All windows created by the program will be identified clearly as Java windows. Todas las
ventanas creadas por el programa serán identificados claramente como las ventanas de
Java. This identification prevents someone from creating a fake window asking for the
user's name and password. Esta identificación impide que alguien de la creación de una
ventana falsa que pide el nombre del usuario y la contraseña.
 Programs cannot make connections to Web sites other than the one they came from. Los
programas no pueden hacer conexiones con otros sitios Web que el que viene.
 All programs will be verified to make sure that nothing was modified after they were
compiled. Todos los programas serán verificadas para asegurarse de que nada se modificó
después de que fueron recopilados.

At this time, the general consensus among Java developers is that the language has enough
safeguards in place to be usable over the Web. En este momento, el consenso general entre
los desarrolladores de Java es que el lenguaje dispone de garantías suficientes en el lugar
para ser utilizable en la Web. Several security holes have been found, often by
programming security experts, and these holes have been dealt with quickly by Sun or the
Web browser programmers. Varios agujeros de seguridad se han encontrado, a menudo por
los expertos en seguridad de programación, y estos agujeros se han tratado con rapidez por
el Sol o los programadores del navegador web. Because JavaWorld covers the latest news
of note in the Java development community, it is a good way to keep track of any security
issues that arise. Debido a JavaWorld cubre las últimas noticias de la nota en la comunidad
de desarrollo Java, es una buena manera de hacer un seguimiento de cualquier problema de
seguridad que se plantean.

Caution: None of the safeguards in place are a complete block against malicious programs.
Precaución: Ninguna de las salvaguardias en el lugar son un bloque completo contra los programas
maliciosos. Just as loopholes were found in the past year, more will undoubtedly be found in the
future. Al igual que las lagunas se encuentran en el último año, más, sin duda, se encontrarán en el
futuro. If you are concerned about running Java programs through your Web browser, you might
want to run programs only from a source such as Gamelan because it tests the programs before
including them in the directory. Si usted está preocupado acerca de cómo ejecutar programas Java
a través de su navegador de Internet, es posible que desee ejecutar programas sólo de una fuente
como Gamelan, ya que las pruebas de los programas antes de incluirlos en el directorio. You also
should back up anything you can't afford to lose on your computer, which is good practice for
anyone who runs programs received from the Internet. También debería respaldar cualquier cosa
que usted no puede permitirse el lujo de perder en su equipo, que es una buena práctica para
cualquier persona que lleva a cabo programas recibidos desde Internet.

Taking in a Ball Game at Instant Ballpark Teniendo en un partido de béisbol en el


estadio instantánea
The first afternoon stop on the Java tour will be a trip to the old ball game. La parada de la
tarde por primera vez en la gira de Java será un viaje para el juego de pelota de edad.
Instant Sports, a Texas company that provides sports reporting information, is using Java to
present baseball games as they happen in a visual, pitch-by-pitch fashion. Instantánea
Deportes, una compañía de Texas que proporciona la información deportiva de la
información, es utilizar Java para presentar los juegos de béisbol a medida que ocurren de
una manera visual, el tono-por la moda de paso. To see how baseball is played in
cyberspace, visit the following address: Para ver cómo el béisbol se juega en el
ciberespacio, visite la siguiente dirección:

http://www.instantsports.com/

The Java program called Instant Ballpark presents each pitch in a major league game. El
programa Java llamada instantánea Estadio presenta cada paso en un juego de Grandes
Ligas. The ball travels from the pitcher's icon to the batter and goes out to the fielders when
it's hit. La pelota viaja desde el icono del lanzador al bateador y sale a los jardineros cuando
es golpeado. Sound effects, such as the umpire's strike call and the ball hitting the bat, also
are presented. Los efectos de sonido, tales como la convocatoria de huelga del árbitro y la
pelota golpea el bate, también se presentan.

The program is a unique way to follow live games and past games that are available from
the Instant Ballpark archive. El programa es una forma única de seguir los partidos en
directo y los juegos anteriores que están disponibles en el estadio de béisbol instantánea de
archivo. Figure 3.4 shows the last play in a game between the Chicago White Sox and the
Seattle Mariners from the 1996 season. Figura 3.4 muestra la última jugada en un partido
entre los Medias Blancas de Chicago y los Marineros de Seattle desde la temporada de
1996.

Figura 3.4. Mariners shortstop Alex Rodriguez drives home the winning run in Instant
Ballpark, a presentation of a live baseball game using a Java program . Marineros
torpedero Alex Rodríguez lleva a casa la carrera del triunfo en el estadio de béisbol
instantánea, la presentación de un partido de béisbol en vivo usando un programa Java.

One of the things that you might notice about Instant Ballpark is that it updates the day's
scores in other games as you are using the program to follow a game. Una de las cosas que
usted podría notar acerca de Instant estadio de béisbol es que se actualiza resultados del día
en otros juegos como usted está utilizando el programa para seguir un juego. This update is
relatively easy to do because the Java language is multithreaded. Esta actualización es
relativamente fácil de hacer porque el lenguaje Java es multiproceso. Multithreading is a
way for the computer to do more than one thing at the same time. Multithreading es una
manera para que el equipo haga más de una cosa al mismo tiempo. One part of a program
takes care of one task, another part takes care of a different task, and the two parts can pay
no attention to each other. Una parte de un programa se encarga de una tarea, otra parte se
encarga de una tarea diferente, y las dos partes puede no prestar atención el uno al otro.
Each part of a program in this example is called a thread. Cada parte de un programa en
este ejemplo se llama un hilo.

In a program such as Instant Ballpark, the league scoreboard along one side of the window
could run in its own thread. En un programa como Instant estadio de béisbol, el marcador
de la liga a un lado de la ventana podía correr en su propio hilo. The rest of the program
could be another thread. El resto del programa podría ser otro hilo. If you use an operating
system such as Microsoft Windows 95, you're using a type of this behavior when you run
more than one program at the same time. Si utiliza un sistema operativo, como Microsoft
Windows 95, que está utilizando un tipo de este comportamiento al ejecutar varios
programas al mismo tiempo. If you're at work and you surf the Web for European aerobics
videos in one window while running a company sales report in another window,
congratulate yourself--you're multithreading! Si estás en el trabajo y navegar por la web de
vídeos de aeróbic Europea en una ventana mientras se ejecuta un informe de ventas de la
compañía en otra ventana, te felicito - multithreading you're!

Getting Down to Business Hablemos de negocios


At this point in your travels, you might be getting the impression that Java is primarily of
use to baseball fans and those who have body parts to show the world. En este punto de su
visita, usted puede estar recibiendo la impresión de que Java es principalmente útil para los
fanáticos del béisbol y los que tienen partes del cuerpo para mostrar al mundo. Although
those two subject areas are enough to keep most of us entertained for hours, the next stop
on our trip shows an example of Java getting down to business. Aunque los dos temas son
suficientes para mantener a la mayoría de nosotros entretenido durante horas, la siguiente
parada de nuestro viaje se muestra un ejemplo de Java de entrar en materia.

Direct your Web browser to the following address: Dirija su navegador Web a la siguiente
dirección:

http://www.engine.com/java/engbrowse/Employee.html

This example is an employee payroll database managed as a pair of Java programs. Este
ejemplo es una base de datos de nómina de los empleados gestionan como un par de
programas Java. Employee information is viewed in one program, and the other program is
used to edit items from the payroll record of a specific employee. información de los
empleados es visto en un programa, y el otro programa se utiliza para editar los artículos de
los registros de nómina de un empleado específico. Figure 3.5 shows Bart Simpson's record
as it is being edited. Figura 3.5 muestra los registros de Bart Simpson, ya que se está
editando.

Unlike other payroll tracking systems that require the installation of software on the
computers of each employee who needs access, the use of Java enables Software Engine to
make the program available to any employee with a Web browser. A diferencia de la
nómina de otros sistemas de seguimiento que requieren la instalación de software en los
ordenadores de cada empleado que necesita tener acceso, el uso de Java permite a software
del motor para hacer el programa a disposición de cualquier empleado con un navegador
Web. With some kind of password security system in place, the program could even be
used by employees who are away from the office on business trips. Con algún tipo de
sistema de contraseña de seguridad en su lugar, el programa podría incluso ser utilizado por
los empleados que están fuera de la oficina de viajes de negocios. All the employees would
have to do is access the company's Web site. Todos los empleados tendrían que hacer es
acceder al sitio web de la compañía.

Figura 3.5. A Java program from Software Engine that is used to maintain employee
payroll records. Un programa Java de Software del motor que se utiliza para mantener la
nómina de los registros de empleados.

A database program such as Software Engine's can be thought of in several different ways.
Un programa de base de datos como de software del motor puede ser pensado de varias
maneras diferentes. One way is to think of a program as an object--something that exists in
the world, takes up space, and has certain things it can do. Una forma es pensar en un
programa como un objeto - algo que existe en el mundo, ocupa un espacio, y tiene ciertas
cosas que puede hacer. Java, like the C++ language, uses object-oriented programming, as
you will see during Hour 10, "Creating Your First Object." Java, como el lenguaje C + +,
utiliza la programación orientada a objetos, como se verá durante la hora 10, "Creación de
su primer objetivo." Object-oriented programming (OOP) is a way of thinking about
computer programs. Programación orientada a objetos (POO) es una forma de pensar
acerca de los programas de ordenador. A program is thought of as a group of objects. Un
programa se considera como un grupo de objetos. Each object handles a specific task and
knows how to speak to other objects. Cada objeto se ocupa de una tarea específica y sabe
cómo hablar a otros objetos. For example, a word-processing program could be set up as
the following group of objects: Por ejemplo, un procesador de textos se podría establecer
que el grupo de objetos siguientes:
 A document object, which is the area where you type in text Un objeto de documento,
que es la zona donde se escribe en el texto
 A spell-checking object, which can look over the document object to find any possible
spelling errors Un objeto de corrección ortográfica, que puede mirar por encima del
objeto de documento para encontrar los errores de ortografía posibles
 A printer object, which handles the printing of the document Un objeto de impresora, que
se encarga de la impresión del documento
 A menu object, a mouse object, and many others Un objeto de menú, un objeto del ratón,
y muchos otros

Each of these objects is an independent computer program that doesn't need the others to do
its job. Cada uno de estos objetos es un programa de computadora independiente que no
necesita a los demás a hacer su trabajo. The word-processing software is a collection of all
the objects necessary to get work done. El software de procesamiento de texto es una
colección de todos los objetos necesarios para realizar su trabajo.

OOP is a powerful way to create programs and it makes the programs you write more
useful. Programación orientada a objetos es una forma eficaz de crear programas y hace
que los programas que escribir más útil. Consider the word-processing software. Considere
el software de procesamiento de textos. If the programmer wants to use the spell-checking
capabilities of that program with some other software, the spell-checking object is ready for
use with the new program. Si el programador quiere utilizar las funciones de corrección
ortográfica de dicho programa con algún otro software, el objeto de la corrección
ortográfica está listo para su uso con el nuevo programa. No changes need to be made. No
hubo cambios deben hacerse.

Stopping by Gamelan to Ask Directions Venir a Gamelan para hacerle llegar


This world tour of Java programs is being led by a professional who is well-versed in the
hazards and highlights of Web-based travel. Esta gira mundial de los programas de Java
está siendo dirigida por un profesional que está bien versado en los peligros y los aspectos
más destacados de viajes basado en la Web. You'll be venturing out on your own trips soon,
so it's worthwhile to stop at the best tour guide currently available for the Java-hungry
tourist, the Gamelan Web site: Estarás de salir de su propios viajes pronto, así que vale la
pena detenerse en la mejor guía turística disponible actualmente para el turista ávido de
Java, el sitio Web de Gamelan:

http://www.gamelan.com

Gamelan is the most comprehensive directory of Java programs, programming resources,


and other information related to the language. Gamelan es el directorio más completo de los
programas de Java, los recursos de programación, y otra información relacionada con la
lengua. Most of the programs visited during this hour were originally found on a trek
through the searchable database maintained by Gamelan. La mayoría de los programas
visitados durante esta hora se encuentran originalmente en una caminata a través de la base
de datos gestionada por Gamelan. Updates are made on a daily basis, so this is another
place that you'll be visiting often as you develop your Java programming skills. Las
actualizaciones se realizan a diario, por lo que este es otro lugar que usted va a visitar a
menudo como a desarrollar sus habilidades de programación Java.

One of the best uses of Gamelan for programmers is to see what programs are available that
offer source code. Uno de los mejores usos de Gamelan para los programadores es ver qué
programas están disponibles que ofrecen el código fuente. In case you're unfamiliar with
the term, source code is another name for the text files that are used to write computer
programs. En caso de que usted no está familiarizado con el término, el código fuente es
otro nombre para los archivos de texto que se utilizan para escribir programas de
ordenador. The file that you created during Hour 2, "Writing Your First Program," is an
example of source code. El archivo BigDebt.java que creó durante horas 2, "Escribiendo
tu primer programa," es un ejemplo de código fuente.

Gamelan's directory listings indicate when a compiled Java program is accompanied by the
source code used to create it. Gamelan listados de directorio de indicar cuando un programa
compilado de Java es acompañado por el código fuente utilizado para crearlo. After you
have finished your first 24 hours as a Java programmer, you ought to take a look at some of
these programs. Después de haber terminado su primeras 24 horas como programador Java,
debería echar un vistazo a algunos de estos programas. Figure 3.6 shows a Java program
being used on Gamelan to provide instant access to the different areas that comprise the
site. Figura 3.6 muestra un programa en Java que se utiliza en Gamelan para proporcionar
acceso instantáneo a las diferentes áreas que componen el sitio.

Figura 3.6. The Gamelan directory offers more than 4,000 Java resources and links to
programs. El directorio Gamelan ofrece más de 4.000 recursos de Java y los enlaces a los
programas. It uses this Java program as a navigational aid. Utiliza este programa Java
como una ayuda a la navegación.

The large number of programs listed in Gamelan show that the language has been adopted
quickly by thousands of programmers around the world. El gran número de programas que
figuran en el show de Gamelan que el lenguaje ha sido adoptado rápidamente por miles de
programadores de todo el mundo. Part of the reason is that Java's popularity inspires people
to learn it, which is the same principle that caused parachute pants and breakdancing to be
briefly popular in the mid-'80s. Parte de la razón es que la popularidad de Java inspira a la
gente a aprender, que es el mismo principio que causó pantalones de paracaídas y el
breakdance a ser brevemente populares a mediados de los años 80. Another reason for the
swiftly growing population of Java programmers is the simplicity of the language. Otra
razón para la población rápidamente creciente de programadores de Java es la simplicidad
de la lengua.
One of the goals of Java's design was to make it easier to learn than C++, the language
James Gosling was having fits with on Sun's smart-appliance project. Uno de los objetivos
de diseño de Java era más fácil de aprender que C + +, el lenguaje de James Gosling tenía
encaja con el proyecto de Sun inteligente aparato. Much of Java is based on C++, so
programmers who have learned to use that language will find it easier to learn Java. Gran
parte de Java está basado en C + +, por lo que los programadores que han aprendido a
utilizar el idioma será más fácil para aprender Java. However, some of the elements of C++
that are the hardest to learn--and the hardest to use correctly--have been removed from
Java. Sin embargo, algunos de los elementos de C + + que son los más difíciles de aprender
- y la más difícil de utilizar correctamente - se han quitado de Java.

For people who are learning programming for the first time, Java is easier to learn than C++
would be. Para las personas que están aprendiendo de programación, por primera vez, Java
es más fácil de aprender que C + + sería. Also, Java will not work if its variables and other
elements of a program are used incorrectly. Además, Java no funcionará si sus variables y
otros elementos de un programa se utilizan incorrectamente. This adherence to rules can be
painful for experienced programmers, but it forces everyone to develop good habits as they
create programs. Esta adherencia a las normas pueden ser dolorosas para los programadores
con experiencia, pero obliga a todos a desarrollar buenos hábitos, ya que crean los
programas.

Some languages are created to make it easier for experienced programmers to harness the
capabilities of the computer in their programs by including shortcuts and other features that
programming veterans easily understand. Algunos idiomas se crean para facilitar a los
programadores con experiencia para aprovechar las capacidades de la computadora en sus
programas mediante la inclusión de los accesos directos y otras características que los
veteranos de programación fácil de entender. Java does not use these features, preferring to
make the language as simple as an object-oriented programming language can be. Java no
utilizar estas funciones, prefiriendo hacer que el lenguaje tan simple como un lenguaje de
programación orientado a objetos puede ser. Java was created to be easy to learn, easy to
debug, and easy to use. Java fue creado para ser fácil de aprender, fácil de depurar, y fácil
de usar.

A Big Finish with Castanets Un gran final con castañuelas


The second-to-last stop on your Java vacation has a certain Caribbean flair to it--castanets,
marimbas, and bongos are involved. La segunda parada a la última en sus vacaciones de
Java tiene un cierto aire del Caribe para - castañuelas, marimbas, bongos y están
involucrados. If you packed a ruffly Cuban bandleader shirt just like the one Carmine
Ragusa used to wear on episodes of Laverne and Shirley, now's the best chance you'll ever
have to wear it. Si lleno de una camisa de líder de la banda ruffly cubana como el Carmine
Ragusa solía usar en los episodios de Laverne y Shirley, ahora es la mejor oportunidad que
nunca tendrá que usarlo. Visit the following Web address: Visita la siguiente página web:

http://www.marimba.com

Unlike the other sightseeing locations you have visited, this site can't be viewed with a Web
browser alone. A diferencia de los otros lugares turísticos que ha visitado, este sitio no
pueden ser vistos con un navegador Web solo. Marimba, a startup company formed by
several former Java developers at Sun, has used Java to create Castanet, a new way to
receive and run software over the Internet. Marimba, una compañía de lanzamiento
formado por varios ex desarrolladores de Java de Sun, Java ha utilizado para crear
Castañuelas, una nueva manera de recibir y ejecutar el software a través de Internet.

Castanet is a way to send out computer programs that automatically update themselves on
the computers of people who request them. Castañuelas es una forma de enviar los
programas de ordenador que automáticamente se actualicen en los equipos de personas que
lo soliciten. It's a service not unlike television, where you turn to a channel and
immediately start receiving the broadcast signal of that channel. Es un servicio que no
diferencia de la televisión, donde a su vez a un canal y de inmediato comenzará a recibir la
señal de emisión de ese canal. In fact, the Java programs sent by this method are called
channels. De hecho, los programas Java enviados por este método se llaman canales. Figure
3.7 shows a Castanet channel offered by Excite that presents the lineup of other channels
that are currently available. Figura 3.7 muestra un canal de Castañuelas ofrecidos por
Excite que presenta el cartel de otros canales que están disponibles actualmente. Like TV
listings, Excite's guide offers previews of each channel and a way to immediately request
them. Al igual que los otros listados de TV, la guía de Excite ofrece vistas previas de cada
canal y una forma de inmediato lo soliciten. If Excite updates its guide channel program,
Castanet sends that update automatically over the Internet. Si las actualizaciones Excite su
programa de canal de la guía, Castañuelas envía que se actualizan automáticamente a través
de Internet. No effort is required on the user's end to keep up with new versions of the
software. Ningún esfuerzo se requiere en el extremo derecho del usuario a mantenerse al
día con las nuevas versiones del software.

Figura 3.7. The Excite guide to Castanet channels, which itself is a channel. La guía Excite
a los canales de castañuelas, que a su vez es un canal.

Java is not able to send out its programs in this manner, so Castanet requires the use of
special software called the Tuner. Java no es capaz de enviar sus programas de esta manera,
por lo que Castañuelas requiere el uso de un software especial llamado el sintonizador. The
Castanet Tuner is a sophisticated Java program that runs from the command line. El
sintonizador de Castañuelas es un sofisticado programa de Java que se ejecuta desde la
línea de comandos. Although Netscape has announced plans to include the Tuner's
functionality in a future version of its software, this feature has not become available at the
time of this writing. Aunque Netscape ha anunciado sus planes para incluir la funcionalidad
del sintonizador en una futura versión de su software, esta característica no se dispone en el
momento de escribir este artículo. To find out more about downloading the Tuner for your
system, visit the following Web page: Para obtener más información acerca de cómo
descargar el sintonizador de su sistema, visite la siguiente página Web:

http://www.marimba.com/products/castanet-tuner.html

The Tuner is several megabytes in size, so you might not want to install it on your system
immediately. El sintonizador es de varios megabytes de tamaño, por lo que no puede ser
que desee instalar en el sistema de inmediato. Visit the Marimba Web site to find out more
about channels and what services they offer. Visite el sitio Web de Marimba para obtener
más información acerca de los canales y los servicios que ofrecen.

Castanet illustrates a point about Java that sometimes get lost: Although Java is most
popular as a way to write Web page programs, it is not limited to use on the Internet.
Castañuelas ilustra un punto de Java que a veces se pierden: Aunque Java es el más popular
como una forma de escribir programas de páginas web, no se limita al uso en Internet. You
can use it to write any kind of software. Puede usarlo para escribir cualquier tipo de
software.

Workshop: Putting Java on Your Desktop Taller: Poner Java en el escritorio


The last stop on your whirlwind tour of Java is ESPNET SportsZone, the electronic edition
of the cable sports channel. La última parada en su gira relámpago de Java es ESPNET
SportsZone, la edición electrónica del canal de cable de deportes. So far, your guides have
asked nothing of you other than an occasional wardrobe change, but that's going to change.
Hasta ahora, los guías no han pedido nada de lo que no sea un cambio de vestuario
ocasional, sino que va a cambiar. Redirect your Web browser to the following address:
Redirigir el navegador web a la siguiente dirección:

http://espnet.sportszone.com

If you're using a browser such as Netscape Navigator or Microsoft Internet Explorer, your
first assignment is to find the Java programs on this page. Si estás usando un navegador
como Netscape Navigator o Microsoft Internet Explorer, su primera tarea es encontrar los
programas Java en esta página. This assignment ought to be a lot easier than finding Waldo
in those Where's Waldo? Esta tarea debería ser mucho más fácil que encontrar a Wally en
los Dónde está Wally? children's books, but if you need a hint, here it is: They're the parts
with changing text and graphics. libros para niños, pero si usted necesita una pista, aquí
está: Son las partes con el cambio de texto y gráficos.
ESPN uses Java programs to provide constant updates to scores and headlines in the same
way it uses a sports ticker during some events. ESPN utiliza programas en Java para ofrecer
actualizaciones constantes de las puntuaciones y los titulares de la misma manera que
utiliza un tablero de deportes durante algunos eventos. In the scoreboard program, scores
are frequently updated in the program's window, along with graphical advertisements. En el
programa de cuadro de indicadores, los resultados se actualizan con frecuencia en la
ventana del programa, junto con los anuncios gráficos.

The scoreboard Java program is offered as part of a Web page, but it has a special feature
that adds to its usefulness. El programa de marcador de Java se ofrece como parte de una
página Web, pero tiene una característica especial que se suma a su utilidad. It can be
detached from the page and placed on your system's desktop as a stand-alone window. Se
puede extraer de la página y se coloca en el escritorio de su sistema como una ventana
independiente. Click the Display on Desktop button and then minimize your Web browser.
Haga clic en el botón de la pantalla de escritorio y minimizar su navegador de Internet. This
might be more sports than you're able to handle in a short period of time, but it shows how
Java can present information in a way much different from standard Web pages. Esto
podría ser más deportes que usted es capaz de manejar en un corto período de tiempo, pero
muestra cómo Java puede presentar la información de una manera muy diferente de páginas
Web estándar. Figure 3.8 shows the scoreboard program on a Windows 95 desktop. Figura
3.8 muestra el programa de marcador en un escritorio de Windows 95.

Figura 3.8. Scores are presented in a desktop window with the ESPNet SportsZone
Scorepost program.

Once you're completely caught up on the sports events that have taken place during your
world-in-an-hour jaunt, it's time to put away your luggage and get ready for a return to
programming. More Web sites and other items of note for Java programmers are described
in Appendix A, "Where to Go from Here: Java Resources."

Q&A Q & A
Q Can I use the sample Java programs from the JavaSoft Web site on my own home
page? Q ¿Puedo usar el Java programas de ejemplo del sitio Web de JavaSoft en mi
propia página?

A JavaSoft encourages the use of its sample programs on Web sites. Un JavaSoft fomenta
el uso de la muestra de sus programas en los sitios Web. Take a look at the directories that
were created when you installed the Java Developer's Kit on your system. Echa un vistazo
a los directorios que se crearon al instalar el Kit de Desarrollo Java en su sistema. You will
find more than a dozen sample programs along with the files that were used to compile
them. Va a encontrar más de una docena de programas de la muestra junto con los
archivos java. Que fueron utilizados para compilar. These programs can be a valuable
resource when you're working on your own Java programs later on. Estos programas
pueden ser un recurso valioso cuando usted está trabajando en sus propios programas en
Java más adelante.

Q What other ways have been devised to offer programs on Web pages? Q ¿Qué otras
formas se han ideado para ofrecer programas en las páginas web?

A Several programming strategies are aimed at making Web pages smarter. Un estrategias
de programación Varias están dirigidas a hacer páginas Web más inteligente. The main
competitor to Java is ActiveX, an extension of Microsoft technology called the Component
Object Model. El principal competidor de Java es ActiveX, una extensión de la tecnología
de Microsoft llamado el Modelo de objetos componentes. ActiveX programs are similar in
function to Java programs--they are placed on Web pages and are run when browsers are
equipped to handle them. programas ActiveX son similares en función a los programas de
Java - se colocan en las páginas Web y se ejecutan cuando los navegadores están
preparados para manejarlos. The primary differences are that ActiveX uses a way to verify
the identity of ActiveX programmers, and ActiveX programs are not downloaded each time
they are encountered. Las diferencias principales son que ActiveX utiliza una forma de
verificar la identidad de los programadores de ActiveX y los programas ActiveX no se
descargan cada vez que se encuentran. Unlike Java programs, an ActiveX program stays on
a user's system. A diferencia de los programas Java, un programa de estancias de ActiveX
en el sistema del usuario. In addition to ActiveX, JavaScript and VBScript offer some
programming capabilities on Web pages. Además de ActiveX, JavaScript y VBScript ofrece
algunas capacidades de programación en las páginas Web. These programs must be more
simple than Java and ActiveX programs, however. Estos programas deben ser más simples
que los programas de Java y ActiveX, sin embargo.

QI ran a useful Java program on a Web page. P publicó un útil programa Java en una
página Web. Can I run it on my system without the browser? ¿Puedo utilizar en mi
sistema sin el navegador?

A Under most circumstances, no. A En la mayoría de las circunstancias, no. Java programs
typically are developed either to run on a Web page or to run from the command line. los
programas de Java normalmente se desarrollan ya sea para ejecutar en una página Web o
para ejecutarse desde la línea de comandos. A program can be written so that it works in
both ways, but most of the programs you will find in a directory such as Gamelan do not
include this functionality. Un programa puede ser escrito para que funcione en ambos
sentidos, pero la mayoría de los programas que se encuentran en un directorio como
Gamelan no incluyen esta funcionalidad. You'll learn much more about the different types
of Java programs during Hour 4, "Understanding How Java Programs Work." Usted
aprenderá mucho más sobre los diferentes tipos de programas en Java durante horas 4,
"Descripción de cómo Java programas de trabajo."

Q If Java programs are platform-independent, why are some Java programs such as
SunSoft Java WorkShop only available for specific systems? Q Si los programas Java son
independientes de la plataforma, ¿por qué algunos programas de Java tales como Java
SunSoft WorkShop sólo está disponible para sistemas específicos?
A Java programs might be limited to specific systems such as PC compatibles because the
programs include the use of non-Java programming for some features. A los programas
Java puede ser limitado a los sistemas específicos, tales como PC compatibles porque los
programas incluyen el uso de programación Java, no para algunas funciones. For example,
a Java program might use a program written in C++ to communicate with a modem
because Java does not support this capability in its current version. Por ejemplo, un
programa Java puede utilizar un programa escrito en C + + para comunicarse con un
módem, porque Java no es compatible con esta capacidad en su versión actual. Java is still
relatively young in its development, and some of its goals concerning complete platform
independence have not been achieved yet. Java es todavía relativamente joven en su
desarrollo, y algunos de sus objetivos relativos a la independencia completa plataforma no
se han alcanzado todavía. Web programs are the area where Java's multiplatform promise
is most fully realized. programas web son el área donde es más plenamente la promesa
multiplataforma Java cuenta. Anyone with a Java-capable Web browser can use one of
Java's Web programs on a page. Cualquier persona con un navegador Web con capacidad
Java puede utilizar uno de los programas Java de Web en una página.

Q Is there a print edition of JavaWorld? Q ¿Existe una edición impresa de JavaWorld?

A At present, JavaWorld is distributed strictly through the World Wide Web. A En la


actualidad, se distribuye JavaWorld estrictamente a través de la World Wide Web.
However, several newsstand magazines are available that cover the language, including
Java Report, Dr. Dobb's Journal, and others. Sin embargo, varias revistas de quiosco de
prensa están disponibles que cubren la lengua, incluyendo informes Java, Dr. Dobb's
Journal, y otros.

Q Can a Java program I run on a Web page give my computer a virus? Q ¿Puede un
programa Java que se ejecutan en una página Web doy mi computadora un virus?

A Because of security restrictions that prevent Web programs from reading, writing, or
modifying files, there's no way for a virus to be transmitted from a Java program on a Web
page to your system. A causa de las restricciones de seguridad que impiden que los
programas de Web de lectura, escritura, o la modificación de los archivos, no hay forma de
que un virus pueda ser transmitido de un programa Java en una página Web a su sistema.
Java programs that you download and run from the command line have the same risk of
viruses as any program you download. los programas de Java que se descarga y se ejecuta
desde la línea de comandos tienen el mismo riesgo de virus como cualquier programa que
descargue. If you're using programs received over the Internet, you need to acquire a
good antivirus program and use it regularly. Si estás utilizando programas recibidos a
través de Internet, es necesario adquirir un buen programa antivirus y el uso de manera
regular.
Quiz Quiz
If your mind hasn't taken a vacation by this point in the hour, test your knowledge of this
chapter with the following questions. Si tu mente no se ha tomado unas vacaciones en este
punto de la hora, prueba tus conocimientos de este capítulo con las siguientes preguntas.

Questions Preguntas

1. How did object-oriented programming get its name? 1. ¿Cómo programación orientada
a objeto de obtener su nombre?

(a) Programs are considered to be a group of objects working together. (A) Los programas
son considerados como un grupo de objetos que trabajan juntos.
(b) People often object because it's hard to master. (B) Las personas a menudo objeto
porque es difícil de dominar.
(c) Its parents named it. (C) Sus padres la llamaron.

2. Which of the following isn't a part of Java's security? 2. ¿Cuál de los siguientes no es una
parte de la seguridad de Java?

(a) Web programs cannot run programs on the user's computer. (A) los programas Web no
puede ejecutar programas en el ordenador del usuario.
(b) The identity of a program's author is verified. (B) La identidad del autor de un
programa se verifica.
(c) Java windows are labeled as Java windows. (C) las ventanas de Java son etiquetados
como ventanas de Java.

3. What is a program's capability to handle more than one task called? 3. ¿Cuál es la
capacidad de un programa para manejar más de una tarea se llama?

(a) Schizophrenia (A) la esquizofrenia


(b) Multiculturalism (B) Multiculturalismo
(c) Multithreading (C) Multithreading

Answers Respuestas

1. a. 1. A. It's also abbreviated as OOP. Es también abreviado como programación


orientada a objetos.

2. b. 2. B. ActiveX programs verify the author of the program, but this security method is
not implemented with Java. programas ActiveX verificar el autor del programa, pero este
método de seguridad no se ha implementado con Java.

3. c. 3. C. This also is called multitasking, but the term multithreading is used in


conjunction with Java because an independently running part of a program is called a
thread. Esto también se llama multitarea, pero el multithreading término se utiliza en
combinación con Java, ya una parte independiente de funcionamiento de un programa
que se llama un hilo.

Activities Actividades
Before unpacking your luggage, you can explore the topics of this hour more fully with the
following activities: Antes de desempacar su equipaje, puede explorar los temas de esta
hora más plenamente con las siguientes actividades:

 Use the Gamelan directory at to find out what card games have been developed using
Java. Utilice el directorio en Gamelan http://www.gamelan.com para averiguar qué
juegos de cartas se han desarrollado utilizando Java.
 Find the sample Java programs by searching the JavaSoft site, and download one of them
to your computer. Encuentra los programas de ejemplo de Java mediante la búsqueda en
el sitio JavaSoft, y descargar uno de ellos en el equipo.

 4 horas
o Descripción de cómo funcionan los programas de trabajo de Java
 Creación de una aplicación
 Listado 4.1. El texto completo de Root.java.
 El envío de argumentos a las aplicaciones
 Listado 4.2. El texto completo de NewRoot.java.
 Applet Básico
 Listado 4.3. El texto completo de RootApplet.java.
 Listado 4.4. El texto completo de RootApplet.html.
 Figura 4.1.
 El envío de parámetros a subprogramas
 Figura 4.2.
 Taller: Viendo el código utilizado para ejecutar applets
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 4 4 horas

Understanding How Java Programs Work Descripción


de cómo funcionan los programas de trabajo de Java
An important distinction to make in Java programming is where your program is supposed
to be running. Una distinción importante a hacer en la programación de Java es donde el
programa se supone que debe estar en ejecución. Some programs are intended to work on
your computer; you type in a command or click on an icon to start them up. Algunos
programas están diseñados para trabajar en el equipo; escribe en un comando o haga clic en
un icono para la puesta en marcha. Other programs are intended to run as part of a World
Wide Web page. Otros programas están destinados a funcionar como parte de una página
del World Wide Web. You encountered several examples of this type of program during
the previous hour's whirlwind vacation. Se encontraron varios ejemplos de este tipo de
programas durante las vacaciones de torbellino de la hora anterior.

Java programs that run locally on your own computer are called applications. los programas
de Java que se ejecutan de forma local en su propia computadora se llaman las aplicaciones.
Programs that run on Web pages are called applets. Programas que se ejecutan en las
páginas Web se llaman applets. During this hour, you'll learn why that distinction is
important, and the following topics will be covered: Durante esta hora, usted aprenderá por
qué esa distinción es importante, y los siguientes temas serán cubiertos:

 How applications work ¿Cuántas solicitudes de trabajo


 Organizing an application La organización de una aplicación
 Sending arguments to an application El envío de los argumentos a una aplicación
 How applets work ¿Cómo applets de trabajo
 The required parts of an applet Las partes necesarias de un applet
 Sending parameters to an applet El envío de parámetros a un applet
 Using HTML tags to put an applet on a page El uso de etiquetas HTML para poner un
applet en una página

Creating an Application Creación de una aplicación


Although Java has become well-known because it can be used in conjunction with World
Wide Web pages, you can also use it to write any type of computer program. Aunque Java
se ha convertido en notoriamente conocida, ya que puede ser usado en conjunto con la
World Wide Web de las páginas, también se puede utilizar para escribir cualquier tipo de
programa de ordenador. The program that you wrote during Hour 2, "Writing Your First
Program," is an example of a Java application. El programa BigDebt que escribió durante
horas 2, "Escribiendo tu primer programa," es un ejemplo de una aplicación Java.

To try out another program, use your word processor to open up a new file and enter
everything from Listing 4.1. Para probar otro programa, utilice el procesador de textos para
abrir un archivo nuevo y escriba todo lo del listado 4.1. Remember not to enter the line
numbers and colons along the left-hand side of the listing; these items are used to make
parts of programs easier to describe in the book. Recuerde que no debe introducir los
números de línea y dos puntos a lo largo del lado izquierdo de la lista, estos artículos se
utilizan para fabricar partes de los programas más fácil de describir en el libro. When you're
done, save the file as . Cuando haya terminado, guarde el archivo como Root.java.

Listing 4.1. Listado 4.1. The full text of Root.java. El texto completo de Root.java.

1: class Root { 1: clase raíz {


2: public static void main(String[] arguments) { 2:
public static void main (String [argumentos]) {
3: int number = 225; , 225: 3 int = número
4: System.out.println("The square root of " 4:
System.out.println ("La raíz cuadrada de"
5: + number 5: + número
6: + " is " 6: + "es"
7: + Math.sqrt(number) ); 7: + Math.sqrt (número));
8: } 8:}
9:}

Before you can test out this application, you need to compile it with the compiler tool.
Antes de que usted puede probar esta aplicación, es necesario compilarlo con la
herramienta del compilador javac. While in the same directory as the file, compile it with
the following command: Mientras que en el mismo directorio que el archivo Root.java,
compilarlo con el siguiente comando:

javac Root.java javac Root.java

If you have entered Listing 4.1 without any typos, including all punctuation and every word
capitalized as shown, it should compile without any errors. Si ha introducido de venta 4.1
sin ningún tipo de errores tipográficos, incluyendo todos los puntuacion y cada palabra en
mayúsculas como se muestra, se debe compilar sin errores. The compiler responds to a
successful compilation by not responding with any message at all. El compilador javac
responde a una compilación exitosa, al no responder a ningún mensaje en absoluto.

You run Java applications in the same way you would run any program that's installed on
your computer. Ejecutar aplicaciones Java en la misma forma que ejecutar cualquier
programa que está instalado en su equipo. Because they require the use of the interpreter to
run, the most common way that you'll run a Java program is probably by typing a command
like the following at a command-line prompt: Porque requieren el uso del intérprete de
Java para correr, la forma más común que usted va a ejecutar un programa Java es,
probablemente, al escribir un comando como el siguiente en la línea de comandos del
sistema:

java DrumMachine java DrumMachine

This command would cause the interpreter to look for a Java program called in the current
directory. Este comando haría que el intérprete de Java para buscar un programa de Java
llamada DrumMachine.class en el directorio actual. If it found one, it would start running
it. Si encuentra uno, sería empezar a implementarla. To run the application, type the
following: Para ejecutar la aplicación de raíz, escriba lo siguiente:

java Root java Raíz

The output should resemble the following: El resultado debería parecerse a lo siguiente:

The square root of 225 is 15.0 La raíz cuadrada de 225 es


de 15,0

When you run a Java application, the interpreter looks for a block and starts handling Java
statements at that point. Cuando se ejecuta una aplicación Java, el intérprete busca un () el
bloque principal y se inicia tratamiento de las declaraciones de Java en ese momento. If
your program does not have a block, as most applets do not, the interpreter will respond
with an error. Si su programa no tiene un () Edificio principal, como la mayoría de
los applets no lo hace, el intérprete responderá con un error.

Sending Arguments to Applications El envío de argumentos a las aplicaciones


Because Java applications are usually run from a command line, you can send information
to applications at the same time that you run them. Dado que las aplicaciones Java son
generalmente se ejecuta desde una línea de comandos, puede enviar la información a las
aplicaciones al mismo tiempo que se ejecutan. The following example uses the interpreter
to run an application called , and it sends two extra items of information to the application:
and : En el ejemplo siguiente se utiliza el intérprete Java para ejecutar una aplicación
llamada DisplayTextFile.class, y envía dos elementos adicionales de información a la
aplicación: readme.txt y / p:

java DisplayTextFile readme.txt /p java DisplayTextFile


leeme.txt / p

The extra information you can send to a program is called arguments. La información
adicional que usted puede enviar a un programa que se llama argumentos. The first
argument, if there is one, is provided one space after the name of the application. El primer
argumento, si es que existe, se proporciona un espacio después del nombre de la aplicación.
Each additional argument is also separated by a space. Cada argumento adicional es
también separado por un espacio. You can send as many arguments as you want to a Java
application. Usted puede enviar tantos argumentos como que desea una aplicación Java. In
order to do something with them, however, you have to write some statements in the
application to handle them. Con el fin de hacer algo con ellos, sin embargo, usted tiene que
escribir algunos estados en la aplicación para manejar.

To see how arguments work in an application, create a new file in your word processor
called . Para ver cómo los argumentos de trabajo en una aplicación, crear un nuevo archivo
en el procesador de textos llamado NewRoot.java. Enter the text of Listing 4.2 into the file
and save it when you're done. Introduzca el texto del listado 4.2 en el archivo y guardarlo
cuando haya terminado. Compile the program with the compiler tool, while correcting any
errors that are caused by typos. Compilar el programa con la herramienta del compilador
javac, mientras que la corrección de los errores que son causados por errores tipográficos.

Listing 4.2. Listado 4.2. The full text of NewRoot.java. El texto completo de
NewRoot.java.

1: class NewRoot { 1: clase {NewRoot


2: public static void main(String[] arguments) { 2:
public static void main (String [argumentos]) {
3: int number = 0; ; 0: 3 int = número
4: if (arguments.length > 0) 4: si (arguments.length> 0)
5: number = Integer.parseInt( arguments[0] ); 5: número =
Integer.parseInt (argumentos [0]);
6: System.out.println("The square root of " 6:
System.out.println ("La raíz cuadrada de"
7: + number 7: + número
8: + " is " 8: + "es"
9: + Math.sqrt(number) ); 9: + Math.sqrt (número));
10: } 10:}
11:}

This program is similar to the program except for Lines 3-5. Este programa es similar al
programa de la raíz, excepto para las líneas 3-5. Don't worry about the specific
statements used in these lines; they use some advanced features. No te preocupes por los
estados específicos utilizados en estas líneas, que utilizan algunas funciones avanzadas.
What's important to note is what these lines are accomplishing: If an argument is sent to the
program when it is run, the argument is stored in the variable. Lo que es importante tener
en cuenta es lo que estas líneas están logrando: Si el argumento es enviado al programa
NewRoot cuando se ejecuta, el argumento es almacenado en la variable de número.

To try the program out, use the Java interpreter with a command such as the following:
Para probar el programa, utilice la intérprete de Java con un comando como el siguiente:

java NewRoot 169 java NewRoot 169

This command causes the output to report that the square root of 169 is 13.0. Este comando
hace que la salida de informar que la raíz cuadrada de 169 es 13,0. Try the program several
times with different numbers. Pruebe el programa varias veces con diferentes números.

Arguments are a useful way to customize the performance of a program. Los argumentos
son una forma útil para personalizar el rendimiento de un programa. They are often used to
configure a program so that it runs a specific way. A menudo se utilizan para configurar un
programa para que se ejecute de una manera específica. Java applications use arguments,
but applets use a different way to receive information as they are run. aplicaciones Java
utilizan argumentos, pero los applets utilizar una forma diferente de recibir información a
medida que se ejecutan.

Applet Basics Applet Básico


Applets--programs that can run on World Wide Web pages--were the thing that made Java
a computer magazine cover subject upon its release. Applets - programas que se pueden
ejecutar en las páginas World Wide Web - Se lo que hicieron en Java una revista cubierta
del equipo sujeto en su lanzamiento. Applets put a spotlight on the ways that Java was
different and remarkable. Applets puesto los reflectores sobre las formas en que Java era
diferente y sorprendente. Before Java, World Wide Web pages were a combination of text,
images, and forms that used gateway programs running on the computer that hosted the
pages. Antes de Java, las páginas World Wide Web eran una combinación de texto,
imágenes y formas que utilizan programas de puerta de enlace se ejecuta en el ordenador
que alojaba las páginas. These gateway programs required special access to the Web page
server machine, so most Web users did not have the ability to use them. Estos programas
requieren de puerta de enlace de acceso especial a la máquina de la página del servidor
Web, por lo que la mayoría de usuarios de Internet no tienen la capacidad de utilizarlos.
Writing them required even more expertise. Escribirlos requiere experiencia aún más.

In contrast, programmers of all skill levels can write Java applets, and you'll write several
during the span of these 24 hours. Por el contrario, los programadores de todos los niveles
puede escribir applets Java, y que voy a escribir varias ocasiones durante el transcurso de
estas 24 horas. You can test applets with any Web browser that handles Java programs and
put one on a Web page without any special access from a Web provider. Puede probar los
applets con cualquier navegador web que se encarga de los programas de Java y poner uno
en una página Web sin ningún tipo de acceso especial a un proveedor de Internet. The Java
programs that you toured during the previous hour were all applets. Los programas Java
que recorrió durante la última hora fueron todos los subprogramas. Their structure differs
from applications in several important ways, and they are designed specifically for
presentation on the World Wide Web. Su estructura difiere de las aplicaciones de varias
maneras importantes, y están diseñados específicamente para su presentación en la World
Wide Web.

As stated previously, applets do not have a block like applications do. Como se mencionó
anteriormente, los applets no tiene un main () como bloque de hacer aplicaciones. Applets
have several different sections that are handled depending on what is happening in the
applet. Applets tienen varias secciones diferentes que se manejan en función de lo que está
sucediendo en el applet. These sections are detailed fully during Hour 13, "Learning How
Applets Work." Estas secciones se detallan por completo durante 13 horas, "Aprender
applets de trabajo." Two of the sections are the block statement and the block. is short for
initialization, and it is used to set up anything that needs to be set up as an applet first runs.
Dos de las secciones son las de inicio () Declaración de bloque y la pintura () del
bloque. Init () es la abreviatura de la inicialización, y se utiliza para crear cualquier cosa
que necesita ser configurado como un applet se ejecuta primero. The block is used to
display anything that should be displayed. La pintura () del bloque se utiliza para
mostrar cualquier cosa que se debe mostrar.

To see an applet version of the application, create a new file in your word processor and
call it . Para ver una versión applet de la raíz de la aplicación, crear un nuevo archivo en
el procesador de textos y lo llaman RootApplet.java. Enter the code in Listing 4.3; save
it when you're done. Introduzca el código del listado 4.3; guardar cuando haya terminado.
Compile the file with the compiler tool by typing the following: Compilar el archivo con la
herramienta del compilador javac escribiendo lo siguiente:

javac RootApplet.java javac RootApplet.java

Listing 4.3. Listado 4.3. The full text of RootApplet.java. El texto completo de
RootApplet.java.

1: public class RootApplet extends java.applet.Applet {


1: public class RootApplet extiende java.applet.Applet {
2: int number; 2: int numero;
3: 3:
4: public void init() { 4: public void init () {
5: number = 225; 5: número = 225;
6: } 6:}
7: 7:
8: public void paint(java.awt.Graphics g) { 8: public
void paint (g java.awt.Graphics) {
9: g.drawString("The square root of " + 9: g.drawString
("La raíz cuadrada de" +
10: number + 10: número +
11: " is " + 11: "es" +
12: Math.sqrt(number), 5, 50); 12: Math.sqrt (número), 5,
50);
13: } 13:}
14:}

This program contains a lot of the same statements as the Java application that did the same
thing. Este programa contiene una gran cantidad de las mismas declaraciones en que la
aplicación Java que hizo lo mismo. The main difference is in how it is organized--the
block has been replaced with an block and a block. La principal diferencia está en cómo se
organiza - el () bloque principal ha sido sustituido por un init () y un bloque de paint
() del bloque.

The sample programs in this hour are provided primarily to introduce you to the way Java
programs are structured. Los programas de ejemplo en esta hora son prestados
principalmente para presentarle a la forma se estructuran los programas de Java. Some
aspects of these programs will be introduced fully later, so don't feel like you're falling
behind. Algunos aspectos de estos programas se introdujo plenamente más adelante, así que
no siente que está quedando atrás. The main purpose of this hour is to get the programs to
compile and see how they function when you run them. El objetivo principal de esta hora es
conseguir que los programas para recopilar y ver cómo funcionan cuando se ejecutan.

Unlike applications, compiled Java applets cannot be tested using the interpreter tool. A
diferencia de las aplicaciones, applets de Java compilado no puede ser probado con la
herramienta intérprete de Java. You have to put them on a Web page and view that page in
one of two ways: Usted tiene que colocar en una página Web y ver esa página en una de
dos maneras:

 Use a Web browser that can handle Java applets, such as the current versions of Netscape
Navigator or Microsoft Internet Explorer. Utilice un navegador Web que puede manejar
los applets de Java, como las versiones actuales de Netscape Navigator o Microsoft
Internet Explorer.
 Use the tool that comes with the Java Developer's Kit. Utilice la herramienta
appletviewer que viene con Java Developer Kit.

To create a Web page that can display the program, return to your word processor and
create a new file. Para crear una página Web que puede mostrar el programa RootApplet,
regresar a su procesador de textos y crear un nuevo archivo. Enter Listing 4.4 in that file
and save it as . Introduzca Listado 4.4 en el archivo y guárdelo como RootApplet.html.

Listing 4.4. Listado 4.4. The full text of RootApplet.html. El texto completo de
RootApplet.html.
1: <applet code="RootApplet.class" height=100 width=300>
1: <applet code="RootApplet.class" height=100 width=300>

This Web page contains the bare minimum needed to display a Java applet on a Web page.
2: </ applet> Esta página Web contiene el mínimo necesario para visualizar un applet de
Java en una página Web. The tag is used to specify that a Java program is being put on the
page, the attribute provides the name of the applet, and the and attributes describe the size
of the applet's display area. La etiqueta <APPLET> se utiliza para especificar que un
programa Java se está poniendo en la página, el atributo de código proporciona el nombre
del applet, y la altura y el ancho de los atributos describen el tamaño de la pantalla el
área del applet. These items will be described in detail during Hour 13. Estos elementos se
describen en detalle durante la hora 13.

For now, use the tool to take a look at this page. Por ahora, utilice la herramienta
appletviewer a echar un vistazo a esta página. Type the following at the command line:
Escriba lo siguiente en la línea de comandos:

appletviewer RootApplet.html appletviewer RootApplet.html

Figure 4.1 shows what the applet looks like using . La figura 4.1 muestra lo que el applet
se ve como el uso de appletviewer.

Figura 4.1. The applet displayed with the tool. El applet RootApplet que aparecen con la
herramienta appletviewer.

Sending Parameters to Applets El envío de parámetros a subprogramas


Java applets are never run from the command line, so you can't specify arguments the way
you can with applications. applets de Java no se ejecutan desde la línea de comandos, por lo
que no puede especificar los argumentos de la misma manera que con las aplicaciones.
Applets use a different way to receive information at the time the program is run. Applets
uso de una manera diferente de recibir información en el momento de ejecutar el programa.
This information is called parameters, and you can send parameters through the HTML
page that runs the applet. Esta información se conoce como parámetros, y puede enviar los
parámetros a través de la página HTML que se ejecuta el applet. You have to use a special
HTML tag for parameters called . Usted tiene que usar una etiqueta de HTML especial
para los parámetros de llamada <PARAM>.

Load the file back into your word processor. Cargue el archivo RootApplet.java de
nuevo en su procesador de textos. The block of the program should resemble the
following: El init () de bloque del programa debe ser similar a lo siguiente:

public void init() { public void init () {


number = 225; = número 225;
} }

Replace these three lines with the following statements: Vuelva a colocar estas tres líneas
con las siguientes afirmaciones:

public void init() { String parameter =


getParameter("NUMBER"); if (parameter != null) number =
Integer.parseInt(parameter); } public void init ()
{parámetro String = getParameter ("NUMERO"); if (!
parámetro = null) número = Integer.parseInt (parámetros);}

Save the file and then compile it by typing the following at the command line: Guarde el
archivo y luego compilarlo escribiendo lo siguiente en la línea de comandos:

javac RootApplet.java javac RootApplet.java

Before you can try this change out, you need to modify the Web page so that it sends a
parameter. Antes de poder tratar este cambio, usted necesita modificar el
RootApplet.html página Web para que envíe un parámetro. Load the page into your word
processor and add a line between the line and the line, so that the code resembles the
following: Cargue la página en el procesador de palabra y añadir una línea entre la línea de
<APPLET> y </ APPLET> línea, por lo que el código similar al siguiente:

<applet code="RootApplet.class" height=100 width=300>


code="RootApplet.class" <applet height=100 width=300>
<param name="NUMBER" value=196> <param nombre="nombre"
value=196>
</applet> </ Applet>
Save the file when you're done, and load the page using again. Guarde el archivo cuando
haya terminado, y la carga de la página utilizando appletviewer nuevo. The output should
resemble Figure 4.2. La salida debe ser similar a la Figura 4.2. Change the value of the
attribute in the file and run the program again. Cambie el valor del atributo de valor en el
archivo RootApplet.html y ejecutar el programa de nuevo. Try this several times, and
you'll see that your program is now flexible enough to handle any number. Pruebe esto
varias veces, y verá que su programa es ahora lo suficientemente flexible como para
manejar cualquier número.

Figura 4.2. The modified program displayed with . La modificación del programa
RootApplet que aparecen con appletviewer.

You can use as many parameters as needed to customize the operation of an applet, as long
as each has a different attribute specified along with the tag. Puede utilizar como
parámetros que sea necesario para personalizar el funcionamiento de un applet, siempre y
cuando cada uno tiene un nombre diferente atributo especificado junto con la etiqueta
<PARAM>.

Workshop: Viewing the Code Used to Run Applets Taller: Viendo el código utilizado
para ejecutar applets
As a brief workshop to better familiarize yourself with the tag and how it can be used to
alter the performance of an applet, visit this book's World Wide Web site at the following
address: Como un breve taller para familiarizarse mejor con la etiqueta <APPLET> y cómo
se puede utilizar para alterar el funcionamiento de un applet, visita este libro World Wide
Web en la siguiente dirección:

http://www.prefect.com/java24

Visit this site using either the current version of Netscape Navigator or Microsoft Internet
Explorer. Visite este sitio utilizando la versión actual de Netscape Navigator o Microsoft
Internet Explorer. Go to the section of the site labeled , and you'll be given a guided tour
through several working examples of applets. Vaya a la sección del sitio marcado cuatro
horas Showcase, y se le dará una visita guiada a través de varios ejemplos de trabajo de
los subprogramas. On each of these pages, you can use a pull-down menu command to
view the HTML tags that were used to create the page. En cada una de estas páginas, puede
utilizar un menú desplegable el comando de menú para ver las etiquetas HTML que se
utiliza para crear la página. With Navigator, the command is , and with Internet Explorer,
the command is . Con Navigator, el comando se Ver | Fuente del documento, y con
Internet Explorer, el comando Ver | Fuente. Compare the parameters that are used with
each applet to the way the applet runs. Comparación de los parámetros que se utilizan con
cada subprograma a la forma en que el applet se ejecuta.
Appendix C, "This Book's Web Site," describes other things you can do on this book's site.
Apéndice C, "este libro Sitio Web", describe las cosas que usted puede hacer en la página
de este libro. The Web site is intended as a complement to the material covered in this book
and a way to find out about corrections, revisions, or other information that makes these 24
hours more productive. El sitio web pretende ser un complemento al material cubierto en
este libro y una manera de averiguar acerca de las correcciones, revisiones, o cualquier otra
información que hace que estas 24 horas más productivas.

Summary Resumen
During this hour, you got a chance to create both a Java application and an applet. Durante
esta hora, tienes la oportunidad de crear tanto una aplicación Java y un applet. These two
types of programs have several important differences in the way they function and the way
they are created. Estos dos tipos de programas tienen varias diferencias importantes en la
forma en que la función y la forma en que se crean. The next several hours will continue to
focus on applications as you become more experienced as a Java programmer. Las
próximas horas se seguirá centrando en aplicaciones a medida que adquieren experiencia
como programador Java. Applications are easier to test because they don't require you to
create a Web page to view them; they can be easier to create as well. Las aplicaciones son
más fáciles de probar, ya que no requieren volver a crear una página web para verlas, sino
que puede ser más fácil para crear así. The last several hours of the book focus on applets,
however, because that's the area where beginning programmers are most likely to want to
put their skills to work. Las últimas horas varios de los libro se centran en los applets, sin
embargo, porque esa es la zona donde los programadores de inicio es más probable que
quiera poner sus habilidades a trabajar.

Q&A Q & A
Q Can a single Java program be both an applet and an application? Q ¿Puede un solo
programa Java a la vez de un applet y una aplicación?

A It is possible to make a program serve as both applet and application, but it's often an
unwieldy solution unless the program is simple. R Es posible hacer un programa de servir
como applet y aplicación, pero a menudo es una solución difícil de manejar a menos que el
programa es simple. An applet could be set up to run as an application also by including a
block in the applet, but you would not be able to use the block or block in the automatic
fashion they are used in an applet. Un applet puede ser configurado para ejecutarse como
una aplicación también mediante la inclusión de un main () por categorías en el applet,
pero no sería capaz de usar el init () bloquear o pintura () en el bloque de manera
automática que se utilizan en una applet. Most programs are written either as an
application or as an applet, rather than attempting to do both. La mayoría de los
programas se escriben ya sea como una aplicación o un applet, en vez de intentar hacer
las dos cosas.

Q Do all arguments sent to a Java application have to be strings? Q ¿Todos los


argumentos enviados a una aplicación Java que ser cadenas?

A Java puts all arguments into strings for storage when an application runs. Un Java pone
todos los argumentos en cadenas de almacenamiento cuando se ejecuta una aplicación.
When you want to use one of these arguments as an integer or some other non-string
type, you have to convert the value. Cuando se desea utilizar uno de estos argumentos
como un entero o algún otro tipo que no son cadenas, hay que convertir el valor. You'll
learn how to do this during the coming hours. Usted aprenderá a hacer esto durante las
próximas horas.

Q Why don't Java applets require the same kind of special access as gateway programs?
Q ¿Por qué no los applets de Java requieren el mismo tipo de acceso especial como los
programas de puerta de enlace?

A Java applets don't have the same access requirements because they don't pose the
same risk to a Web site provider. Un applet de Java no tienen los requisitos de acceso
misma porque no presentan el mismo riesgo para un proveedor de sitios Web. Gateway
programs don't have any kind of security in place to prevent the program from attempting
to do harmful things to the machine running the Web page. programas de puerta de
enlace no tiene ningún tipo de seguridad para impedir que el programa tratando de hacer
cosas perjudiciales para la máquina en marcha la página Web. Java applets, on the other
hand, have strict restrictions to prevent them from being used to write harmful programs.
applets de Java, por el contrario, existen restricciones estrictas para evitar que sean
utilizados para escribir programas nocivos. Also, Java programs do not run on the Web
site's machine--they run on the system of the person viewing the page. Además, los
programas Java no se ejecutan en el equipo del sitio web - que se ejecutan en el sistema
de la persona que ve la página. This means that the Web site's machine will not slow down
due to numerous people running a Java applet on a page. Esto significa que el equipo del
sitio web no se retrasará debido a numerosas personas al ejecutar un subprograma Java
en una página.

Quiz Quiz
Test your knowledge of the material covered in this chapter by answering the following
questions. Pon a prueba tus conocimientos sobre el material tratado en este capítulo,
respondiendo a las siguientes preguntas.

Questions Preguntas

1. Which type of Java program can be run by the interpreter tool? 1. ¿Qué tipo de
programa de Java puede ser ejecutado por la herramienta intérprete de Java?

(a) Applets (A) Applets


(b) Applications (B) Aplicaciones
(c) none (C) ninguno

2. What special HTML tag is used to put a Java program onto a Web page? 2. Lo especial
de etiquetas HTML se utiliza para poner un programa Java en una página web?

(a) (A) <APPLET>


(b) (B) <PROGRAM>
(c) (C) <Run>

3. If you get into a fight with someone over the way to send information to a Java
application, what are you doing? 3. Si te metes en una pelea con alguien sobre la forma de
enviar información a una aplicación Java, ¿qué estás haciendo?

(a) Struggling over strings (A) La lucha por cadenas


(b) Arguing about arguments (B) Discutir acerca de los argumentos
(c) Feudin' on functionality (C) Feudin 'en la funcionalidad

Answers Respuestas

1. b. 1. B. Applications are run with the interpreter tool, and Web pages containing applets
can be run with the tool as well as Java-capable World Wide Web browsers. Las
aplicaciones se ejecutan con la herramienta de intérprete, y las páginas web que
contienen applets se pueden ejecutar con la herramienta appletviewer, así como en
Java capaz Mundial de los exploradores Web ancha.

2. a. 2. A. The tag is used along with the tag to send parameters to the applet. La etiqueta
<APPLET> se usa junto con la etiqueta <PARAM> para enviar parámetros al applet.

3. b. 3. B. Can't we all get along? No podemos vivir todos juntos?

Activities Actividades
If you'd like to apply your acumen of applets and applications, do the following activities:
Si desea aplicar su visión de los applets y aplicaciones, realizar las siguientes actividades:

 Check out the Gamelan site at and use the search term Marquee to see links and
descriptions to all of the applets that have been written to display text in a marquee sign
format. Echa un vistazo a la página Gamelan en http://www.gamelan.com y utilizar el
término de búsqueda Marquesina para ver los links y descripciones de todos los applets
que se han escrito para mostrar texto en un formato de marquesina. Each of these applets
use parameters to modify the text that is displayed. Cada uno de estos subprogramas
utilizar parámetros para modificar el texto que se muestra.
 Write a Java applet that can handle a parameter named and a parameter named . Escriba
un applet de Java que puede manejar un parámetro denominado X y un parámetro
denominado Y. Display the two numbers in a statement like the one in the program.
Mostrar los dos números en una drawString () declaración como la que en el
programa RootApplet.
 5 horas
o y cambio de Almacenamiento de información en un programa de
 Las declaraciones y expresiones
 Asignación de los tipos variables
 Números enteros y números de punto flotante
 Caracteres y cadenas
 Listado 5.1. El programa variable.
 Otros tipos de variables numéricas
 La variable de tipo booleano
 Designación de su Variables
 Almacenamiento de información en las variables
 Taller: Uso de expresiones
 Listado 5.2. El programa de Elvis.
 Listado 5.3. La salida del programa de Elvis.
 Todo sobre los operadores
 El incremento y disminución de una variable
 Precedencia de Operadores
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 5 5 horas

Storing and Changing Information in a Program y


cambio de Almacenamiento de información en un
programa de
In Hour 2, "Writing Your First Program," you used a variable, a special storage place that is
used to hold information. En la hora 2, "Escribiendo tu primer programa," que utiliza una
variable, un lugar especial de almacenamiento que se utiliza para almacenar la información.
The information stored in variables can be changed as your program runs, which is why
they're called variables. La información almacenada en las variables pueden cambiar como
su programa se ejecuta, por lo que son variables llamadas. Your first program stored an
integer number in a variable called . Su primer programa almacena un número entero en
una variable denominada la deuda. Integers are only one of the types of information that
can be stored in variables. Los enteros son sólo uno de los tipos de información que se
puede almacenar en las variables. Variables also can hold characters, lines of text, floating-
point numbers, and other things. Las variables también pueden contener caracteres, líneas
de texto, números de punto flotante, y otras cosas.

Variables are the main way that a computer remembers something as it runs a program. Las
variables son la principal forma en que un equipo se acuerda de algo ya que se ejecuta un
programa. The program used the variable to tell the computer that the national debt
increases by $59 million per day. El programa BigDebt utiliza la variable de la deuda
para decirle al ordenador que los aumentos de deuda pública por 59 millones dólares por
día. The computer needed to remember that fact a little later so a minute's worth of debt
increase could be calculated. El equipo necesario para recordar ese hecho un poco más
tarde, podrían valer la pena un minuto de incremento de la deuda calculada. During this
hour, you'll learn more about using variables in your Java programs. Durante esta hora,
usted aprenderá más sobre el uso de variables en los programas Java.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 Creating variables Creación de variables


 The different types of variables Los diferentes tipos de variables
 Storing values into variables Almacenamiento de los valores en variables
 Using variables in mathematical expressions Utilización de variables en expresiones
matemáticas
 Putting one variable's value into another variable Poner un valor variable en otra variable
 Increasing and decreasing a variable's value El aumento y la disminución de valor de una
variable

Statements and Expressions Las declaraciones y expresiones


Computer programs are a set of instructions that tell the computer what to do. Los
programas de ordenador son un conjunto de instrucciones que indican a la computadora qué
hacer. Each of these instructions is called a statement. Cada una de estas instrucciones se
llama un comunicado. The following example from a Java program is a statement: El
siguiente ejemplo de un programa Java es una declaración:
int HighScore = 400000; Puntuación de int = 400,000;

In a Java program, you can use brackets to group statements. En un programa en Java,
puede utilizar paréntesis para agrupar sentencias. These groupings are called block
statements. Estos grupos se llaman estados del bloque. Consider the following portion of a
program: Considere la siguiente parte de un programa:

1: public static void main (String[] arguments) { 1:


public static void main (String [argumentos]) {
2: int a = 3; 2: int a = 3;
3: int b = 4; ; 4: 3 int b =
4: int c = 8 * 5; , 5: 4 int c = 8 *
5: } 5:}

Lines 2-4 of this example are a block statement. Líneas 2-4 de este ejemplo es un bloque de
sentencias. The opening bracket on Line 1 denotes the beginning of the block, and the
closing bracket on Line 5 denotes the end of the block. El corchete de apertura de la línea 1
indica el principio del bloque, y el paréntesis de cierre en la línea 5 indica el final del
bloque.

Some statements are called expressions because they involve a mathematical expression.
Algunos estados se llaman expresiones porque implican una expresión matemática. Line 4
in the preceding example is an expression because it sets the value of the variable equal to
8 multiplied by 5. Línea 4 en el ejemplo anterior es una expresión, ya que establece el valor
de la variable c igual a 8 y se multiplicarán por 5. You'll be working with several different
types of expressions throughout the coming sections. Usted estará trabajando con varios
tipos diferentes de expresiones a lo largo de las siguientes secciones.

Assigning Variable Types Asignación de los tipos variables


In a Java program, variables are created with a statement that must include two things: En
un programa Java, las variables se crean con una declaración que debe incluir dos cosas:

 The name of the variable El nombre de la variable


 The type of information the variable will store El tipo de información la variable
almacenará

To see the different types of variables and how they are created, load the word processor
you're using to write programs and set it up to start a new file. Para ver los diferentes tipos
de variables y cómo se crean, la carga del procesador de textos que está utilizando para
escribir programas y configurarlo para comenzar un nuevo archivo. You will be creating a
program called . Usted será la creación de un programa llamado variable.
Give your new file the name , and start writing the program by entering the following
lines: Dé a su nuevo archivo con el nombre Variable.java, y comenzar a escribir el
programa mediante la introducción de las siguientes líneas:

class Variable { clase de variables {


public static void main (String[] arguments) {
public static void main (String [argumentos]) {
// Coming soon: variables / / Muy pronto: las
variables
} }
} }

Go ahead and save these lines before making any changes. Adelante y guarde estas líneas
antes de hacer cualquier cambio.

Integers and Floating-Point Numbers Números enteros y números de punto flotante

So far, the program has a block with only one statement in it--the comment line . Hasta
ahora, el programa tiene una variable principal () de bloque con una sola declaración
en la que - la línea de comentario en breve: las variables. Delete the comment line
and enter the following statement in its place: Eliminar la línea de comentario y escriba la
siguiente declaración en su sitio:

int tops; tapas int;

This statement creates a variable named . Esta sentencia crea una variable denominada
tapas. This statement does not specify a value for , so the variable is an empty storage
space for the moment. Esta declaración no especifica un valor para las tapas, por lo que la
variable es un espacio vacío por el momento. The text at the beginning of the statement
designates as a variable that will be used to store integer numbers. El texto int al principio
de la declaración señala tapas como una variable que se utiliza para almacenar números
enteros. You can use the type to store most of the nondecimal numbers that you will need
in your computer programs. Usted puede utilizar el tipo int para almacenar la mayoría de
los números no decimal que se necesita en la computadora de sus programas. It can hold
any integer from -2.14 billion to 2.14 billion. Puede contener cualquier número entero -2,14
mil millones a 2,14 mil millones.

Create a blank line after the statement and add the following statement: Crear una línea en
blanco después de las copas int; declaración y agregar la siguiente declaración:

float gradePointAverage; flotador gradePointAverage;


This statement creates a variable with the name . Esta sentencia crea una variable con el
gradePointAverage nombre. The text stands for floating-point numbers. El texto del
flotador es sinónimo de puntos números en coma flotante. Floating-point variables are
used to store numbers that might contain a decimal point. variables de punto flotante se
utilizan para almacenar los números que pueden contener un punto decimal.

A floating-point variable could be used to store a grade point average such as 2.25, to pick
a number that's dear to my heart. Una variable de punto flotante se podría utilizar para
almacenar un promedio de calificaciones, tales como 2.25, para recoger un número que es
caro a mi corazón. It also could be used to store a number such as 0, which is the
percentage chance of getting into a good graduate school with that grade point average,
despite my really good cover letter and a compelling written recommendation from my
parole officer. También se podría utilizar para almacenar un número como 0, lo que es el
porcentaje de posibilidades de entrar en una universidad de postgrado con ese buen
promedio de calificaciones, a pesar de mi carta de presentación muy buena y una
recomendación convincente por escrito de mi oficial de libertad condicional.

Characters and Strings Caracteres y cadenas

Because all the variables you have dealt with so far are numeric, you might have the
mistaken impression that all variables are used with numbers. Debido a que todas las
variables que se han ocupado hasta ahora son numéricos, es posible que la impresión
errónea de que todas las variables se utilizan con los números. You can also use variables to
store text. También puede utilizar variables para almacenar texto. Two types of text can be
stored as variables: characters and strings. Dos tipos de texto se pueden guardar como
variables: caracteres y cadenas. A character is a single letter, number, punctuation mark, or
other symbol. Un personaje es una sola letra, número, marca de puntuacion, u otro símbolo.
Most of the things you can use as characters are shown on your computer's keyboard. La
mayoría de las cosas que se pueden utilizar como caracteres se muestran en el teclado de su
ordenador. A string is a group of characters. Una cadena es un grupo de personajes.

Your next step in creating the program is to create a variable and a variable. Su siguiente
paso en la creación del programa de variable es crear una variable de tipo char y una
variable de cadena. Add these two statements after the line : Añadir estos dos estados
después de la línea de flotación gradePointAverage;:

char key = `C'; char clave = "C";


String productName = "Orbitz"; ProductName cadena = "Haga
clic aquí";
When you are using character values in your program, such as in the preceding example,
you must put single quote marks on both sides of the character value being assigned to a
variable. Cuando usted está utilizando los valores de caracteres en su programa, como en el
ejemplo anterior, usted debe poner comillas simples citan a ambos lados del valor de
carácter que se asigne a una variable. You must surround string values with double quote
marks. Usted debe rodear los valores de cadena con comillas dobles. These quote marks are
needed to prevent the character or string from being confused with a variable name or other
part of a statement. Estas comillas son necesarias para evitar que la cadena de caracteres o
de ser confundido con un nombre de variable o por otra de un comunicado. Take a look at
the following statement: Echa un vistazo a la siguiente declaración:

String productName = Orbitz; String productName = Haga


clic aquí;

This statement might look like a statement that tells the computer to create a variable
called and give it the text value of . Esta afirmación puede parecer una declaración que
dice la computadora para crear una variable de cadena llamada productName y darle el
valor de texto de Orbitz. However, because there are no quote marks around the word ,
the computer is being told to set the value to the same value as a variable named . Sin
embargo, porque no hay comillas alrededor de la palabra Haga clic aquí, el equipo se
está contando para establecer el valor de ProductName al mismo valor que una variable
denominada Haga clic aquí.

After adding the and statements, your program should resemble Listing 5.1. Después de
añadir el char y String declaraciones, el programa debe ser similar de venta 5.1. Make
any changes that are needed and be sure to save the file. Haga los cambios necesarios y
asegúrese de guardar el archivo. This program does not produce anything to display, but
you should compile it with the compiler tool to make sure it was created correctly. Este
programa no produce nada para mostrar, pero debe compilar con la herramienta del
compilador javac para asegurarse de que se ha creado correctamente.

Listing 5.1. Listado 5.1. The Variable program. El programa variable.


1: class Variable { 1: clase de variables {
2: public static void main (String[] arguments) { 2:
public static void main (String [argumentos]) {
3: int tops; 3: tapas int;
4: float gradePointAverage; 4: gradePointAverage flotador;
5: char key = `C'; 5: clave char = "C";
6: String productName = "Orbitz"; 6: productName String =
"Haga clic aquí";
7: } 7:}
8:}

The last two variables in the program use the = sign to assign a starting value when the
variables are created. Las dos últimas variables en el programa variable utilizar el signo =
para asignar un valor inicial cuando las variables se crean. You can use this option for any
variables that you create in a Java program. Usted puede utilizar esta opción para cualquier
variable que se crea en un programa Java. For more information, see the section called
"Storing Information in Variables." Para obtener más información, consulte la sección
titulada "Almacenamiento de la Información en las variables."

Although the other variable types are all lowercase letters ( , , , the capital letter is
required in the word when creating variables. Aunque los tipos de variables demás letras
minúsculas (int, float, char), la letra mayúscula se requiere en la palabra de cadena
cuando se crean las variables de cadena. A string in a Java program is somewhat different
than the other types of information you will use in variables. Una cadena en un programa
Java es algo diferente que los otros tipos de información que va a utilizar en las variables.
You'll learn about this distinction in Hour 6, "Using Strings to Communicate." Usted
aprenderá acerca de esta distinción en la hora 6, "Uso de cadenas para la comunicación."

Other Numeric Variable Types Otros tipos de variables numéricas

The variables that you have been introduced to so far will be the main ones that you use
during this book and probably for most of your Java programming. Las variables que se
han introducido hasta el momento serán los principales que se utilizan en este libro y,
probablemente, la mayor parte de su programación Java. There are a few other types of
variables you can use in special circumstances. Hay algunos otros tipos de variables que
puede utilizar en circunstancias especiales.

You can use three other variable types with integers. Usted puede utilizar tres tipos de
variables de otros con números enteros. The first, , can be used for integer numbers that
range from -128 to 127. La primera, byte, se puede utilizar para los números enteros que
van desde -128 a 127. The following statement creates a variable called with an initial
value of 27: La siguiente sentencia crea una variable llamada escapeKey con un valor
inicial de 27:

byte escapeKey = 27; escapeKey bytes = 27;

The second, , can be used for integers that are smaller in size than the type. El segundo,
corto, se puede utilizar para los números enteros que son menores en tamaño que el tipo
int. A integer can range from -32,768 to 32,767, as in the following example: Un entero
corto puede variar entre -32.768 y 32.767, como en el ejemplo siguiente:

short roomNumber = 222; roomNumber corta = 222;

The last of the special numeric variable types, , is typically used for integers that are too
big for the type to hold. El último de los tipos de variables numéricas especiales, de
largo, se suele utilizar para los números enteros que son demasiado grandes para el tipo
int para celebrar. A integer can be of almost any size; if the number has five commas or
less when you write it down, it can fit into a . Un entero largo puede ser de casi cualquier
tamaño, y si el número tiene cinco comas o menos cuando se escribe, puede caber en un
largo plazo. Some six-comma numbers can fit as well. Algunos números de seis coma
puede caber también.

Except for times when your integer number is bigger than 2.14 billion or smaller than -2.14
billion, you won't need to use any of these special variable types very often. A excepción de
ocasiones en que su número entero es mayor de 2,14 millones de dólares o más pequeño
que -2140000000, no será necesario utilizar cualquiera de estos tipos de variables
especiales muy a menudo. If they're muddling your understanding of variable types,
concentrate on and . Si están confundiendo su comprensión de los tipos de variables, se
concentran en int y float. Those types are the ones you'll be using most often. Esos tipos
son los que usted va a utilizar más a menudo.

The boolean Variable Type La variable de tipo booleano

Java has a special type of variable that can only be used to store the value or the value .
Java tiene un tipo especial de variable que sólo se puede utilizar para almacenar el valor
verdadero o valor de lo falso. This type of variable is called a . Este tipo de variable que
se llama un valor lógico. At first glance, a variable might not seem particularly useful
unless you plan to write a lot of computerized true-or-false quizzes. A primera vista, una
variable booleana no parece particularmente útil a menos que piense en escribir una gran
cantidad de informáticos-o falsas pruebas verdaderas. However, variables will be used in a
variety of situations in your programs. Sin embargo, las variables booleanas se utilizan en
una variedad de situaciones en sus programas. The following are some examples of
questions that variables can be used to answer: Los siguientes son algunos ejemplos de
preguntas que las variables booleanas se pueden utilizar para responder:

 Has the user pressed a key? Tiene el usuario pulsa una tecla?
 Is the game over? Es el juego más?
 Is this the first time the user has done something? ¿Es esta la primera vez que el usuario
ha hecho algo?
 Is the bank account overdrawn? Es la cuenta bancaria en descubierto?
 Have all 10 images been displayed onscreen? Han sido las 10 imágenes que aparecen en
pantalla?
 Can the rabbit eat Trix? ¿Puede comer el conejo Trix?

The following statement is used to create a variable called : La siguiente declaración se


utiliza para crear una variable booleana llamada gameOver:

boolean gameOver = false; gameOver Boolean = false;

This variable has the starting value of , and a statement such as this one could be used in a
game program to indicate that the game isn't over yet. Esta variable tiene el valor inicial de
falsa, y una declaración como ésta podría ser utilizado en un programa de juego para
indicar que el juego no ha terminado todavía. Later on, when something happens to end the
game (such as the destruction of all of the player's acrobatic Italian laborers), the variable
can be set to . Más tarde, cuando sucede algo para terminar el juego (por ejemplo, la
destrucción de todas las acrobacias de la mano de obra italiana del jugador), la variable
gameOver se puede establecer en true. Although the two possible values-- and --look like
strings in a program, you should not surround them with quote marks. Aunque los dos
valores booleanos posible - verdadero y lo falso - parecen a las cadenas en un programa,
usted no debe rodearse de las comillas. Hour 7, "Using Conditional Tests to Make
Decisions," describes variables more fully. Horas del día 7, "Uso de pruebas condicionales
para tomar decisiones", se describen las variables booleanas más plenamente.

Boolean numbers are named for George Boole, who lived from 1815 to 1864. booleanos
llevan el nombre de George Boole, que vivió desde 1815 hasta 1864. Boole, a British
mathematician who was mostly self-taught until late adulthood, invented Boolean algebra,
a fundamental part of computer programming, digital electronics, and logic. Boole, un
matemático británico que fue su mayor parte autodidacta hasta la edad adulta tardía,
inventó el álgebra de Boole, una parte fundamental de la programación informática,
electrónica digital, y la lógica.

Naming Your Variables Designación de su Variables


Variable names in Java can begin with a letter, underscore character (_), or a dollar sign
($). Los nombres de variables en Java pueden comenzar con una letra, guión bajo (_) o un
signo de dólar ($). The rest of the name can be any letters or numbers, but you cannot use
blank spaces. El resto del nombre puede ser cualquier letra o número, pero no puede utilizar
espacios en blanco. You can give your variables any names that you like under those rules,
but you should be consistent in how you name variables. Usted puede dar a las variables de
cualquier nombre que te gusta en esas reglas, pero deben ser coherentes en la forma en que
las variables de nombre. This section outlines the generally recommended naming method
for variables. En esta sección se describe el método general, se recomienda nombrar las
variables.

Caution: Java is case-sensitive when it comes to variable names, so you must always capitalize
variable names in the same way throughout a program. Atención: Java es sensible cuando se trata
de nombres de variables, por lo que siempre debe aprovechar los nombres de variables de la
misma manera a través de un programa. For example, if the variable is used as somewhere in the
program, the statement will cause an error when you compile the program. Por ejemplo, si la
variable gameOver se utiliza como GameOver en alguna parte del programa, la declaración
GameOver se producirá un error al compilar el programa.

First, the name that you give a variable should describe its purpose in some way. En primer
lugar, el nombre que le dan una variable debe describir el propósito de alguna manera. The
first letter should be lowercase, and if the variable name has more than one word, make the
first letter of each word a capital letter. La primera letra debe estar en minúsculas, y si el
nombre de la variable tiene más de una palabra, que la primera letra de cada palabra de una
letra mayúscula. For instance, if you wanted to create an integer variable to store the all-
time high score in a game program, you could use the following statement: Por ejemplo, si
desea crear una variable entera para guardar la puntuación más alta de todos los tiempos en
un programa de juego, puede utilizar la siguiente declaración:

int allTimeHighScore; allTimeHighScore int;

You can't use punctuation marks or spaces in a variable name, so neither of the following
would work: Usted no puede utilizar las marcas de puntuacion o espacios en un nombre de
variable, por lo que ninguno de los siguientes trabajos:

int all-TimeHigh Score; int todas TimeHigh-Score;


int all Time High Score; int todas las Altas Puntuación
Tiempo;

If you tried to use these names in a program, the Java compiler would respond with an
error. Si ha intentado utilizar estos nombres en un programa, el compilador de Java que
responder con un error.

Storing Information in Variables Almacenamiento de información en las variables


As you have seen, in a Java program you can put a value into a variable at the same time
that you create the variable. Como se ha visto, en un programa de Java que puede poner un
valor en una variable al mismo tiempo que se crea la variable. You also can put a value in
the variable at any time later in the program. También puede poner un valor en la variable
en cualquier momento posterior en el programa.

To set up a starting value for a variable upon its creation, use the equals sign (=). Para
establecer un valor inicial de una variable sobre su creación, el uso del signo igual (=). The
following is an example of creating a floating-point variable called with the starting value
of 3.14: El siguiente es un ejemplo de cómo crear un punto variable flotante llamada pi con
el valor inicial de 3.14:

float pi = 3.14; float pi = 3,14;

All variables that store numbers can be set up in a similar fashion. Todas las variables que
almacenan números se pueden configurar de una manera similar. If you're setting up a
variable for a character or a string, you must place quote marks around the value as shown
previously. Si está configurando una variable para un personaje o una cadena, debe colocar
entre comillas el valor como se indica anteriormente.

You also can set one variable equal to the value of another variable if they both are of the
same type. También puede establecer una variable igual al valor de otra variable si ambos
son del mismo tipo. Consider the following example: Consideremos el siguiente ejemplo:

int mileage = 300; kilometraje int = 300;


int totalMileage = mileage; totalMileage int =
kilometraje;

First, an integer variable called is created with a starting value of 300. En primer lugar, una
variable llamada kilometraje entero se crea con un valor inicial de 300. In the second
line, an integer variable called is created with the same value as . En la segunda línea, una
variable llamada totalMileage entero se crea con el mismo valor que el kilometraje.
Both variables will have the starting value of 300. Ambas variables tienen el valor inicial de
300. In future hours, you will learn ways to convert one variable's value to the type of
another variable. En horas de futuro, usted aprenderá la manera de convertir el valor de una
variable con el tipo de otra variable.

Caution: If you do not give a variable a starting value, you must give it a value before you try to use
it. Precaución: Si usted no da una variable un valor de partida, debe darle un valor antes de
intentar usarlo. If you don't, when you attempt to compile your program, the compiler will
respond with an error message such as the following: Si no, al intentar compilar el programa, el
compilador javac responderá con un mensaje de error como los siguientes:
WarGame.java:7: Variable warships may not have been initialized. WarGame.java: 7:
buques de guerra de variable no puede haber sido inicializado.
warships = warships + 10; buques de guerra de los buques de guerra + = 10;
^^
1 error Un error

Workshop: Using Expressions Taller: Uso de expresiones


As you worked on a particularly unpleasant math problem in school, did you ever complain
to a higher power, protesting that you would never use this knowledge again in your life? A
medida que trabajaba en un problema de matemáticas particularmente desagradable en la
escuela, ¿alguna vez se quejan de que un poder superior, en protesta por que nunca
utilizaría este conocimiento nuevo en tu vida? Sorry to break this to you, but all your
teachers were right: Those math skills are going to be used in your computer programming.
Siento decirte esto, pero todos los profesores tenían razón: Las habilidades matemáticas se
va a utilizar en su programación de computadoras.

That's the bad news. Esa es la mala noticia. The good news is that the computer will do any
of the math that you ask it to do. La buena noticia es que el equipo va a hacer cualquiera de
las matemáticas que le pida que haga. As mentioned earlier in this hour, any instructions
you give a computer program involving math are called expressions. Como se mencionó
anteriormente en esta hora, las instrucciones que le dan un programa de ordenador de la
matemática se llaman expresiones. Expressions will be used frequently in your computer
programs. Las expresiones se utilizan con frecuencia en los programas de su computadora.
You can use them for tasks such as the following: Puedes usarlos para tareas como las
siguientes:

 Changing the value of a variable Cambiar el valor de una variable


 Counting the number of times something has happened in a program Contar el número de
veces que algo ha sucedido en un programa de
 Using a mathematical formula in a program Usando una fórmula matemática en un
programa de

As you write computer programs, you will find yourself drawing upon your old math
lessons as you use expressions. Al escribir programas de ordenador, te encontrarás
aprovechando las lecciones de matemáticas de edad a medida que utilice expresiones.
Expressions can use addition, subtraction, multiplication, division, and modulus division.
Las expresiones pueden usar la suma, resta, multiplicación, división, división y módulo.

To see expressions in action, return to your word processor and close the file if it is still
open. Para ver las expresiones en la acción, volver a su procesador de textos y cierre el
archivo Variable.java si todavía está abierta. Create a new file and save it as . Crear un
nuevo archivo y guardarlo como Elvis.java. The program creates a fictional person
whose weight loss and weight gain can be tracked with mathematical expressions. El
programa de Elvis crea un personaje de ficción cuya pérdida de peso y aumento de peso
pueden ser rastreados con expresiones matemáticas. Instead of adding statements to the
program piece by piece, enter the full text of Listing 5.2 into the word processor. En lugar
de agregar instrucciones a la pieza a pieza del programa, escriba el texto completo del
listado 5.2 en el procesador de textos. Each part of the program will be discussed in turn.
Cada parte del programa se tratarán a su vez.

Listing 5.2. Listado 5.2. The Elvis program. El programa de Elvis.


1: class Elvis { 2: public static void main(String[]
arguments) { 3: int weight = 250; 4:
System.out.println("Elvis weighs " + weight); 5:
System.out.println("Elvis visits a few all-you-can-eat rib
joints."); 6: System.out.println("Elvis throws a
Thanksgiving luau."); 7: weight = weight + 10; 8:
System.out.println("Elvis now weighs " + weight); 9:
System.out.println("Elvis discovers aerobics."); 10: weight
= weight - 15; 11: System.out.println("Elvis now weighs " +
weight); 12: System.out.println("Elvis falls into a washing
machine during the 13: shrink cycle."); 14: weight = weight
/ 3; 15: System.out.println("Elvis now weighs " + weight);
16: System.out.println("Elvis accidentally clones himself
12 times."); 17: weight = weight + (weight * 12); 18:
System.out.println("The 13 Elvii now weigh " + weight); 19:
} 1: Elvis clase {2: public static void main (String
[argumentos]) {3: peso int = 250; 4: System.out.println
("Elvis pesa" + peso); 5: System.out.println (" Elvis
visitas de unos pocos "all-you-can-eat" juntas de costilla
"."); 6: System.out.println (Elvis lanza un luau de Acción
de Gracias. "); 7 de peso = peso + 10, 8:
System.out.println ("Elvis ahora pesa" + peso); 9:
System.out.println peso = peso - 15, 11: ("Elvis descubre.
aeróbicos"); 10: System.out.println ("Elvis ahora pesa" +
peso) ; 12: System.out.println ("Elvis cae en una lavadora
durante las 13: ciclo de contracción."); 14: peso = peso /
3, 15: System.out.println ("Elvis ahora pesa" + peso) ; 16:
System.out.println ("Elvis accidentalmente clones de sí
mismo 12 veces."); 17: peso = peso + (* Peso 12); 18:
System.out.println ("El Elvii ahora pesan 13" + peso) ;
19:} 20:}

When you're done, save the file and use the tool to compile the program. Cuando haya
terminado, guarde el archivo y el uso de la herramienta javac para compilar el programa.
In the same directory as the file, type the following command to compile the program: En
el mismo directorio que el archivo Elvis.java, escriba el comando siguiente para
compilar el programa de Elvis:
javac Elvis.java javac Elvis.java

If it compiles without any errors, you will not see any output; responds only if something
goes wrong. Si se compila sin ningún error, no verá ninguna salida; javac sólo responde si
algo sale mal. If you do see error messages, check the line number that is listed in the error
message to look for typos. Si no aparecen mensajes de error, compruebe el número de línea
que aparece en el mensaje de error en busca de errores tipográficos. Correct any typos that
you find and compile the program. Corrija los errores ortográficos que encuentre y
compilar el programa.

Next, run the program by typing the following command: A continuación, ejecute el
programa escribiendo el siguiente comando:

java Elvis java Elvis

Listing 5.3 shows the output for this program. Listado 5.3 muestra el resultado de este
programa.

Listing 5.3. Listado 5.3. The output of the Elvis program. La salida del programa de
Elvis.

Elvis weighs 250 Elvis pesa 250


Elvis visits a few all-you-can-eat rib joints. Elvis
visitas de unos pocos "all-you-can-eat" juntas de costilla.
Elvis throws a Thanksgiving luau. Elvis lanza un luau de
Acción de Gracias.
Elvis now weighs 260 Elvis ahora pesa 260
Elvis discovers aerobics. Elvis descubre aeróbic.
Elvis now weighs 245 Elvis ahora pesa 245
Elvis falls into a washing machine during the shrink
cycle. Elvis cae en una lavadora durante el ciclo de
contracción.
Elvis now weighs 81 Elvis ahora pesa 81
Elvis accidentally clones himself 12 times. Elvis
accidentalmente clones de sí mismo 12 veces.
El Elvii 13 ahora pesa 1053

As in the other programs that you have created, the program uses a block statement for all
of its work. Al igual que en los otros programas que usted ha creado, el programa utiliza un
Elvis main () sentencia de bloque de todo su trabajo. This statement can be divided into
the following five sections: Esta declaración se puede dividir en las siguientes cinco
secciones:

1. Lines 3-4: The initial weight of Elvis is set to 250. 1:. Líneas 3-4 El peso inicial de Elvis se
establece en 250.

2. Lines 5-8: Elvis gains weight. 2:. Líneas 5-8 Elvis aumenta de peso.

3. Lines 9-11: Elvis loses weight. 3. Líneas de 11.09 Elvis pierde peso.

4. Lines 12-14: Elvis reduces in size dramatically. 4. Líneas 12 a 14 Elvis reduce en tamaño
de forma espectacular.

5. Lines 15-17: Elvis multiplies. 5:. Líneas 15 a 17 Elvis multiplica.

Line 3 creates the variable and designates it as an integer variable with . Línea 3 crea la
variable de peso y la designa como una variable de tipo entero con int. The variable is
given the initial value 250, and it is used throughout the program to monitor Elvis' weight.
La variable se le da el valor inicial de 250, y se utiliza en todo el programa para vigilar el
peso de Elvis.

The next line is similar to several other statements in the program: La siguiente línea es
similar a otras declaraciones en el programa:

System.out.println("Elvis weighs " + weight);


System.out.println ("Elvis pesa" + peso);

The command displays a string that is contained within the parentheses. El


System.out.println () comando muestra una cadena que se encuentra dentro de los
paréntesis. In the preceding line, the text is displayed, followed by the value of the
variable. En la línea anterior, el texto Elvis pesa es que aparecen, seguido por el valor de
la variable de peso. There are numerous statements in the program. Hay numerosos
System.out.println () declaraciones en el programa. If you're still unclear about how
these statements work, look at each of them in Listing 5.2 and compare them to the
corresponding lines in Listing 5.3. Si usted todavía está poco claro acerca de cómo estas
declaraciones trabajar, buscar en cada uno de ellos en el Listado 5.2 y compararlas con las
líneas correspondientes en el listado 5.3.

All About Operators Todo sobre los operadores


Four different mathematical expressions are used in the program to add weight to Elvis,
subtract weight from Elvis, divide it, and finish it off with some multiplication. Cuatro
expresiones matemáticas diferentes se utilizan en el programa de Elvis para añadir peso a
Elvis, restar el peso de Elvis, dividirlo, y terminar con algunos de multiplicación. Each of
these expressions uses symbols (+, -, *, /, and %) called operators. Cada una de estas
expresiones se utilizan símbolos (+, -, *, / y%) Los operadores de llamadas. You will be
using these operators to crunch numbers throughout your Java programs. Usted va a utilizar
estos operadores para hacer cálculos a lo largo de los programas Java.

An addition expression in Java uses the sign, as in Line 7 of your program: Además de una
expresión en Java utiliza el signo +, como en la línea 7 de su programa:

weight = weight + 10; peso = peso + 10;

This line sets the variable equal to its current value plus 10. Esta línea define la variable
de ponderación igual a su valor actual más 10. Because the was set to 250 when it was
created, Line 7 changes to 260. Debido a que el peso se fijó a 250 cuando se creó, la línea
7 cambios de peso a 260.

A subtraction expression uses the sign, as in Line 10: Una expresión de la resta utiliza el
signo -, como en la línea 10:

weight = weight - 15; peso = peso - 15;

This expression sets the variable equal to its current value minus 15. Esta expresión define
la variable de ponderación igual a su valor actual menos 15. The variable is now equal to
245. La variable de ponderación es ahora igual a 245.

A division expression uses the sign, as in Line 13: Una expresión de la división utiliza el
signo /, como en la línea 13:

weight = weight / 3; peso = peso / 3;

The variable is set to its current value divided by 3 and rounded down because is an
integer. La variable de ponderación se establece en su valor actual, dividido por tres y se
redondea hacia abajo porque el peso es un número entero. The variable is now equal to 81.
La variable de ponderación es ahora igual a 81.

There's another expression that you can use to find the remainder of a division. Hay otra
expresión que puede utilizar para encontrar el resto de una división. When the value of the
variable was divided by 3 in Line 13, a remainder of was discarded in order for to remain
as an integer value. Cuando el valor de la variable peso se dividió por tres en la línea 13, un
resto de 2 se descartó para que el peso de permanecer como un valor entero. To find a
remainder from an expression, use the operator. Para encontrar un resto de una expresión,
utilice el operador%. You could use the following statement to find the remainder of 245
divided by 3: Usted podría utilizar la siguiente declaración para encontrar el resto de 245
dividido por 3:

remainder = 245 % 3; resto = 245% 3;

A multiplication expression uses the sign. Una expresión de multiplicación utiliza el signo
*. Line 16 uses a multiplication expression as part of a more complicated statement: Línea
16 utiliza una expresión de la multiplicación como parte de una declaración más
complicada:

weight = weight + (weight * 12); peso = peso + (* Peso


12);

The part of the expression multiplies by 12. El peso * 12 parte de la expresión se


multiplica el peso por 12. The full statement takes the current value of and adds it to
multiplied by 12. La declaración completa toma el valor actual de peso y se agrega al peso
multiplicado por 12. This example shows how more than one expression can be combined
in a statement. Este ejemplo muestra cómo más de una expresión se pueden combinar en un
comunicado. The result is that becomes 1,053--in other words, 81 + (81 * 12). El resultado
es que el peso se convierte en 1053 - es decir, 81 + (81 * 12).

Incrementing and Decrementing a Variable El incremento y disminución de una


variable

One thing you will need to do often is to change the value of a variable by 1. Una cosa que
usted tendrá que hacer a menudo es cambiar el valor de una variable en 1. Because this task
is so common, there are special, simplified ways to accomplish it in your Java programs.
Debido a que esta tarea es tan común, hay maneras simplificado especial para lograr en los
programas Java. You can increase the value by 1, which is called incrementing the variable,
or decrease the value by 1, which is decrementing the variable. Puede aumentar el valor en
1, que se llama el incremento de la variable, o disminuir el valor en 1, que es la variable
decreciente. You use special operators for each of these tasks. Puede utilizar operadores
especiales para cada una de estas tareas.

To increment the value of a variable by 1, use the operator, as in the following statement:
Para incrementar el valor de una variable en 1, utilice el operador + +, como en la
siguiente declaración:

x++; x + +;
This statement adds 1 to the value stored in the variable. Esta sentencia añade 1 al valor
almacenado en la variable x.

To decrement the value of a variable by 1, use the operator: Para disminuir el valor de una
variable en 1, utilice el operador -:

y--; y -;

This statement reduces by 1. Esta declaración y reduce en 1.

During Hour 1, "Becoming a Programmer," the name of the C++ programming language
was described as a joke you'd understand later on. Durante una hora, "convertirse en un
programador," el nombre de C + + lenguaje de programación que se describió como una
broma que lo entendería más adelante. Now that you've been introduced to the increment
operator , you have all the information you need to figure out why C++ has two plus signs
instead of just one. Ahora que ya ha sido introducido en el operador de incremento + +,
tienes toda la información que necesita para entender por qué C + + tiene dos signos más en
lugar de uno solo. If you're still having trouble, C++ adds new features and functionality to
the C programming language in the same way that the operator adds 1 to a variable. Si
sigues teniendo problemas, C + + agrega nuevas características y funcionalidad para el
lenguaje de programación C de la misma manera que el operador + + suma 1 a una
variable. Just think: After you work through all 24 hours of this book, you'll be able to tell
jokes that are incomprehensible to more than 99 percent of the world's population. Sólo
piensa: Después de trabajar a través de las 24 horas de este libro, usted será capaz de contar
chistes que son incomprensibles para los más de 99 por ciento de la población mundial.

Operator Precedence Precedencia de Operadores

When you are using an expression with more than one operator, you need to know what
order the computer will use as it works out the expression. Cuando se utiliza una expresión
con más de un operador, lo que necesita saber para lo que el equipo va a usar, ya que se
resuelve la expresión. Consider the following statement: Considere la siguiente declaración:

x = y * 3 + 5; x = y * 3 + 5;

Unless you know what order the computer will use when working out the math in this
expression, you cannot be sure what the variable will be set to. A menos que sepa lo que
para el equipo a utilizar cuando se trabaja con las matemáticas en esta expresión, no puede
estar seguro de lo que la variable x se establecerá. If is equal to 10 and multiplication
occurs before addition, will equal 35. Si y es igual a 10 y la multiplicación se produce
antes de la adición, x será igual a 35. If equals 10 and addition occurs before
multiplication, will equal 80. Si y es igual a 10 y además se produce antes de la
multiplicación, x será igual a 80.

The following order is used when working out an expression: La siguiente orden se utiliza
cuando se trabaja con una expresión:

 Incrementing and decrementing take place first. Incremento y decremento ocupar el


primer lugar.
 Multiplication, division, and modulus division occur next. Multiplicación, división y división
módulo ocurrir a continuación.
 Addition and subtraction follow. Suma y resta seguir.
 Comparisons take place next. Las comparaciones tendrá lugar el próximo.
 The equal sign is used to set a variable's value. El signo igual = se utiliza para establecer el
valor de una variable.

Comparisons will be discussed during Hour 7. Las comparaciones serán discutidos durante
horas 7. The rest has been described during this hour, so you should be able to figure out
the result of the following statement: El resto se ha descrito en esta hora, por lo que debe
ser capaz de averiguar el resultado de la siguiente declaración:

int number = 5++ * 6 + 4 * 10 / 2; int numero = 5 + + * 6


+ 4 * 10 / 2;

This statement sets the variable to 56. Esta declaración establece la variable de número a
56. How does the computer come up with this number? ¿Cómo funciona el equipo llegar a
este número? First, the increment operator is handled, and is set to the value of 5 increased
by 1--in other words, 6. En primer lugar, el operador de incremento se maneja, y 5 + + se
establece en el valor de 5 años aumentó a 1 - en otras palabras, 6. The expression then
becomes the following: La expresión se convierte entonces en lo siguiente:

int number = 6 * 6 + 4 * 10 / 2; int numero = 6 * 6 + 4 *


10 / 2;

Now, multiplication and division are handled from left to right. Ahora, la multiplicación y
la división son manejados de izquierda a derecha. First, 6 is multiplied by 6. En primer
lugar, 6 se multiplica por 6. Then 4 is multiplied by 10 and that result is divided by 2 ( . A
continuación, cuatro se multiplica por 10 y ese resultado se divide por 2 (4 * 10 / 2).
The expression becomes the following: La expresión se convierte en lo siguiente:

int number = 36 + 20; int numero = 36 + 20;

This expression results in the variable being set to 56. Esto da lugar a la expresión en la
variable de número se establece en 56.
If you want an expression to be evaluated in a different order, you can use parentheses to
group parts of an expression that should be handled first. Si desea una expresión a ser
evaluada en un orden diferente, se pueden utilizar paréntesis para agrupar partes de una
expresión que deben ser manejadas en primer lugar. For example, the expression would
normally cause to equal 17 because multiplication is handled before addition. Por ejemplo,
la expresión x = 5 * 3 + 2; normalmente causa x 17 a la igualdad ya que la
multiplicación es manejado antes de la adición. However, look at a modified form of that
expression: Sin embargo, mirar una forma modificada de esta expresión:

x = 5 * (3 + 2); x = 5 * (3 + 2);

In this case, the expression within the parentheses is handled first, so the result equals 25.
En este caso, la expresión dentro del paréntesis se maneja en primer lugar, por lo que el
resultado es igual a 25. You can use parentheses as often as needed in a statement. Puede
utilizar paréntesis con la frecuencia necesaria en un comunicado.

Summary Resumen
Now that you have been introduced to variables and expressions, you can give a wide range
of instructions to your computer in a program. Ahora que se han introducido a las variables
y expresiones, se puede dar una gran variedad de instrucciones a su equipo en un programa.
Programs that you write can accomplish many of the same tasks as a calculator by handling
sophisticated mathematical equations with ease. Los programas que se escribe puede
realizar muchas de las mismas tareas que una calculadora de ecuaciones matemáticas
sofisticadas de manipulación con facilidad. Manipulating numbers is only one element of
variable use. La manipulación de números es sólo un elemento de uso variable. You also
can handle characters, strings of characters, and special true-or-false values called
variables. Usted también puede manejar caracteres, cadenas de caracteres, y especial-o-
falso verdaderos valores llamadas variables booleanas. The next hour will expand your
knowledge of variables and how they are used. La siguiente hora se ampliará su
conocimiento de las variables de cadena y cómo se utilizan.

Q&A Q & A
Q Is a line in a Java program the same thing as a statement? Q es una línea en un
programa en Java lo mismo que una declaración?

A No. R No. Although the programs that you will create in this book put one statement on
each line, this is done to make the programs easier to understand; it's not required.
Aunque los programas que va a crear en este libro, poner una declaración en cada línea,
esto se hace para hacer los programas más fácil de entender, no es necesario. The Java
compiler does not consider lines, spacing, or other formatting issues when compiling a
program. El compilador de Java no tiene en cuenta las líneas, el espacio, u otros problemas
de formato al compilar un programa. The compiler just wants to see semicolons at the end
of each statement. El compilador sólo quiere ver punto y coma al final de cada
declaración. You can put more than one statement on a line, although this is not generally
recommended. Usted puede poner más de una instrucción en una línea, aunque esto
generalmente no se recomienda.

Q Is there a reason to set up a variable without giving it a value right away? Q ¿Hay
alguna razón para establecer una variable sin darle un valor inmediato?

A For many of the simple programs that you will be creating in the first several hours, no.
A Para muchos de los programas sencillos que va a crear en las primeras horas, no.
However, there are many circumstances where it makes more sense to give a variable a
value at some point later in the program. Sin embargo, hay muchas circunstancias en que
tiene más sentido para dar una variable un valor en algún momento más adelante en el
programa. One example would be a calculator program. Un ejemplo sería un programa de
calculadora. The variable that stores the result of a calculation will not be needed until a
user tries out the program's calculator buttons. La variable que almacena el resultado de
un cálculo no será necesaria hasta que un usuario trata de los botones del programa de la
calculadora. Therefore, you would not need to set up an initial value when creating a
variable. Por lo tanto, no sería necesario establecer un valor inicial al crear una variable de
resultado.

Q What's the specific range for the long variable type? Q ¿Cuál es la gama específica
para el tipo de variable de tiempo?

A In Java, a integer variable can be anything from -9,223,372,036,854,775,808 to


9,223,372,036,854,775,807. A En Java, una variable puede ser cualquier cosa desde
-9.223.372.036.854.775.808 a 9.223.372.036.854.775.807. This range ought to give your
mathematical expressions plenty of breathing room when you can't use , which has a
range of -2,147,483,648 to 2,147,483,647. Este rango debe dar a sus muchas expresiones
matemáticas de espacio para respirar cuando no se puede utilizar int, que tiene un
rango de -2.147.483.648 a 2.147.483.647.

Q Why should the first letter of a variable name be lowercase, as in gameOver? Q ¿Por
qué la primera letra del nombre de una variable estar en minúsculas, como en
gameOver?

A It makes the variable easier to spot among all of the other elements of a Java program.
Un Esto hace que la variable más fácil de ver entre todos los demás elementos de un
programa Java. Also, by following a consistent style in the naming of variables, you
eliminate errors that can occur when you use a variable in several different places in a
program. Además, siguiendo un estilo consistente en la denominación de las variables,
eliminar los errores que pueden ocurrir cuando se utiliza una variable en varios lugares
diferentes en un programa. The style of naming used in this book has become popular
since Java's release. El estilo de nombres utilizados en este libro se ha hecho popular
desde el lanzamiento de Java.
Q Can two variables have the same letters but different capitalization, as in highScore
and HighScore? Q ¿Pueden dos variables tienen las mismas letras mayúsculas, pero
diferentes, como en la puntuación más alta y la puntuación más alta?

A Each of the differently capitalized names would be treated as its own variable, so it's
possible to use the same name twice in this way. A cada uno de los nombres en
mayúsculas de otra manera sería considerado como su propia variable, por lo que es
posible utilizar el mismo nombre dos veces en este camino. However, it seems likely to
cause a lot of confusion when you or someone else is attempting to figure out how the
program works. Sin embargo, parece probable que cause una gran confusión cuando
usted u otra persona está tratando de averiguar cómo funciona el programa. It also
increases the likelihood of using the wrong variable name somewhere in your program,
which is an error that will not be caught during compilation. También aumenta la
probabilidad de utilizar el nombre de variable mal en alguna parte de tu programa, que es
un error que no serán capturados durante la compilación. Errors like that make it into the
finished product and are called logic errors. Errores como que lo hacen en el producto final
y se llaman errores de lógica. They must be caught by an attentive programmer during
testing. Ellos deben ser capturados por un programador atento durante la prueba.

Quiz Quiz
Test your knowledge of variables, expressions, and the rest of the information in this hour
by answering the following questions. Pon a prueba tu conocimiento de las variables,
expresiones, y el resto de la información en esta hora contestando las siguientes preguntas.

Questions Preguntas

1. What do you call a group of statements contained with an opening bracket and a closing
bracket? 1. ¿Cómo se llama un grupo de instrucciones que figuran con un corchete de
apertura y un paréntesis de cierre?

(a) A block statement (A) Un bloque de instrucciones


(b) Groupware (B) Groupware
(c) Bracketed statements (C) las declaraciones entre corchetes

2. A variable is used to store true-or-false values. 2. Una variable booleana se utiliza para
almacenar / falso verdaderos valores.

(a) True (A) Verdadero


(b) False (B) Falso
(c) No, thanks. (C) No, gracias. I already ate. Yo ya comí.

3. What characters cannot be used to start a variable name? 3. ¿Qué caracteres no se


puede utilizar para iniciar un nombre de variable?

(a) A dollar sign (A) Un dólar más firme


(b) Two forward slash marks (//) (B) Dos barras diagonales (/ /)
(c) A letter (C) Una carta

Answers Respuestas

1. a. 1. A. The grouped statements are called a block statement or a block. Los estados
agrupados se denominan un bloque de sentencias o un bloque.

2. a. 2. A. True or false are the only answers a variable can store. Verdadero o falso son las
únicas respuestas de una variable booleana puede almacenar.

3. b. 3. B. Variables can start with a letter, dollar sign ($), or an underscore character ( ).
Las variables pueden comenzar con una letra, signo de dólar ($), o un guión bajo (_). If
you started a variable name with two slash marks, the rest of the line would be ignored
because the slash marks are used to start a comment line. Si ha iniciado un nombre de
variable con dos marcas de barra, el resto de la línea sería ignorado por las marcas de
barra se utilizan para iniciar una línea de comentario.

Activities Actividades
You can review the topics of this hour more fully with the following activities: Usted puede
revisar los temas de esta hora más plenamente con las siguientes actividades:

 Expand the program to track the weight if it were incremented by one pound for three
consecutive days. Expandir el programa de Elvis para realizar un seguimiento del peso si
se incrementa en una libra por tres días consecutivos.
 Create a short Java program that uses an integer and a integer and displays the result of
squared plus squared. Crear un corto programa de Java que utiliza un entero y un entero
x y y muestra el resultado de x al cuadrado más cuadrado y.
 6 horas
o Uso de cadenas para la comunicación
 Almacenamiento de cadenas de texto en
 Viendo las cadenas en los programas
 Uso de caracteres especiales en cadenas
 Cuerdas pegar Juntos
 Uso de otras variables con cadenas
 Avanzado manejo de cadenas
 Comparando dos cadenas
 La determinación de la longitud de una cadena
 Cambio de un caso de cadenas
 Taller: Presentación de Créditos
 Listado 6.1. El programa de créditos.
 Listado 6.2. La salida del programa de créditos.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 6 6 horas

Using Strings to Communicate Uso de cadenas para la


comunicación

In the film The Piano, Holly Hunter portrays Ada, a young Scottish woman who marries
badly. En la película El Piano, Holly Hunter interpreta a Ada, una joven escocesa que se
casa mal. A mute since the age of 6, Ada can only express herself fully by playing her
prized possession, a piano. Un silencio desde la edad de 6, Ada sólo puede expresarse
plenamente al tocar su preciada posesión, un piano. Like Ada, your computer programs are
capable of quietly doing their work and never stopping for a chat--or piano recital--with
humans. Al igual que Ada, sus programas de ordenador son capaces de hacer su trabajo en
silencio y sin detenerse para charlar - considerando o piano - con los seres humanos.
However, if The Piano teaches us anything, it is that communication ranks up there with
food, water, and shelter as essential needs. Sin embargo, si el piano nos enseña algo, es que
la comunicación califica con alimentos, agua y refugio como necesidades esenciales. (It
also teaches us that Harvey Keitel has a lot of body confidence, but that's a matter for
another book.) (También nos enseña que Harvey Keitel tiene mucha confianza en el cuerpo,
pero eso es un tema para otro libro.)
Java programs don't have access to a piano. programas Java no tienen acceso a un piano.
They use strings as the primary means to communicate with users. Que utilizan cadenas
como la principal vía para comunicarse con los usuarios. Strings are collections of text--
letters, numbers, punctuation, and other characters. Las cadenas son colecciones de texto -
letras, números, puntuacion, y otros personajes. During this hour, you will learn all about
working with strings in your Java programs. Durante esta hora, usted aprenderá todo acerca
de la utilización de cadenas en sus programas Java. The following topics will be covered:
Los siguientes temas serán cubiertos:

 Using strings to store text Uso de cadenas para almacenar texto


 Displaying strings in a program Viendo las cadenas en un programa
 Including special characters in a string Incluidos los caracteres especiales de una cadena
 Pasting two strings together Pegar dos cadenas
 Including variables in a string Incluidas las variables en una cadena
 Some uses for strings Algunos usos de las cadenas
 Comparing two strings Comparando dos cadenas
 Determining the length of a string La determinación de la longitud de una cadena
 Changing a string to uppercase or lowercase Cambio de una cadena a mayúsculas o
minúsculas

Storing Text in Strings Almacenamiento de cadenas de texto en


Strings are a common feature in computer programming because they provide a way to
store text and present it to users. Las cadenas son una característica común en
programación de computadoras, ya que proporcionan una manera de guardar el texto y
presentarlo a los usuarios. The most basic element of a string is a character. El elemento
más básico de una cadena es un carácter. A character is a single letter, number, punctuation
mark, or other symbol. Un personaje es una sola letra, número, marca de puntuacion, u otro
símbolo.

In Java programs, a character is one of the types of information that can be stored in a
variable. En los programas de Java, un personaje es uno de los tipos de información que
puede ser almacenado en una variable. Character variables are created with the type in a
statement such as the following: Personaje variables se crean con el tipo char en una
declaración como la siguiente:

char keyPressed; char keyPressed;

This statement creates a variable named that can store a character. Esta sentencia crea una
variable denominada keyPressed que puede almacenar un carácter. When you create
character variables, you can set them up with an initial value, as in the following: Al crear
las variables de carácter, que puede configurar con un valor inicial, como en lo siguiente:

char quitKey = `@'; QuitKey char = '@';


Note that the value of the character must be surrounded by single quotation marks. Tenga
en cuenta que el valor del personaje debe estar rodeado de comillas simples. If it isn't, the
compiler tool will respond with an error when the program is compiled. Si no es así, la
herramienta del compilador javac responderá con un error cuando se compila el programa.

A string is a collection of characters. Una cadena es una colección de personajes. You can
set up a variable to hold a string value by using the text and the name of the variable, as in
the following statement: Puede configurar una variable para contener un valor de cadena
utilizando la cadena de texto y el nombre de la variable, como en la siguiente declaración:

String fullName = "Ada McGrath Stewart"; String FullName =


"Ada McGrath Stewart";

This statement creates a variable called and stores the text in it, which is the full name of
Hunter's pianist. Esta sentencia crea una variable de cadena llamada FullName y almacena
el texto Ada McGrath Stewart en él, que es el nombre completo de la pianista Hunter. In a
Java statement, a string is denoted with double quotation marks around the text. En un
comunicado de Java, una cadena que se denota con comillas dobles alrededor del texto.
These quote marks will not be included in the string itself. Estas comillas no se incluirá en
la propia cadena.

Unlike the other types of variables that you have used-- , , , , and so on--the type is
capitalized. A diferencia de los otros tipos de variables que se han utilizado - int, float,
char booleano, etc - el tipo de cadena se escribe con mayúscula. The reason for this is
that strings are somewhat different than the other variable types in Java. La razón de esto es
que las cadenas son algo diferentes de los tipos de otra variable en Java. Strings are a
special resource called objects, and the types of all objects are capitalized. Las cadenas son
un recurso especial denominado objetos, y los tipos de todos los objetos están en
mayúsculas. You'll be learning about objects during Hour 10, "Creating Your First Object."
Usted aprenderá acerca de los objetos durante la hora 10, "Creación de su primer objetivo."
The important thing to note during this hour is that strings are different than the other
variable types, and because of this difference, is capitalized when strings are used in a
statement. La cosa importante a tener en cuenta durante esta hora es que las cadenas son
diferentes de los tipos de otra variable, y debido a esta diferencia, String se escribe con
mayúscula cuando las cadenas se usan en un comunicado.

Displaying Strings in Programs Viendo las cadenas en los programas


The most basic way to display a string in a Java program is with the statement. La forma
más básica para mostrar una cadena en un programa Java es con el System.out.println
() declaración. This statement takes any strings and other variables inside the parentheses
and displays them. Esta declaración tiene todas las cadenas y otras variables dentro de los
paréntesis y los muestra. The following statement displays a line of text to the system
output device, which is the computer's monitor: La siguiente declaración muestra una línea
de texto al dispositivo de salida del sistema, que es el equipo de monitor:

System.out.println("Silence affects everyone in the


end."); System.out.println ("El silencio nos afecta a todos
al final.");

The preceding statement would cause the following text to be displayed: La declaración
anterior podría causar el siguiente texto que se muestra:

Silence affects everyone in the end. El silencio nos


afecta a todos al final.

Displaying a line of text on the screen is often called printing, which is what stands
for--"print this line." Visualización de una línea de texto en la pantalla se llama a menudo la
impresión, que es lo que println () representa - "esta línea. Impresión" You can use the
statement to display text within double quotation marks and also to display variables, as
you will see. Usted puede utilizar el System.out.println () para mostrar el texto entre
comillas dobles y también para mostrar las variables, como se verá. Put all material that
you want to be displayed within the parentheses. Ponga todo el material que desea que se
muestre dentro de los paréntesis.

Using Special Characters in Strings Uso de caracteres especiales en cadenas


When a string is being created or displayed, its text must be enclosed within double
quotation marks to indicate the beginning and end of the string. Cuando una cadena se crea
o se muestra, su texto debe escribirse entre comillas dobles para indicar el principio y el
final de la cadena. These quote marks are not displayed, which brings up a good question:
What if you want to display double quotation marks? Estas comillas no se muestran, que
será una buena pregunta: ¿Qué pasa si usted desea mostrar comillas dobles?

In order to display them, Java has created a special code that can be put into a string: .
Whenever this code is encountered in a string, it is replaced with a double quotation mark.
For example, examine the following: Con el fin de mostrarlos, Java ha creado un código
especial que se puede poner en una cadena: ". \ Cada vez que el código se encuentra en
una cadena, se sustituye con un signo de comillas dobles siguiente. Por ejemplo, examinar
el:

System.out.println("Jane Campion directed \"The Piano\" in


1993."); System.out.println ("Jane Campion dirigido \" El
Piano \ "en 1993.");
This code is displayed as the following: Este código se muestra como lo siguiente:

Jane Campion directed "The Piano" in 1993. Jane Campion


dirigió "The Piano" en 1993.

You can insert several special characters into a string in this manner. Puede insertar
caracteres especiales de varias en una cadena de esta manera. The following list shows
these special characters; note that each is preceded by a backslash (\). La siguiente lista
muestra estos caracteres especiales, tenga en cuenta que cada uno está precedido por una
barra invertida (\).

Special characters
Los caracteres Display Mostrar
especiales

Single quotation
\ ' mark comilla
simple

Double quotation
\ " mark Doble
comilla

Backslash Barra
\ \
invertida

\ T Tab Ficha

Backspace
\ B
Retroceso

Carriage return
\ R
Retorno de carro

Formfeed
\ F
Formfeed

Newline Nueva
\ N
línea

The newline character causes the text following the newline character to be displayed at the
beginning of the next line. El carácter de nueva línea hace que el texto que sigue al carácter
de nueva línea se muestren al principio de la línea siguiente. Look at this example: Mira
este ejemplo:
System.out.println("Music by\nMichael Nyman");
System.out.println ("Música de \ nMichael Nyman");

This statement would be displayed as the following: Esta afirmación se mostraría como la
siguiente:

Music by Música de
Michael Nyman Michael Nyman

Pasting Strings Together Cuerdas pegar Juntos


When you use the statement and handle strings in other ways, you will sometimes want to
paste two strings together. Cuando se utiliza el System.out.println () declaración y
manejar cadenas de otras maneras, a veces se desea pegar dos cadenas juntas. You do this
by using the same operator that is used to add numbers: . Esto se hace utilizando el mismo
operador que se utiliza para agregar los números: +.

The operator has a different meaning in relation to strings. El operador + tiene un


significado diferente en relación a las cadenas. Instead of trying to do some math, it pastes
two strings together. En lugar de tratar de hacer algunos cálculos, lo pega dos cadenas
juntas. This action can cause strings to be displayed together, or it can make one big string
out of two smaller ones. Esta acción puede causar cadenas se muestren juntos, o se puede
hacer uno con cadena grande de los dos más pequeños. Concatenation is a word used to
describe this action, because it means to link two things together. La concatenación es una
palabra usada para describir esta acción, porque significa vincular dos cosas juntas. You'll
probably see this term in other books as you build your programming skills, so it's worth
knowing. Es probable encontrar este término en otros libros como a construir sus
habilidades de programación, por lo que vale la pena conocer. However, pasting is the term
used here to describe what happens when one string and another string decide to get
together. Sin embargo, pegar es el término usado aquí para describir lo que sucede cuando
una cadena y otra cadena decide reunirse. Pasting sounds like fun. Pegar suena divertido.
Concatenating sounds like something that should never be done in the presence of an open
flame. Concatenación de sonidos como algo que nunca debe hacerse en presencia de una
llama abierta.

The following statement uses the operator to display a long string: La declaración siguiente
se utiliza el operador + para mostrar una cadena larga:

System.out.println("\"\'The Piano\' is as peculiar and


haunting as any film " + System.out.println ("\" \ "El
Piano \ 'es tan peculiar e inquietante como cualquier
película" +
"I've seen.\"\n\t-- Roger Ebert, \'Chicago
Sun-Times\'"); "He visto \". \ N \ t - Roger Ebert, \
'Chicago Sun-Times \ "");

Instead of putting this entire string on a single line, which would make it harder to
understand when you look at the program later, the operator is used to break up the text
over two lines of the program's Java text file. En lugar de poner toda esta cadena en una
sola línea, lo que haría más difícil de entender si nos fijamos en el programa más tarde, el
operador + se utiliza para dividir el texto en dos líneas de programa Java de archivo de
texto. When this statement is displayed, it will appear as the following: Cuando esta
declaración se muestra, aparecerá como el siguiente:

"`The Piano' is as peculiar and haunting as any film I've


seen." "` El 'Piano es tan peculiar e inquietante como
cualquier película que he visto. "
-- Roger Ebert, `Chicago Sun-Times' - Roger Ebert,
"Chicago Sun-Times '

Several special characters are used in the string: , , , and . To better familiarize yourself
with these characters, compare the output with the statement that produced it. Varios
caracteres especiales se utilizan en la cadena: ", \", \ n, y \ t. \ Para familiarizarse
mejor con estos personajes, comparar la salida con el System.out.println () que lo
produjo.

Using Other Variables with Strings Uso de otras variables con cadenas
Although you can use the operator to paste two strings together, as demonstrated in the
preceding section, you will use it more often to link strings and variables. Aunque puede
utilizar el operador + para pegar dos cadenas, como se demuestra en la sección anterior, lo
va a usar con más frecuencia para enlazar cadenas y variables. Take a look at the following:
Echa un vistazo a lo siguiente:

int length = 121; int longitud = 121;


char rating = `R'; Valoración char = `R ';
System.out.println("Running time: " + length + "
minutes"); System.out.println ("Tiempo de ejecución:" +
largo + "minutos");
System.out.println("Rated " + rating); System.out.println
("nominal" calificación A +);

This code will be displayed as the following: Este código se mostrará como la siguiente:

Running time: 121 minutes Duración: 121 minutos


Rated R Rated R

This example displays a unique facet about how the operator works with strings. Este
ejemplo muestra una faceta única acerca de cómo el operador + funciona con cadenas. It
can allow variables that are not strings to be treated just like strings when they are
displayed. Se puede permitir que las variables que no son cadenas a ser tratada igual que las
cadenas cuando se muestran. The variable is an integer set to the value 121. La longitud
variable es un número entero establece en el valor 121. It is displayed between the strings
and . Es que aparecen entre las cuerdas Duración: y los minutos. The statement is being
asked to display a string plus an integer plus another string. El System.out.println ()
Declaración de que se pide para mostrar una cadena, más un número entero, más otra
cadena. This statement works because at least one part of the group is a string. Esta
declaración funciona porque al menos una parte del grupo es una cadena. The Java
language offers this functionality to make displaying information easier. El lenguaje Java
ofrece esta funcionalidad para mostrar la información más fácil.

One thing that you might want to do with a string is paste something to it several times, as
in the following example: Una cosa que usted puede ser que quiere hacer con una cadena es
algo pegar varias veces, como en el ejemplo siguiente:

String searchKeywords = ""; SearchKeywords cadena = "";


searchKeywords = searchKeywords + "drama "; searchKeywords
searchKeywords + = "drama";
searchKeywords = searchKeywords + "romance ";
searchKeywords searchKeywords + = "romance";
searchKeywords = searchKeywords + "New Zealand ";
searchKeywords searchKeywords + = "Nueva Zelanda";

This code would result in the variable being set to . Este código se traduciría en la variable
searchKeywords se establece en el drama romántico de Nueva Zelanda. The first
line creates the variable and sets it to be an empty string because there's nothing between
the double quotation marks. La primera línea crea la variable searchKeywords y establece
que sea una cadena vacía porque no hay nada entre las comillas dobles. The second line
sets the variable equal to its current string plus the string added to the end. La segunda
línea define la variable searchKeywords igual a su serie actual más el drama cadena añade
al final. The next two lines add and in the same way. Las siguientes dos líneas de añadir
el romance y la Nueva Zelanda de la misma manera.

As you can see, when you are pasting more text at the end of a variable, the name of the
variable has to be listed twice. Como puede ver, cuando se le pega más texto al final de una
variable, el nombre de la variable tiene que ser repetida en la lista. Java offers a shortcut to
simplify this process a bit: the operator. Java ofrece un acceso directo para simplificar este
proceso un poco: el operador + =. The operator combines the functions of the and
operators. El operador + = combina las funciones de los operadores = y +. With strings, it
is used to add something to the end of an existing string. Con cadenas, se utiliza para añadir
algo al final de una cadena existente. The example can be shortened by using , as shown in
the following code: El ejemplo searchKeywords se puede acortar usando + =, como se
muestra en el siguiente código:

String searchKeywords = ""; SearchKeywords cadena = "";


searchKeywords += "drama "; searchKeywords + = "drama";
searchKeywords += "romance "; searchKeywords + =
"romance";
searchKeywords += "New Zealand "; searchKeywords + =
"Nueva Zelanda";

This code produces the same result: is set to . Este código produce el mismo resultado:
searchKeywords se establece en el drama romántico de Nueva Zelanda.

Advanced String Handling Avanzado manejo de cadenas


In addition to creating strings, pasting them together, and using them with other types of
variables, there are several different ways you can examine a string variable and change its
value. Además de la creación de cadenas, pegar juntos, y su uso con otros tipos de
variables, hay varias maneras diferentes que usted puede examinar una variable de cadena y
cambiar su valor. These advanced features are possible because strings are objects in the
Java language. Estas funciones avanzadas son posibles porque las cadenas son objetos en el
lenguaje Java. Working with strings develops skills that you'll be using to work with other
objects later. Trabajar con cadenas desarrolla habilidades que usted va a utilizar para
trabajar con otros objetos más tarde.

Comparing Two Strings Comparando dos cadenas

One thing you will be testing often in your programs is whether one string is equal to
another. Una cosa que pondrá a prueba a menudo en sus programas es si una cadena es
igual a otro. You do this by using in a statement with both of the strings, as in this
example: Esto se hace utilizando equals () en un comunicado con los dos de las cuerdas,
como en este ejemplo:

String favorite = "piano"; Cadena favorita = "piano";


String guess = "ukelele"; Supongo cadena = "ukelele";
System.out.println("Is Ada's favorite instrument a " +
guess + "?"); System.out.println ("es el favorito
instrumento Ada un" + + supongo "?");
System.out.println("Answer: " + favorite.equals(guess));
System.out.println ("Respuesta:" + favorite.equals
(supongo));

This example uses two different string variables. En este ejemplo se utiliza dos variables de
cadena diferentes. One, , is used to store the name of Ada's favorite instrument: a piano.
Uno, el favorito, se utiliza para almacenar el nombre de Ada favoritos instrumento: el
piano. The other, , is used to store a guess as to what her favorite might be. Los otros,
supongo, se utiliza para almacenar una conjetura en cuanto a lo que podría ser su favorito.
The guess is that Ada prefers the ukelele. La conjetura es que Ada prefiere el ukelele.

The third line displays the text followed by the value of the variable and then a question
mark. La tercera línea muestra el texto es el favorito de un instrumento Ada
seguido por el valor de la variable respuesta y después un signo de interrogación. The
fourth line displays the text and then contains something new: La cuarta línea muestra el
texto Respuesta: y, a continuación contiene algo nuevo:

favorite.equals(guess) favorite.equals (supongo)

This part of the statement is known as a method. Esta parte de la declaración que se conoce
como un método. A method is a way to accomplish a task in a Java program. Un método es
un camino para realizar una tarea en un programa Java. This method's task is to determine
if one string, , has the same value as another string, . Este método de trabajo consiste en
determinar si una cadena, el favorito, tiene el mismo valor que otra cadena, supongo. If
the two string variables have the same value, the text will be displayed. Si las dos variables
de cadena tienen el mismo valor, el verdadero texto en la pantalla. If not, the text will be
displayed. Si no, el texto falso en la pantalla. The following is the output of this example:
La siguiente es la salida de este ejemplo:

Is Ada's favorite instrument a ukelele? Es el favorito


instrumento Ada un ukelele?
Answer: false Respuesta: Falso

Determining the Length of a String La determinación de la longitud de una cadena

It can be useful at times to determine the length of a string in characters. Puede ser útil a
veces para determinar la longitud de una cadena de caracteres. You do this by using the
method. Esto se hace mediante el método length (). This method works in the same
fashion as the method, except that only one string variable is involved. Este método
funciona de la misma manera como el método equals (), excepto que sólo una variable de
cadena se tratara. Look at the following example: Mira el siguiente ejemplo:

String cinematographer = "Stuart Dryburgh"; Cadena de


fotografía = "Stuart Dryburgh";
int nameLength = cinematographer.length(); nameLength int
= cinematographer.length ();

This example sets , an integer variable, equal to 15. Este ejemplo establece nameLength,
una variable entera, igual a 15. The method counts the number of characters in the string
variable called , and this count is assigned to the integer variable. El
cinematographer.length () método cuenta el número de caracteres en la variable
denominada cadena de fotografía, y esta cuenta se asigna a la variable entera
nameLength.

Changing a Strings Case Cambio de un caso de cadenas

Because computers take everything literally, it's easy to confuse them. Como los equipos
toman todo literalmente, es fácil confundirlos. Although a human would recognize that the
text Harvey Keitel and the text HARVEY KEITEL are referring to the same thing, most
computers would disagree. A pesar de un ser humano se reconoce que el texto Harvey
Keitel y el texto Harvey Keitel se refieren a lo mismo, la mayoría de las computadoras
estarían en desacuerdo. For instance, the method discussed previously in this hour would
state authoritatively that Harvey Keitel is not equal to HARVEY KEITEL. Por ejemplo, el
método equals () descrito anteriormente en esta hora que el estado con autoridad que
Harvey Keitel no es igual a Harvey Keitel.

To get around some of these obstacles, Java has methods that display a string variable as all
uppercase letters ( ) or all lowercase letters ( . Para solucionar algunos de estos obstáculos,
Java dispone de métodos que muestran una variable de cadena como todas las letras
mayúsculas (toUpperCase ()) o letras minúsculas (toLowerCase ()). The following
example shows the method in action: En el ejemplo siguiente se muestra el toUpperCase
() en acción:

String baines = "Harvey Keitel"; Baines cadena = "Harvey


Keitel";
String change = baines.toUpperCase(); String = cambio
baines.toUpperCase ();
This code sets the string variable equal to the string variable converted to all uppercase
letters-- , in other words. Este código establece el cambio de variable de cadena igual a la
variable de cadena Baines convierte todas las letras mayúsculas - Harvey Keitel, en
otras palabras. The method works in the same fashion but returns an all-lowercase string
value. El toLowerCase () método funciona de la misma manera, pero devuelve un valor
de cadena en minúsculas, todo.

Workshop: Presenting Credits Taller: Presentación de Créditos


Ada McGrath Stewart was thrown into unfamiliar territory when she moved from Scotland
to New Zealand to marry a stranger who didn't appreciate her ivory tickling. Ada McGrath
Stewart fue arrojado a un territorio desconocido cuando se trasladó de Escocia a Nueva
Zelanda para casarse con un extranjero que no valoraron su cosquilleo de marfil. You might
have felt similarly lost with some of the topics introduced during this hour. Es posible que
haya perdido sentido similar con algunos de los temas introducidos durante esta hora.

As a workshop to reinforce the string handling features that have been covered, you will
write a Java program to display credits for a feature film. Como un taller para reforzar la
cadena de manejo de las características que han sido cubiertos, usted va a escribir un
programa Java para mostrar los créditos de una película. You have three guesses as to the
movie chosen, and if you need a hint, it starts with a The and ends with a musical
instrument that can be used to express the repressed passion of attractive mutes. Usted tiene
tres suposiciones en cuanto a la película elegida, y si usted necesita una pista, que comienza
con una y termina con un instrumento musical que se puede utilizar para expresar la pasión
reprimida de silencia atractivo.

Load the word processor you're using to write Java programs and create a new file called .
Cargar el procesador de textos que está utilizando para escribir programas Java y crear un
nuevo archivo llamado Credits.java. Enter the text of Listing 6.1 into the word
processor and save the file when you're done. Introduzca el texto del listado 6.1 en el
procesador de texto y guarde el archivo cuando haya terminado.

Listing 6.1. Listado 6.1. The Credits program. El programa de créditos.


1: class Credits { 2: public static void main(String[]
arguments) { 3: // set up film information 4: String title
= "The Piano"; 5: int year = 1993; 6: String director =
"Jane Campion"; 7: String role1 = "Ada"; 8: String actor1 =
"Holly Hunter"; 9: String role2 = "Baines"; 10: String
actor2 = "Harvey Keitel"; 11: String role3 = "Stewart"; 12:
String actor3 = "Sam Neill"; 13: String role4 = "Flora";
14: String actor4 = "Anna Paquin"; 15: // display
information 16: System.out.println(title + " (" + year +
")\n" + 17: "A " + director + " film.\n\n" + 18: role1 +
"\t" + actor1 + "\n" + 19: role2 + "\t" + actor2 + "\n" +
20: role3 + "\t" + actor3 + "\n" + 21: role4 + "\t" +
actor4); 22: } 1: Créditos de clase {2: public static void
main (String [argumentos]) {3: / / hasta cine información
que figura 4: título String = "El Piano"; 5: int año =
1993; 6: director de cadena = "Jane Campion "; 7: String
role1 =" Ada ", 8: String actor1 =" Holly Hunter "; 9:
String role2 =" Baines "; 10: String actor2 =" Harvey
Keitel "; 11: String role3 =" Stewart "; 12: String actor3
= "Sam Neill"; 13: String role4 = "Flora"; 14: String
actor4 = "Anna Paquin"; 15: / / información de la pantalla
16: System.out.println (título + "(" + años + ") \ n" +
17:. \ n \ n "" "A + + director de" cine + 18: role1 + "\
t" + actor1 + "\ n" + 19: role2 + "\ t" + actor2 + "\ n" +
20: role3 + "\ t" + actor3 + "\ n" + 21: role4 + "\ t" +
actor4); 22:} 23:}

Before you attempt to compile the program with the tool, look over the program and see
whether you can figure out what it's doing at each stage. Antes de intentar compilar el
programa con la herramienta javac, revisa el programa y ver si puede averiguar lo que
está haciendo en cada etapa. Here's a breakdown of what's taking place: He aquí un
desglose de lo que está ocurriendo:

 Line 1 gives the Java program the name . Línea 1 se presenta el programa Java los
Créditos nombre.
 Line 2 begins the block statement in which all of the program's work gets done. Línea 2
comienza el main () sentencia de bloque en el que todo el programa de trabajo de la se
hace.
 Line 3 is a comment statement explaining that you're going to set up the film's information
in subsequent lines. La línea 3 es una declaración comentario explicando que vamos a
configurar la información de la película en las líneas siguientes.
 Lines 4-14 set up variables to hold information about the film, its director, and its stars.
Líneas 4-14 establecer las variables que guardan información sobre la película, su director
y sus estrellas. One of the variables, , is an integer. Una de las variables, el año, es un
número entero. The rest are string variables. El resto son variables de cadena.
 Line 15 is another comment line for the benefit of humans like us examining the program.
La línea 15 es otra línea de comentario para el beneficio de los seres humanos como
nosotros examinar el programa.
 Lines 16-21 are one long statement. Líneas 16-21 son una larga System.out.println
() declaración. Everything between the first parenthesis on Line 16 and the last
parenthesis on Line 21 is displayed on-screen. Todo lo que entre el primer paréntesis en la
línea 16 y el último paréntesis en la línea 21 se muestra en pantalla. The newline text ( )
causes the text after it to be displayed at the beginning of a new line. El texto de nueva
línea (\ n) hace que el texto después de que se muestren en el inicio de una nueva línea.
The Tab text ( ) inserts Tab spacing in the output. El texto de la pestaña (\ t) inserta el
espaciado de tabulación en la salida. The rest is either text or string variables that should
be shown. El resto es bien variables de texto o una cadena que se debe mostrar.
 Line 22 ends the block statement. La línea 22 termina la main () sentencia de bloque.
 Line 23 ends the program. La línea 23 termina el programa.
Attempt to compile the program by going to the directory that contains and typing this
command: Intento de compilar el programa, vaya al directorio que contiene Credits.java
y escribir este comando:

javac Credits.java javac Credits.java

If you do not see any error messages, the program has compiled successfully, and you can
run it with the following command: Si usted no ve ningún mensaje de error, el programa ha
recopilado con éxito, y se puede ejecutar con el siguiente comando:

java Credits java Créditos

If you do encounter error messages, correct any typos that you find in your version of the
program and try again to compile it. Si usted encuentra mensajes de error, corregir las
erratas que encuentre en su versión del programa de créditos e inténtelo de nuevo para su
recopilación.

Listing 6.2 shows the output of the program: a rundown of the film, year of release,
director, and the four lead performers from The Piano. Listado 6.2 muestra la salida del
programa de créditos: un resumen de la película, año de lanzamiento, el director, y los
cuatro intérpretes de plomo de El Piano. Be glad that you didn't have to present the credits
for an ensemble film. Alégrate de que no tienen que presentar los créditos de una película
coral. A program detailing Robert Altman's Short Cuts, the 1993 film with more than 25
lead characters, could hog an hour on typing alone. Un programa detallado Short Cuts de
Robert Altman, la película de 1993 con más de 25 personajes principales, cerdo podría hora
de escribir solo.

Listing 6.2. Listado 6.2. The output of the Credits program. La salida del programa de
créditos.

The Piano 1993 El Piano 1993


A Jane Campion film. Una película de Jane Campion.
Ada Holly Hunter Ada Holly Hunter
Baines Harvey Keitel Baines Harvey Keitel
Stewart Sam Neill Stewart, Sam Neill
Flora Anna Paquin

If this hour's trivia related to The Piano and the films of director Jane Campion has sparked
your curiosity, or if you just dig quiet women in braids, visit the following World Wide
Web sites: Magnus Hjelstuen's unofficial The Piano Web site, with cast descriptions,
storyline discussion, and comprehensive details about his favorite movie: Si la hora de la
trivia de este relacionado con el piano y las películas de Jane Campion ha despertado su
curiosidad, o si simplemente excavar las mujeres calma en trenzas, visite los siguientes
sitios de World Wide Web: Magnus Hjelstuen no oficial n El sitio Web de Piano, con
descripciones de reparto , la discusión historia y detalles completos acerca de su película
preferida:

http://www.ifi.uio.no/ ~ magnush / Piano /

The Internet Movie Database, a voluminous yet searchable database of movies, TV shows,
actors, directors, yet other related topics: n La Internet Movie Database, sin embargo, una
búsqueda de base de datos voluminosa de las películas, programas de televisión, actores,
directores, sin embargo, otros temas relacionados:

http://www.imdb.com

Summary Resumen
Once your version of works like the one shown in Listing 6.2, give yourself some credits,
too. Una vez que su versión de Créditos obras como la que se muestra en el listado 6.2,
dan un poco de créditos, también. You're writing longer Java programs and dealing with
more sophisticated issues each hour. Usted está escribiendo ya los programas de Java y se
ocupan de cuestiones más sofisticadas cada hora. Like variables, strings are something
you'll use every time you sit down to write a program. Al igual que las variables, las
cadenas son algo que vamos a usar cada vez que te sientas a escribir un programa.

At the beginning of The Piano, Holly Hunter's Ada lost her piano when her new husband
refused to make his Maori laborers carry it home. Al comienzo de El Piano, Holly Hunter
Ada ha perdido su piano cuando su nuevo marido se negó a hacer sus trabajadores maoríes
llevarlo a casa. Luckily for you, the ability to use strings in your Java programs cannot be
taken away by an insensitive newlywed or anyone else. Por suerte para usted, la capacidad
de utilizar las cadenas en sus programas Java no puede ser llevado por una recién casada
insensible o cualquier otra persona. You'll be using strings in many ways to communicate
with users. Usted va a usar cadenas en muchas formas de comunicarse con los usuarios.

Q&A Q & A
Q In addition to System.out.println(), what are some other ways to display strings in
Java programs? Q Además de System.out.println (), ¿cuáles son algunas otras maneras
de mostrar cadenas en los programas de Java?

A Strings can be displayed using different means in Java programs that run on World Wide
Web pages and in programs that have a graphical user interface. Un cadenas se pueden
mostrar utilizando diferentes medios en los programas de Java que se ejecutan en las
páginas World Wide Web y en los programas que tienen una interfaz gráfica de usuario.
Web page Java programs, which are called applets, rely on a method called to display
text. Página web los programas de Java, que se llaman applets, se basan en un método
llamado drawString () para mostrar el texto. Hour 13, "Learning How Applets Work,"
covers several programming features that are specific to applet programming. Hora 13,
"Aprender applets de trabajo", cubre varias características de programación que son
específicos de applet de programación. Programs that have a graphical user interface
display strings by putting them into a text-entry field or displaying them as a label next to
some other part of the program's window. Los programas que tienen una gráfica de
usuario cadenas de exhibición del interfaz y de ponerlo en un campo de entrada de texto o
las muestra como una etiqueta junto a alguna otra parte de la ventana del programa.

Q How can I set the value of a string variable to be blank? Q ¿Cómo puedo establecer el
valor de una variable de cadena en blanco?

A A pair of double quotation marks without any text between them is considered to be an
empty string. Un par Una de comillas dobles sin ningún tipo de texto entre ellos se
considera que es una cadena vacía. You can set a string variable equal to this upon its
creation or in other parts of your programs. Puede establecer una variable de cadena igual
a este momento de su creación o en otras partes de sus programas. The following code
creates a new string variable called and sets it to nothing: El siguiente código crea una
nueva variable de cadena adaSays llamada y establece que a nada:

String adaSays = ""; AdaSays cadena = "";

Q Is there a way to make the text in one println() statement start right at the end of the
text in the preceding println() statement? Q ¿Hay una manera de hacer el texto en un
println () buen comienzo en la última sección del texto en el anterior println () estado de
cuenta? I don't want the second println() statement to start at the beginning of a new
line, but it always does. No quiero que el segundo println () para empezar por el
principio de una nueva línea, pero no siempre.

A Java automatically starts each statement on its own new line, so the only way to
prevent this is to use a statement that includes all of the text you want to display. Un Java
se inicia automáticamente cada System.out.println () declaración sobre su nueva
línea propia, por lo que la única manera de evitar esto es utilizar una declaración que
incluye todo el texto que desea mostrar. The program from the workshop has an example
of a statement that includes several different lines of output. El programa de créditos
del taller tiene un ejemplo de un println () que incluye varias líneas diferentes de
producción. Take a look at it and see whether it fits what you want to do. Echa un vistazo y
ver si se ajusta a lo que quieres hacer.

Q If the + operator is used with strings to link up two different strings, can you add the
numeric value of one string to the value of another? Q Si el operador + se utiliza con
cadenas para unir dos cuerdas diferentes, puede agregar el valor numérico de una
cadena en el valor de otro?

A You can use the value of a variable as an integer only by using a method that A Usted
puede utilizar el valor de una variable String como un entero sólo utilizando un método
que
converts the string's value into a numeric form. convierte el valor de la cuerda en una
forma numérica. This procedure is called casting because it recasts existing information, in
this case a string, as a different type of information. Este procedimiento se llama casting,
ya que una refundición de la información existente, en este caso una cadena, como un
tipo diferente de información.

Q Is it necessary to use += instead of + when adding some text to a string variable? Q ¿Es
necesario el uso de + = en lugar de + al añadir un texto a una variable de cadena?

A Not at all. Un No, en absoluto. The operator is strictly for the benefit of programmers
who want to use it as a shortcut. El operador + = es estrictamente para el beneficio de los
programadores que quieran usarlo como un acceso directo. If you're more comfortable
using the operator when pasting some added text to a string variable, you ought to stick
with it. Si te sientes más cómodo utilizando el operador + al pegar un texto añadido a una
variable de cadena, usted debe pegarse con él. The time and convenience you can gain by
using will be lost pretty quickly if it causes you to make errors in your program. El tiempo
y la comodidad que se puede obtener mediante el uso de + = se pierde muy rápidamente
si se le hace cometer errores en su programa.

Q Isn't there some kind of == operator that can be used to determine whether two
strings have the same value, as in daughter == "Flora"? Q ¿No hay algún tipo de
operador == que se pueden utilizar para determinar si dos cadenas tienen el mismo
valor, como la hija de == "Flora"?

A As you will discover during the next hour, "Using Conditional Tests to Make Decisions,"
the operator can be used with all of the variable types except for strings. A medida que se
descubre durante la hora siguiente, "con pruebas condicionales para tomar decisiones", el
operador == se puede utilizar con todos los tipos de variables, excepto para las cadenas.
The reason for the difference is that strings are objects. La razón de esta diferencia es que
las cadenas son objetos. Java treats objects differently than other types of information, so
special methods are necessary to determine whether one string is equal to another. Java
trata los objetos de manera diferente que otros tipos de información, por lo que los
métodos especiales son necesarios para determinar si una cadena es igual a otro.

Q Do all methods in Java display true or false in the same way that the equals() method
does in relation to strings? Q ¿Todos los métodos en Java pantalla verdadera o falsa de
la misma manera que el método equals () lo hace en relación a las cadenas?

A Methods have different ways of making a response after they are used. Una métodos
tienen diferentes maneras de dar una respuesta después de que se utilizan. When a
method sends back a value, as the method does, this is called returning a value. Cuando
un método devuelve un valor, como el método equals () lo hace, esto se llama devolver
un valor. The method is set to return a Boolean value. El método equals () se establece
para devolver un valor booleano. Other methods might return a string, an integer, another
type of variable, or nothing at all. Otros métodos pueden devolver una cadena, un entero,
otro tipo de variables, o nada en absoluto.

Quiz Quiz
The following questions will test your knowledge of the care and feeding of a string. Las
siguientes preguntas se pondrá a prueba sus conocimientos sobre el cuidado y alimentación
de una cadena.

Questions Preguntas

1. My friend concatenates. 1. Mi amigo concatena. Should I report him to the authorities?


En caso de que le informe a las autoridades?

(a) No. (A) No. It's illegal only during the winter months. Es ilegal que sólo durante los
meses de invierno.
(b) Yes, but not until I sell my story to Hard Copy first. (B) Sí, pero no hasta que vender mi
historia que dura la primera copia.
(c) No. (C) No. All he's doing is pasting two strings together in a program. Todo lo que está
haciendo es pegar dos cadenas juntas en un programa.

2. Why is the word capitalized while and others are not? 2. ¿Por qué es la palabra
cadena en mayúsculas, mientras que int y otros no?

(a) is a full word, but ain't. (A) La cadena es una palabra completa, pero no es int.
(b) Like all objects in Java, has a capitalized name. (B) Al igual que todos los objetos en
Java, String tiene un nombre en mayúsculas.
(c) Poor quality control at JavaSoft. (C) Deficiente control de calidad en JavaSoft.

3. Which of the following characters will put a single quote in a string? 3. ¿Cuál de los
siguientes caracteres pondrá una comilla simple en una cadena?

(a) (A) <quote>


(b) (B) \ '
(c) (C) »

Answers Respuestas

1. c. 1. C. Concatenation is just another word for pasting, joining, melding, or otherwise


connecting two strings together. La concatenación es sólo otra palabra para pegar, unir,
fusionar, o de otra manera la conexión de dos cadenas juntas. It uses the and operators.
Utiliza los botones + y + = operadores.

2. b. 2. B. The types of objects available in Java are all capitalized, which is the main reason
variable names have a lowercase first letter. Los tipos de objetos disponibles en Java se
escriben en mayúsculas, que es la principal razón de los nombres de variable tiene una
letra minúscula en primer lugar. It makes it harder to mistake them for objects. Esto hace
que sea más difícil de confundir con los objetos.
3. b. 3. B. The single backslash is what begins one of the special characters that can be
inserted into strings. La barra invertida es lo que empieza uno de los caracteres especiales
que se pueden insertar en cadenas.

Activities Actividades
You can review the topics of this hour more fully with the following activities: Usted puede
revisar los temas de esta hora más plenamente con las siguientes actividades:

 Write a short Java program called that puts the code from this hour's "Comparing Two
Strings" section into the block statement. Escriba un breve programa de Java llamada
preferido que pone el código de esta hora de "comparar dos cadenas" en la sección)
bloque de instrucciones (principal. Test it out to make sure it works as described and
says that Ada's favorite instrument is not the ukelele. Probarlo para asegurarse de que
funciona como se describe y dice que instrumento favorito de Ada no es el ukelele. Then,
change the initial value of the variable from to . A continuación, cambie el valor inicial de
la variable de adivinar por ukelele al piano. See what happens. Vea lo que sucede.
 Modify the program so that the names of the director and all performers are displayed
entirely in uppercase letters. Modificar el programa de créditos para que los nombres
del director y todos los artistas se muestran totalmente en letras mayúsculas.

 7 horas
o Uso de pruebas condicionales para tomar decisiones
 si las declaraciones
 A menos que y mayor que las comparaciones
 Las comparaciones de igualdad y no igualdad
 La organización de un programa con el Bloque declaraciones
 Listado 7.1. Un programa Java con un main () sentencia de bloque.
 Listado 7.2. La salida del programa de juego.
 if-else declaraciones
 interruptor de declaraciones
 El operador condicional
 Taller: Mirando el reloj
 Listado 7.3. El texto completo de ClockTalk.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 7 7 horas

Using Conditional Tests to Make Decisions Uso de


pruebas condicionales para tomar decisiones

Writing a computer program has been compared to telling a household robot what to do.
Escribir un programa de ordenador ha sido comparado con decirle a un robot para el hogar
lo que debe hacer. You provide the computer a list of instructions, called statements, and
these instructions are followed to the letter. Usted proporciona el equipo una lista de
instrucciones, declaraciones llamada, y estos se siguen las instrucciones de la carta. You
can tell the computer to work out some unpleasant mathematical formulas, and it will work
them out for you. Usted puede decirle a la computadora para trabajar algunas fórmulas
matemáticas desagradables, y les funciona para usted. Tell it to display some information,
and it will dutifully respond. Dile que muestre alguna información, y es capaz de responder
adecuadamente.

However, there are times when you need the computer to be more selective about what it
does. Sin embargo, hay ocasiones en las que necesita el equipo para ser más selectivo con
lo que hace. For example, if you have written a program to balance your checkbook, you
might want the computer to display a warning message if your account is overdrawn. Por
ejemplo, si usted ha escrito un programa para balancear su chequera, usted puede ser que
desea que el equipo muestre un mensaje de advertencia si su cuenta está sobregirada. The
warning could be something along the lines of La advertencia podría ser algo a lo largo de
las líneas de oír que el ruido rebote? The computer should display this message only
if your account is overdrawn. Es su control. El equipo debe mostrar este mensaje sólo si
su cuenta está sobregirada. If it isn't, the message would be both inaccurate and emotionally
upsetting. Si no es así, el mensaje sería inexacta y emocionalmente perturbador.

The way to accomplish this task in a Java program is to use a statement called a
conditional. La forma de realizar esta tarea en un programa Java es el uso de una
declaración llamada condicional. Conditionals cause something to happen in a program
only if a specific condition is met. algo Condicionales causar a suceder en un programa sólo
si la condición expresa de que se cumpla. Country star Kenny Rogers sang with the hippie-
rock group The First Edition in the late '60s, and one of the group's singles hit the top 5 in
1968: "Just Dropped In (To See What Condition My Condition Was In)". La estrella del
country Kenny Rogers cantó con el grupo hippie-rock La primera edición de finales de los
60, y uno de los sencillos del grupo llegó a los top 5 en 1968: "Mas Bajas En (Para ver que
Mi Condena A)". During this hour, you'll be dropping in to check the condition of several
things in your Java programs using the conditional statements , , , , and . Durante esta
hora, estará cayendo en comprobar el estado de varias cosas en los programas Java
utilizando las sentencias condicionales, de lo contrario, el interruptor, si es el
caso, y se rompa. You also will be using several conditional operators: , , , , and .
También se va a utilizar varios operadores condicionales:,! == =, <,>, Y?. The
following topics will be covered: Los siguientes temas serán cubiertos:

 Testing to see whether conditions are met Prueba a ver si se cumplen las condiciones
 Using the statement for basic conditional tests Utilización de la sentencia, si para las
pruebas básicas condicional
 Using other statements in conjunction with Uso de otros estados en relación con el caso
 Testing whether one value is greater than or less than another Probar si un valor es mayor
o menor que otro
 Testing whether two values are equal or unequal Probar si dos valores son iguales o
desiguales
 Using statements as the opposite of statements Utilización de sentencias bien como lo
contrario de si las declaraciones
 Chaining several conditional tests together Encadenamiento de varias pruebas
condicionales, junto
 Using the statement for complicated conditional tests Uso de la sentencia switch para
complicadas pruebas condicionales
 Creating complicated tests with the ternary operator Creación de pruebas complicadas
con el operador ternario

if Statements si las declaraciones


If you want to test a condition in a Java program, the most basic way is with an statement.
Si quieres probar una condición en un programa de Java, la forma más básica es con una
sentencia if. As you learned previously, the variable type is used to store only two possible
values: or . Como ha aprendido anteriormente, el tipo de variable booleana se utiliza para
almacenar sólo dos valores posibles: verdadero o falso. The statement works along the
same lines, testing to see whether a condition is true or false and taking action only if the
condition is true. La declaración de si trabaja en el mismo sentido, las pruebas para ver si
una condición es verdadera o falsa y la adopción de medidas sólo si la condición es
verdadera.

You use along with a condition to test, as in the following statement: Se utiliza en caso
junto con una condición de prueba, como en la siguiente declaración:
if (account < 0.01) if (cuenta <0,01)
System.out.println("Hear that bouncing noise? It's
your checks"); System.out.println ("Escucha el ruido que
rebotar los cheques? Es tu");

Although this code is listed on two lines, it's one statement. Aunque el código está en la
lista en dos líneas, es una declaración. The first part uses to determine whether the
variable is less than 0.01 by using the operator. La primera parte si utiliza para determinar
si la variable de la cuenta es inferior a 0,01 mediante el operador <. The second part
displays the text La segunda parte muestra el texto Escucha el ruido que despide? .
Es sus cheques. The second part of the statement will be run only if the first part is true.
La segunda parte de la declaración si se llevará a cabo sólo si la primera parte es verdad. If
the variable has a value of 0.01 (1 cent) or higher, the statement will be ignored. Si la
variable de la cuenta tiene un valor de 0,01 (1 centavo) o más, la declaración println
será ignorado. Note that the condition that you test with an statement must be surrounded
by parentheses, as in . Tenga en cuenta que la condición de que se prueba con una
sentencia if debe estar rodeado de paréntesis, como en (cuenta <0,01).

If you're not sure why is not a statement on its own, note that there is no semicolon at the
end of the line. Si no está seguro de por qué si (cuenta <0,01) no es una declaración por
sí sola, tenga en cuenta que no hay punto y coma al final de la línea. In Java programs,
semicolons are used to show where one statement ends and the next one begins. En los
programas de Java, puntos y comas se utilizan para mostrar dónde termina una y comienza
la declaración siguiente. In the preceding example, the semicolon does not appear until
after the portion of the statement. En el ejemplo anterior, el punto y coma no aparece hasta
después de la parte println de la declaración. If you put a semicolon after the portion, as
in , you'll cause an error in your program that can be hard to spot. Si usted pone un punto y
coma después de la parte si, como en if (cuenta <0,01);, se le causa un error en su
programa que puede ser difícil de detectar. Take care regarding semicolons when you start
using the statement. Tenga cuidado con respecto a un punto y coma al empezar a utilizar la
sentencia if.

The less than operator, , is one of several different operators that you can use with
conditional statements. El operador menor que, <, es uno de los diferentes operadores que
se pueden utilizar con sentencias condicionales. You'll become more familiar with the
statement as you use it with some of the other operators. Usted se familiarice con la
declaración como si se utiliza con algunos de los otros operadores.

Less Than and Greater Than Comparisons A menos que y mayor que las
comparaciones
In the preceding section, the operator is used the same way it was used in math class, as a
less-than sign. En la sección anterior, el operador <se utiliza de la misma manera que se
utilizó en la clase de matemáticas, como un signo menor que. There also is a greater-than
conditional operator, . También es un creador de lo condicional mayor,>. This operator is
used in the following statements: Este operador se utiliza en las siguientes declaraciones:

if (elephantWeight > 780) if (elephantWeight> 780)


System.out.println("This elephant is too fat for your
tightrope act."); System.out.println ("Este elefante es
demasiado gordo para su acto de cuerda floja.");
if (elephantTotal > 12) if (elephantTotal> 12)
cleaningExpense = cleaningExpense + 150;
cleaningExpense cleaningExpense + = 150;

The first statement tests whether the value of the variable is greater than 780. El primero
si las pruebas indicación de si el valor de la variable elephantWeight es mayor que 780.
The second statement tests whether the variable is greater than 12. El segundo, si las
pruebas de declaración de si la variable elephantTotal es mayor de 12 años.

One thing to learn about statements is that they often cause nothing to happen in your
programs. Una cosa es conocer si las declaraciones es que a menudo causa nada que
suceda en sus programas. If the preceding two statements are used in a program where is
equal to 600 and is equal to 10, the rest of the statements will be ignored. Si los últimos
dos declaraciones se utilizan en un programa donde elephantWeight es igual a 600 y
elephantTotal es igual a 10, el resto de los estados serán ignorados. It's as though you are
giving an order to a younger sibling who is subject to your whims: "Jerry, go to the store. If
they have Everlasting Gobstopper candy, buy some for me. If not, do nothing and await
further orders." Es como si le está dando una orden a un hermano menor que está sujeta a
sus caprichos: "Jerry, vaya a la tienda Si tienen Eterno caramelos chicle, comprar para mí
Si no, no hacer nada y esperar nuevas órdenes..."

There will be times when you will want to determine whether something is less than or
equal to something else. Habrá momentos en los que se desea determinar si algo es menor o
igual a otra cosa. You can do this with the operator, as you might expect; use the operator
for greater-than-or-equal-to tests. Usted puede hacer esto con el operador <=, como era de
esperar, el uso del operador> = mayor que o-igual-a las pruebas. Here's an example: He
aquí un ejemplo:

if (account <= 0) if (cuenta <= 0)


System.out.println("Hear that bouncing noise? It's
your checks"); System.out.println ("Escucha el ruido que
rebotar los cheques? Es tu");

This revision of the checkbook example mentioned previously should be a bit easier to
understand. Esta revisión de la chequera el ejemplo mencionado anteriormente debe ser un
poco más fácil de entender. It tests whether is less than or equal to the value and taunts the
user if it is. Se comprueba si la cuenta es inferior o igual al valor 0 y se burla de el
usuario si lo es.

Equal and Not Equal Comparisons Las comparaciones de igualdad y no igualdad

Another condition to check on in a program is equality. Otra condición para comprobar en


un programa es la igualdad. Is a variable equal to a specific value? Es una variable igual a
un valor específico? Is one variable equal to the value of another? Es una variable igual al
valor de otro? These questions can be answered with the value, as in the following
statements: Estas preguntas pueden ser contestadas con el valor ==, como en las siguientes
declaraciones:

if (answer == rightAnswer) if (respuesta == Respuesta


correcta)
studentGrade = studentGrade + 10; studentGrade
studentGrade + = 10;
if (studentGrade == 100) if (studentGrade == 100)
System.out.println("Congratulations -- a perfect
score!"); System.out.println ("Felicidades - un puntaje
perfecto!");

Caution: The operator used to conduct equality tests has two equal signs: . Atención: El operador
que se utiliza para llevar a cabo pruebas de la igualdad tiene dos signos igual: ==. It's very easy to
confuse this operator with the operator, which is used to give a value to a variable. Es muy fácil
confundir este operador con el operador =, que se utiliza para dar un valor a una variable. Always
use two equal signs in a conditional statement. Siempre utilice dos signos de igual en una
sentencia condicional.

You also can test inequality--whether something is not equal to something else. También
puede probar la desigualdad - si algo no es igual a otra cosa. You do this with the operator,
as shown in the following example: Esto se hace con el ejemplo =! Operador, como se
muestra en las siguientes:
if (team != "New York Jets") if (equipo! = "Jets de Nueva
York")
chanceToWin = 50; chanceToWin = 50;
if (answer != rightAnswer) if (respuesta! = Respuesta
correcta)
score = score - 5; La puntuación = puntuación - 5;

You can use the and operators with every type of variable except for one, strings. Puede
utilizar los operadores == y! = Operadores con cada tipo de variable a excepción de una,
las cadenas. To see whether one string has the value of another, use the method described
during Hour 6, "Using Strings to Communicate." Para ver si una cadena tiene el valor de
otro, utilice el método equals () descrito en seis horas, "Uso de cadenas para la
comunicación."

Organizing a Program with Block Statements La organización de un programa con el


Bloque declaraciones

Up to this point, all of the statements have been followed with a single instruction, such as
the method. Hasta este punto, todos los estados si se han seguido con una sola instrucción,
como el método println (). In many cases, you will want to do more than one action in
response to an statement. En muchos casos, usted tendrá que hacer más de una acción en
respuesta a una sentencia if. To do this, you'll use the squiggly bracket marks { and } to
create a block statement. Para ello, utilizará el soporte de las marcas onduladas {y} para
crear un bloque de sentencias.

Block statements are statements that are organized as a group. estados del bloque son
declaraciones que están organizados como un grupo. Previously, you have seen how block
statements are used to mark the beginning and end of the block of a Java program.
Anteriormente, hemos visto cómo los estados del bloque se utilizan para marcar el
comienzo y el final del main () de bloque de un programa Java. Each statement within the
block is handled when the program is run. Cada declaración dentro de la main () del
bloque se maneja cuando se ejecuta el programa. Listing 7.1 is an example of a Java
program with a block statement used to denote the block. Listado de 7.1 es un ejemplo de
un programa Java con una declaración de bloque utilizado para denotar el main () del
bloque. The block statement begins with the opening bracket on Line 2 and ends with the
closing bracket on Line 11. La declaración del bloque comienza con un paréntesis abierto
{en la Línea 2 y termina con el corchete de cierre} en la línea 11. Load your word
processor and enter the text of Listing 7.1 as a new file. Cargue su procesador de texto y
escriba el texto del listado 7.1 como un nuevo archivo.
Listing 7.1. Listado 7.1. A Java program using a main() block statement. Un programa
Java con un main () sentencia de bloque.

1: class Game { 1: Juego de clase {


2: public static void main(String[] arguments) { 2:
public static void main (String [argumentos]) {
3: int total = 0; ; 0: 3 int total =
4: int score = 7; , 7: 4 int puntuación =
5: if (score == 7) 5: si (== puntuación de 7)
6: System.out.println("You score a touchdown!"); 6:
System.out.println ("Usted anotar un touchdown!");
7: if (score == 3) 7: si (== puntuación de 3)
8: System.out.println("You kick a field goal!"); 8:
System.out.println ("Es un gol de campo!");
9: total = total + score; 9: total = total + puntaje;
10: System.out.println("Total score: " + total); 10:
System.out.println ("Total puntaje:" + total);
11: } 11:}
12:}

Save this file as and compile it with the compiler tool. Guardar este archivo como
Game.java y compilarlo con la herramienta del compilador javac. The output should
resemble Listing 7.2. La salida debe ser similar listado 7.2.

Listing 7.2. Listado 7.2. The output of the Game program. La salida del programa de
juego.
You score a touchdown! Usted anotar un touchdown!

You can also use block statements in conjunction with statements to make the computer
do more than one thing if a conditional statement is true. Puntuación total: 7 También
puede utilizar las declaraciones en relación con el bloque de sentencias if para hacer que
el equipo hacer algo más que una cosa es una sentencia condicional es verdadero. The
following is an example of an statement that includes a block statement: El siguiente es un
ejemplo de una sentencia if que incluye un bloque de sentencias:

if (playerScore > 9999) { if (playerScore> 9999) {


playerLives++; playerLives + +;
System.out.println("Extra life!"); System.out.println
("vida extra");
difficultyLevel = difficultyLevel + 5; difficultyLevel
= difficultyLevel + 5;
} }

The brackets are used to group all statements that are part of the statement. Los soportes se
utilizan para agrupar todas las declaraciones que forman parte de la sentencia if. If the
variable is greater than 9,999, three things will happen: Si el playerScore variable es
mayor que 9999, tres cosas:

 The value of the variable increases by one (because the increment operator is used). El
valor de la variable aumenta playerLives por uno (ya que el operador de incremento +
+ se utiliza).
 The text is displayed. La vida extra texto aparece en pantalla.
 The value of the variable is increased by 5. El valor de la variable difficultyLevel se
incrementa en 5.

If the variable is not greater than 9,999, nothing will happen. Si el playerScore variable
no es mayor que 9999, no pasará nada. All three statements inside the statement block will
be ignored. Los tres estados en el interior del bloque de instrucciones si se ignoran.

if-else Statements if-else declaraciones


There are times when you want to do something if a condition is true and do something else
if the condition is false. Hay ocasiones en las que quiere hacer algo si una condición es
verdadera y otra cosa si la condición es falsa. You can do this by using the statement in
addition to the statement, as in the following example: Usted puede hacer esto usando la
sentencia else, además de la instrucción if, como en el ejemplo siguiente:

if (answer == correctAnswer) { if (respuesta ==


correctAnswer) {
score += 10; La puntuación de + = 10;
System.out.println("That's right. You get 10
points."); System.out.println ("Eso es correcto puntos.
Obtienes 10.");
} }
else { else {
score -= 5; La puntuación de -= 5;
System.out.println("Sorry, that's wrong. You lose 5
points."); System.out.println ("Lo siento, eso está mal
puntos. Pierde 5.");
} }
The statement does not have a condition listed alongside it, unlike the statement. La
declaración de persona no tiene una condición que figuran junto a él, a diferencia de la
sentencia if. Generally, the statement is matched with the statement that immediately
comes before it in a Java program. En general, la sentencia else se empareja con la
declaración de que si viene inmediatamente antes de que en un programa Java. You also
can use to chain several statements together, as in the following example: También puede
utilizar más a la cadena de varias sentencias if juntos, como en el ejemplo siguiente:

if (grade == "A") si (== del grado "A")


System.out.println("You got an A. Great job!");
System.out.println ("Tienes un gran trabajo A.!");
else if (grade == "B") else if (grado == "B")
System.out.println("You got a B. Good work!");
System.out.println ("¿Tienes un buen trabajo B.!");
else if (grade == "C") else if (grado == "C")
System.out.println("You got a C. You'll never get into
a good college!"); System.out.println ("¿Tienes una C. 'll
nunca entrar en una buena universidad!");
else más
System.out.println("You got an F. You'll do well in
Congress!"); System.out.println ("¿Tienes una F. Vas a
hacer bien en el Congreso!");

By putting together several different and statements in this way, you can handle a variety
of conditions. Al poner juntos varios if y else diferentes de esta manera, usted puede
manejar una variedad de condiciones. In the preceding example, a specific message is sent
to A students, B students, C students, and future legislators. En el ejemplo anterior, un
mensaje específico se envía a A estudiantes, B, C, los estudiantes y futuros legisladores.

switch Statements interruptor de declaraciones


The and statements are good for situations with only two possible conditions, but there are
times when you have more than two options that need to be considered. El if y else son
buenos para situaciones con sólo dos condiciones posibles, pero hay momentos en los que
tienen más de dos opciones que deben tenerse en cuenta. With the preceding grade
example, you saw that and statements can be chained to handle several different
conditions. Con el ejemplo del grado anterior, se dio cuenta de que si las declaraciones y
demás se pueden encadenar para tratar varias condiciones diferentes.

Another way to do this is to use the statement. Otra forma de hacer esto es utilizar la
sentencia switch. You can use it in a Java program to test for a variety of different
conditions and respond accordingly. Se puede utilizar en un programa Java para probar una
variedad de condiciones diferentes y responder en consecuencia. In the following example,
the grade example has been rewritten with the statement to handle a complicated range of
choices: En el siguiente ejemplo, el ejemplo de grado ha sido reescrito con la sentencia
switch para manejar una gama compleja de opciones:

switch (grade) { switch (grado) {


case `A': caso de 'A':
System.out.println("You got an A. Great job!");
System.out.println ("Tienes un gran trabajo A.!");
break; break;
case `B': caso `B ':
System.out.println("You got a B. Good work!");
System.out.println ("¿Tienes un buen trabajo B.!");
break; break;
case `C': caso "C":
System.out.println("You got a C. You'll never get
into a good college!"); System.out.println ("¿Tienes una C.
'll nunca entrar en una buena universidad!");
break; break;
default: por defecto:
System.out.println("You got an F. You'll do well
in Congress!"); System.out.println ("¿Tienes una F. Vas a
hacer bien en el Congreso!");
} }

The first line of the statement specifies the variable that will be tested--in this example, .
La primera línea de la sentencia switch especifica la variable que se pondrá a prueba - en
este ejemplo, el grado. Then the statement uses the and brackets to form a block
statement. A continuación, la sentencia switch utiliza el {y} paréntesis para formar un
bloque de sentencias.

Each of the statements checks the test variable from against a specific value. Cada uno de
los estados caso comprueba la variable de prueba del interruptor con un valor
específico. In this example, there are statements for values of , , and . En este ejemplo,
hay declaraciones de caso para los valores de A, B y C. Each of these has one or two
statements that follow it. Cada uno de estos tiene una o dos estados que le siguen. When
one of these statements matches the variable listed with , the computer handles the
statements after the statement until it encounters a statement. Cuando uno de estos estados
caso coincide con la variable de la lista con el interruptor, el equipo maneja las
declaraciones después de la declaración del caso hasta que encuentra una instrucción
break. For example, if the variable has the value of , the text will be displayed. Por
ejemplo, si la variable de grado tiene el valor de B, el texto que tiene un buen
trabajo B.! Se mostrará. The next statement is , so no other part of the statement will be
considered. La declaración del día, se rompen, por lo que ninguna otra parte de la sentencia
switch serán consideradas. The statement tells the computer to break out of the statement.
La sentencia break indica al equipo para salir de la instrucción switch.

The statement is used as a catch-all if none of the preceding statements is true. La


declaración por defecto se utiliza como un cajón de sastre si ninguno de los estados caso
anterior es cierto. In this example, it will occur if the variable does not equal , , or . En
este ejemplo, se producirá si la variable de grado no es igual a A, B o C. You do not have
to use a statement with every block statement that you use in your programs. Usted no
tiene que utilizar una declaración por defecto con cada declaración panel de control que
utiliza en sus programas. If it is omitted, nothing will happen if none of the statements has
the correct value. Si se omite, no pasará nada si ninguna de las declaraciones de caso tiene
el valor correcto.

The Conditional Operator El operador condicional


The most complicated conditional statement is one that you might not find reasons to use in
your programs, the ternary operator. La sentencia condicional más complicado es el que es
posible que no encuentran razones para el uso en sus programas, el operador ternario. If
you find it too confusing to implement in your own programs, take heart: You can use other
conditionals to accomplish the same thing. Si le resulta demasiado confuso para aplicar en
sus propios programas, tomar el corazón: Es posible utilizar otros condicionantes para
llevar a cabo la misma cosa.

You can use the ternary operator when you want to assign a value or display a value based
on a conditional test. Usted puede utilizar el operador ternario cuando se desea asignar un
valor o mostrar un valor basado en una prueba condicional. For example, in a video game,
you might need to set the variable based on whether the variable is greater than 5. Por
ejemplo, en un juego de vídeo, puede que tenga que establecer la variable de
numberOfEnemies en función de si la variable skillLevel es mayor que 5. One way to do
this is with an - statement: Una forma de hacerlo es con un if - else:

if (skillLevel > 5) if (skillLevel> 5)


numberOfEnemies = 10; numberOfEnemies = 10;
else más
numberOfEnemies = 5; numberOfEnemies = 5;
A shorter way to do this is to use the ternary operator, which is . Un camino más corto para
hacer esto es utilizar el operador ternario, lo que es?. A ternary operator has the following
parts: Un operador ternario tiene las siguientes partes:

 The condition to test, surrounded by parentheses, as in La condición para poner a prueba,


entre paréntesis, como en (skillLevel> 5)
 A question mark (?) Un signo de interrogación (?)
 The value to use if the condition is true El valor de uso, si la condición es verdadera
 A colon (:) Los dos puntos (:)
 The value to use if the condition is false El valor de uso, si la condición es falsa

To use the ternary operator to set the value of based on , you could use the following
statement: Para utilizar el operador ternario para establecer el valor de numberOfEnemies
basado en skillLevel, podría utilizar la siguiente declaración:

numberOfEnemies = ( skillLevel > 5) ? numberOfEnemies =


(skillLevel> 5)? 10 : 5; 10: 5;

You can also use the ternary operator to determine what information to display. También
puede utilizar el operador ternario para determinar qué tipo de información para mostrar.
Consider the example of a program that displays the text or depending on the value of the
variable. Consideremos el ejemplo de un programa que muestra el texto del Sr. o la Sra.
dependiendo del valor de la variable de género. You could do this action with another -
statement: Usted puede hacer esta acción con otro si - else:

if (gender == "male") si (sexo == "macho")


System.out.print("Mr."); System.out.print ("señor");
else más
System.out.print("Ms."); System.out.print ("La
señora");

A shorter method is to use the ternary operator to accomplish the same thing, as in the
following: Un método más corto es utilizar el operador ternario para llevar a cabo la misma
cosa, como en lo siguiente:

System.out.print( (gender == "male") ? "Mr." : "Ms." );


System.out.print ((sexo == "macho"): "Sr." "Sra.");

The ternary operator can be useful, but it's also the hardest element of conditional tests in
Java to understand. El operador ternario puede ser útil, pero es también el más difícil
elemento de pruebas condicionales en Java de entender. Feel free to use the longer and
statements if you want. Siéntase libre de utilizar el if y else más si quieres.
Workshop: Watching the Clock Taller: Mirando el reloj
This hour's workshop gives you another look at each of the conditional tests you can use in
your programs. Este taller de hora le da otro vistazo a cada una de las pruebas
condicionales se pueden utilizar en sus programas. For this project, you will use Java's
built-in timekeeping feature, which keeps track of the current date and time, and will
present this information in sentence form. Para este proyecto, que va a utilizar Java
incorporado en función de la hora normal, que realiza un seguimiento de la fecha y hora
actuales, y presentará esta información en forma de frase.

Run the word processor that you're using to create Java programs and give a new document
the name . Ejecutar el procesador de textos que está utilizando para crear programas en
Java y dar un nuevo documento con el nombre ClockTalk.java. This program is long, but
most of it consists of long conditional statements. Este programa es largo, pero la mayor
parte se compone de largas sentencias condicionales. Type the full text of Listing 7.3 into
the word processor and save the file when you're done. Escriba el texto completo del listado
7.3 en el procesador de texto y guarde el archivo cuando haya terminado.

Listing 7.3. Listado 7.3. The full text of ClockTalk.java. El texto completo de
ClockTalk.java.
1: import java.util.*; 2: 3: class ClockTalk { 4: public
static void main(String[] arguments) { 5: // get current
time and date 6: GregorianCalendar now = new
GregorianCalendar(); 7: int hour =
now.get(Calendar.HOUROFDAY); 8: int minute =
now.get(Calendar.MINUTE); 9: int month =
now.get(Calendar.MONTH) + 1; 10: int day =
now.get(Calendar.DAYOFMONTH); 11: int year =
now.get(Calendar.YEAR); 12: 13: // display greeting 14: if
(hour < 12) 15: System.out.println("Good morning.\n"); 16:
else if (hour < 17) 17: System.out.println("Good
afternoon.\n"); 18: else 19: System.out.println("Good
evening.\n"); 20: 21: // begin time message by showing the
minutes 22: System.out.print("It's"); 23: if (minute != 0)
{ 24: System.out.print(" " + minute + " "); 25:
System.out.print( (minute != 1) ? "minutes" : 26:
"minute"); 27: System.out.print(" past"); 28: } 29: 30: //
display the hour 31: System.out.print(" "); 32:
System.out.print( (hour > 12) ? (hour - 12) : hour ); 33:
System.out.print(" o'clock on "); 34: 35: // display the
name of the month 36: switch (month) { 37: case (1): 38:
System.out.print("January"); 39: break; 40: case (2): 41:
System.out.print("February"); 42: break; 43: case (3): 44:
System.out.print("March"); 45: break; 46: case (4): 47:
System.out.print("April"); 48: break; 49: case (5): 50:
System.out.print("May"); 51: break; 52: case (6): 53:
System.out.print("June"); 54: break; 55: case (7): 56:
System.out.print("July"); 57: break; 58: case (8): 59:
System.out.print("August"); 60: break; 61: case (9): 62:
System.out.print("September"); 63: break; 64: case (10):
65: System.out.print("October"); 66: break; 67: case (11):
68: System.out.print("November"); 69: break; 70: case (12):
71: System.out.print("December"); 72: } 73: 74: // display
the date and year 75: System.out.println(" " + day + ", " +
year + "."); 76: } 1: import java.util .*; 2:: 4: 3 clases
ClockTalk {public static void Main (string [argumentos])
{5: / / obtener la hora actual y la fecha 6:
GregorianCalendar ahora = GregorianCalendar () nuevo; 7:
int hora = now.get (Calendar.HOUROFDAY), 8: minuto int =
now.get (Calendar.MINUTE); 9: int mes = now.get
(Calendar.MONTH) + 1, 10: Día int = now.get
(Calendar.DAYOFMONTH); 11: int año = now.get
(Calendar.YEAR); 12: 13: / / pantalla de felicitación 14:
if (horas <12) 15: System.out.println ("Buenos días n. \
"); 16: else if (horas <17) 17: System.out.println (".
Buenas tardes \ n "); 18: otro 19: System.out.println (".
Buenas noches \ n "); 20 : 21: / / iniciar mensaje de
tiempo mostrando los 22 minutos: System.out.print ("es");
23:) si minuto (! = 0 {24: System.out.print ("" + minutos +
"" ); 25: System.out.print ((1 minuto! =): "minutos": 26
"minutos"); 27: System.out.print ("pasado"); 28:} 29: 30: /
/ mostrar la hora 31: System.out.print (""); 32:
System.out.print ((hora> 12): (hora - 12) horas); 33:
System.out.print ("punto de "); 34: 35: / / mostrar el
nombre del mes 36: switch (mes) {37: caso (1): 38:
System.out.print (" Enero "); 39: descanso; 40: caso (2):
41: System.out.print ("febrero"); 42: descanso; 43: caso
(3): 44: System.out.print ("Marcha"); 45: descanso; 46:
asunto (4 ): 47: System.out.print ("Abril"); 48: descanso;
49 casos (5): 50: System.out.print ("May"); 51: descanso;
52 casos (6): 53: System.out.print ("Junio"); 54: descanso;
55: caso (7): 56: System.out.print ("Julio"); 57: descanso;
58: caso (8): 59: System.out.print ("Agosto"); 60:
descanso; 61 casos (9): 62: System.out.print
("Septiembre"); 63: descanso; 64: caso (10): 65: Sistema.
out.print ("Octubre"); 66: descanso; 67 casos (11): 68:
System.out.print ("Noviembre"); 69: descanso; 70: caso
(12): 71: System.out. print ("Diciembre"); 72:} 73: 74: / /
mostrar la fecha y el año 75: System.out.println ("" + dia
+ "" + año + "."); 76:} 77: }

Once you have saved the file, try to compile it by entering at the command line. Una vez
que haya guardado el archivo, trate de compilar javac ClockTalk.java entrando en la
línea de comandos. Correct any typos that cause error messages to occur during the
attempted compilation. Corrija los errores ortográficos que provocan mensajes de error que
se produzca durante el intento de compilación. After the program compiles correctly, look
over Lines 14-75 before going over the description of the program. Después de que el
programa se compila correctamente, mirar por encima de las líneas 14 a 75 antes de ir a la
descripción del programa. See whether you can get a good idea about what is taking place
in each of these sections and how the conditional tests are being used. Vea si usted puede
conseguir una buena idea sobre lo que está ocurriendo en cada una de estas secciones y
cómo las pruebas condicionales se están utilizando.

The program is made up of the following sections: El programa ClockTalk se compone de


las siguientes secciones:

 Line 1 enables your program to use two classes that are needed to track the current date
and time: and . La línea 1 le permite a su programa para utilizar dos clases que se
necesitan para realizar un seguimiento de la fecha y hora actuales:
java.util.Calendar y java.util.GregorianCalendar.
 Lines 3-4 begin the program and its statement block. Líneas 3-4 comenzar el programa
ClockTalk y su main () bloque de instrucciones.
 Line 6 creates a variable called with a special type of variable called a . La línea 6 crea una
variable llamada ahora con un tipo especial de variable llamada un
GregorianCalendar. The variable stores the current date and current time and will
change each time you run this program (unless, of course, the physical laws of the
universe are altered and time stands still). La variable de las tiendas ya la fecha y la hora
actual y cambiará cada vez que se ejecuta este programa (a menos que, por supuesto, las
leyes físicas del universo están alterados y el tiempo se detiene).
 Lines 7-11 create variables to hold the , , , , and . Líneas 7-11 crear variables para
almacenar la hora, minuto, mes, día y año. These variables are used in the
subsequent sections as the program displays information. Estas variables se utilizan en las
siguientes secciones como la información sobre el programa muestra.
 Lines 14-19 display one of three possible greetings: , , or The greeting to display is
selected based on the value of the variable. Líneas 14-19 pantalla uno de los tres saludos
posible: Bueno, buenas tardes,. Por la mañana o buenas. Por la noche. El
saludo a la pantalla se selecciona en función del valor de la variable horas.
 Lines 22-28 display the current minute along with some accompanying text. Líneas 22-28
mostrar el minuto actual, junto con un texto de acompañamiento. First, the text is
displayed in Line 22. En primer lugar, el texto que se visualiza en la línea 22. If the value
of is equal to 0, Lines 24-27 are ignored because of the statement in Line 23. Si el valor
del minuto es igual a 0, líneas 24 a 27 se pasan por alto debido a la declaración si en la
línea 23. This statement is necessary because it would not make sense for the program to
tell someone that it's 0 minutes past an hour. Esta declaración es necesaria porque no
tendría sentido que el programa para decirle a alguien que es 0 minutos después de una
hora. Line 24 displays the current value of the variable. La línea 24 muestra el valor actual
de la variable minuto. A ternary operator is used in Line 25 to display either the text or ,
depending on whether is equal to 1. Un operador ternario se utiliza en la línea 25 a la
pantalla o el acta de texto o minutos, dependiendo de si minuto es igual a 1. Finally, in
Line 27 the text is displayed. Por último, en la Línea 27 del pasado se muestra el texto.
 Lines 30-33 display the current hour by using another ternary operator. Las líneas 30-33
muestran la hora actual con cualquier otro operador ternario. This ternary conditional
statement in Line 32 causes the hour to be displayed differently if it is larger than 12,
which prevents the computer from stating things like 15 o'clock. Esta declaración ternario
condicional en la línea 32 hace que la hora que se muestran de manera diferente si es
mayor de 12, lo que impide que el equipo de declarar cosas como las 15 horas.
 Lines 36-72, almost half of the program, are a long statement that displays a different
name of the month based on the integer value stored in the variable. Líneas 36 a 72, casi
la mitad del programa, son una sentencia switch de largo que muestra un nombre
diferente del mes, basadas en el valor entero almacenado en la variable mes.
 Lines 74-75 finish off the display by showing the current date and the year. Líneas 74-75
acabar con la pantalla, mostrando la fecha actual y el año.
 Lines 76-77 close out the statement block and then the entire program. Líneas 76 a 77
cerca de la) sentencia block (principal y luego el programa ClockTalk entero.

When you run this program, the output should resemble the following code, with changes
based on the current date and time. Cuando se ejecuta este programa, la salida debe ser
similar al código siguiente, con cambios basados en la fecha y hora actuales. For example,
if today's date is 4-13-1997 and the time is 8:30 am, your program would display the
following text: Por ejemplo, si hoy es 13/04/1997 y el tiempo es 8:30 am, el programa
mostrará el texto siguiente:

Good morning. Buenos días.


It's 30 minutes past 8 o'clock on April 13, 1997. Es de 30
minutos después de ocho el 13 de abril de 1997.

Run the program several times to see how it keeps up with the clock. Ejecute el programa
varias veces para ver cómo se mantiene con el reloj.

The program uses the Gregorian calendar system that has been used throughout the
Western world for many years to determine the date and time. El programa ClockTalk
utiliza el sistema de calendario Gregoriano que se ha utilizado en todo el mundo occidental
durante muchos años para determinar la fecha y hora. It was introduced in 1582 when Pope
Gregory XIII moved the Julian calendar system forward 10 days--turning Oct. 5, 1582, into
Oct. 15, 1582. Fue introducido en 1582 cuando el Papa Gregorio XIII se trasladó el sistema
calendario juliano adelante 10 días - girando 05 de octubre 1582, en 15 de octubre 1582.
This was needed because the calendar was moving out of alignment with the seasons due to
discrepancies in the Julian system. Esto era necesario porque el calendario se movía fuera
de la alineación con las estaciones debido a las discrepancias en el sistema de Julian.
Changes introduced with version 1.1 of the Java language make it possible to create other
calendar systems for use with Java programs. Los cambios introducidos con la versión 1.1
del lenguaje Java hace posible la creación de otros sistemas de calendario para el uso con
los programas de Java. Check Gamelan at or other Java programming resources for these
calendar systems as they become available. Compruebe Gamelan en
http://www.gamelan.com u otros recursos de programación Java para estos sistemas de
calendario a medida que estén disponibles.
Summary Resumen
Now that you can use conditional statements, the overall intelligence of your Java programs
has improved greatly. Ahora que puede utilizar instrucciones condicionales, la inteligencia
general de los programas Java ha mejorado mucho. Your programs can now evaluate
information and use it to react differently in different situations, even if information
changes as the program is running. Sus programas pueden ahora evaluar la información y
utilizarla para reaccionar de manera diferente en diferentes situaciones, incluso si cambia la
información de que el programa se está ejecutando. They can decide between two or more
alternatives based on specific conditions. Se puede decidir entre dos o más alternativas
basadas en condiciones específicas.

Using the statement and other conditionals in programming also promotes a type of logical
thinking that can reap benefits in other aspects of your life. Uso de la sentencia if y los
condicionales en la programación de otros también promueve un tipo de pensamiento
lógico que puede obtener beneficios en otros aspectos de su vida. ("If she's attractive, I'll
take her to an expensive restaurant, else we're using my two-for-one Taco Barn burrito
coupon.") Programming a computer forces you to break down a task into a logical set of
steps to undertake and decisions that must be made, and it provides interesting insight. ("Si
ella es atractiva, me la llevo a un restaurante caro, de lo que estamos usando mis dos por
uno Taco cupón burrito Granero.") Programación de un ordenador te obliga a descomponer
una tarea en una serie lógica de pasos para llevar a cabo y las decisiones que se deben
hacer, y proporciona una visión interesante.

One thing that conditional statements do not offer insight about is the thinking of the
lyricist who penned "Just Dropped In (To See What Condition My Condition Was In)".
Una cosa que las sentencias condicionales no ofrecen una visión sobre el pensamiento del
compositor que escribió "Mas Bajas En (Para ver que Mi Condena A)". There may be no
rational explanation for lyrics such as, "I tred on a cloud, I fell eight miles high. Told my
mind I'm gonna sky. I just dropped in to see what condition my condition was in." Puede
haber una explicación racional para letras de canciones como, "Tred que en una nube, me
cayó ocho kilómetros de altura. Le dije a mi mente que voy a cielo. Acabo de caer en ver lo
que la condición de mi condición era in-

Q&A Q & A
Q The if statement seems like the one that's most useful. Q La sentencia if parece que el
que es más útil. Is it possible to use only if statements in programs and never use the
others? ¿Es posible utilizar sólo si los estados en los programas y nunca uso los otros?

A It's possible to do without or , and many programmers never use the ternary operator .
R Es posible hacer sin más o switch, y muchos programadores nunca utilizar el operador
ternario?. However, and often are beneficial to use in your programs because they
make them easier to understand. Sin embargo, otra cosa y cambiar a menudo son
beneficiosas para el uso en sus programas, ya que sean más fáciles de entender. A set of
statements chained together can become unwieldy. Una serie de sentencias if
encadenados juntos pueden llegar a ser difícil de manejar.

Q An if statement is described as a single statement or as a conditional statement


followed by another statement to handle if the condition is true. Q Una sentencia if es
descrito como una sola instrucción o como una sentencia condicional seguido de otro
comunicado de manejar si la condición es verdadera. Which is it? ¿Qué es?

A The point that might be confusing is that statements and other conditionals are used in
conjunction with other statements. Un punto de la que podría ser confuso es que si las
declaraciones y los condicionales se usan otros, en relación con otras declaraciones. The
statement makes a decision, and the other statements do work based on the decision that
is made. La declaración, si toma una decisión, y las declaraciones de otros no
funcionan sobre la base de la decisión que se hace. The statement combines a conditional
statement with one or more other types of Java statements, such as statements that use
the method or create a variable. La declaración, si se combina una sentencia
condicional con uno o más tipos de declaraciones de Java, como las declaraciones que
utilizan el método println () o crear una variable.

Q During this hour, opening and closing brackets { and } are not used with an if
statement if it is used in conjunction with only one statement. Q Durante esta hora, la
apertura y cierre de corchetes {y} no se utilizan con una sentencia if si se utiliza en
conjunción con una sola declaración. Is this mandatory? ¿Es esto obligatorio?

A No. R No. Brackets can be used as part of any statement to surround the part of the
program that's dependent on the conditional test. Los soportes pueden ser utilizados
como parte de una sentencia if para rodear la parte del programa que depende de la
prueba condicional. Using brackets is a good practice to get into because it prevents a
common error that might take place when you revise the program. Uso de paréntesis es
una buena práctica para entrar en, ya que evita que un error común que podría tener
lugar cuando se revise el programa. If you add a second statement after an conditional
and don't add brackets, unexpected errors will occur when the program is run. Si se agrega
una segunda declaración después de un si condicional y no añadir entre paréntesis, los
errores inesperados se producen cuando se ejecuta el programa.

Q Will the Java compiler javac catch the error when an = operator is used with a
conditional instead of an ==? Q ¿El compilador Java javac detectar el error cuando un
operador = se utiliza con un condicional en lugar de un ==?

A Often no, and it results in a real doozy of a logic error. A menudo que no, y el resultado
es un doozy real de un error lógico. These errors only show up when a program is being
run and can be discovered only through observation and testing. Estos errores sólo
aparecen cuando un programa se ejecuta y puede ser descubierto mediante la
observación y pruebas. Because the operator is used to assign a value to a variable, if you
use in a spot in a program where you mean to use ", you could wipe out the value of the
variable and replace it with . Debido a que el operador = se utiliza para asignar un valor a
una variable, si utiliza el nombre = "Fernando" en un lugar en un programa donde te
refieres a utilizar el nombre == "Fernando", que podría acabar con el valor de la
variable de nombre y reemplazarlo con Fernando. When the value stored in variables
changes unexpectedly, the result is subtle and unexpected errors that you must debug.
Cuando el valor almacenado en los cambios de las variables de forma inesperada, el
resultado es sutil y errores inesperados que se debe depurar.

Q Does break have to be used in each section of statements that follow a case? Q se
rompe hay que utilizar en cada sección de las declaraciones que siguen un caso?

A You don't have to use . A Usted no tiene que utilizar descanso. If you do not use it at
the end of a group of statements, all of the remaining statements inside the block
statement will be handled, regardless of the value they are being tested with. Si no lo
utiliza al final de un grupo de estados, todos los estados restantes dentro de la declaración
de campo de control serán tratados, sin importar el valor caso de que se están probando
con.

Q What's the difference between System.out.println() and System.out.print()? Q ¿Cuál


es la diferencia entre System.out.println () y System.out.println ()?

A The statement displays a line of text and ends the line with a newline character. Un
println El () comando muestra una línea de texto y termina la línea con un carácter de
nueva línea. The newline character has the same behavior as the carriage return key on a
manual typewriter. El carácter de nueva línea tiene el mismo comportamiento que la tecla
de retorno de carro en una máquina de escribir manual. It causes the next text to begin
displaying at the leftmost edge of the next line. Hace que el texto siguiente para comenzar
a mostrar en el borde izquierdo de la línea siguiente. The statement does not use a
newline character, making it possible to use several statements to display information on
the same line. La impresión () Declaración de no utilizar un carácter de nueva línea, lo
que hace posible el uso de imprimir varios () En los estados para mostrar la
información en la misma línea.

Quiz Quiz
The following questions will see what condition your knowledge of conditions is in. Las
siguientes preguntas verá lo que la condición de su conocimiento de las condiciones es pulg

Questions Preguntas

1. Conditional tests result in either a true or false value. 1. Resultado de las pruebas
condicionales, ya sea en una o falso verdadero valor. Which variable type does this remind
you of? ¿Qué variable de tipo no te recuerda?

(a) None. (A) Ninguna. They're unique. Son únicos.


(b) The variable type. (B) El tipo de variable a largo.
(c) The type. (C) El tipo booleano.
2. Which statement is used as a catch-all category in a block statement? 2. ¿Qué
enunciado se utiliza como un cajón de sastre categoría en un comunicado el panel de
control?

(a) (A) por defecto


(b) (B) de otra manera
(c) (C) onTheOtherHand

3. What's a conditional? 3. ¿Qué es un condicional?

(a) The thing that repairs messy split ends and tangles after you shampoo. (A) Lo que más
desordenado puntas reparaciones y enredos después de champú.
(b) Something in a program that tests whether a condition is true or false. (B) Algo en un
programa que comprueba si una condición es verdadera o falsa.
(c) The place where you confess your sins to a neighborhood religious figure. (C) El lugar
donde se confiesan sus pecados a una figura religiosa barrio.

Answers Respuestas

1. c. 1. C. The variable type can only equal or , making it similar to conditional tests. El
tipo variable booleana sólo puede ser igual a verdadero o falso, por lo que es similar
a las pruebas condicionales.

2. a. statements will be handled if none of the other statements matches the variable. 2.
A. declaraciones por defecto será manejado si ninguna de las declaraciones de otro
caso coincide con la variable de cambio.

3. b. 3. B. The other descriptions are conditioner and confessional. Las descripciones de


otros acondicionado y confesional.

Activities Actividades
To improve your conditioning in terms of Java conditionals, review the topics of this hour
with the following activities: Para mejorar su condicionamiento en términos de
condicionales de Java, revise los temas de esta hora con las siguientes actividades:

 Remove the statement from one of the lines in the program, and then compile it and see
what happens when you run it. Retire la sentencia break de una de las líneas en el
programa ClockTalk, y luego compilarlo y ver qué pasa cuando se ejecuta. Try it again
with a few more statements removed. Inténtalo de nuevo con un descanso de las
declaraciones poco más retirado.
 Create a short program that stores a value of your choosing from 1 to 100 in an integer
variable called . Crear un programa corto que almacena un valor de elegir de 1 a 100 en
una variable entera llamada grado. Use this variable with a conditional statement to
display a different message for all A, B, C, D, and F students. Esta variable se utiliza grado
con una sentencia condicional para mostrar un mensaje diferente para todos los A, C, D, B
y F estudiantes. Try it first with an statement, and then try it with a statement. Pruebe
primero con una sentencia if, y luego probar con una sentencia switch.
 8 horas
o Repetición de una acción con bucles
 para Loops
 mientras que los bucles
 do-while Bucles
 Salir de un bucle
 Nombrar a un bucle
 Taller: Enseñanza de la computadora una lección
 Listado 8.1. El código fuente completo de Repeat.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 8 8 horas

Repeating an Action with Loops Repetición de una


acción con bucles

One of the more annoying punishments for schoolchildren is to make them write something
over and over again on paper or, for a capital offense, on the chalkboard. Uno de los
castigos más molesto para los escolares es hacer que escribir algo una y otra vez en papel o,
por un delito capital, en la pizarra. In one of his frequent trips to the board, cartoon problem
child Bart Simpson had to write "I will not trade pants with others" dozens of times. En una
de sus frecuentes viajes a la junta, de dibujos animados Bart Simpson problema niño tenía
que escribir "No se negociarán los pantalones con otros" docenas de veces. This kind of
punishment might work on children, but it definitely would fail on a computer. Este tipo de
castigo podría funcionar en los niños, pero definitivamente no en un equipo. They can
repeat a task with ease. Se puede repetir una tarea con facilidad.

As you might expect, every one of Bart Simpson's chalkboard punishments has been
documented on the World Wide Web. Como es de esperar, cada uno de los castigos pizarra
de Bart Simpson se ha documentado en la World Wide Web. Visit the following address to
see the list: Visite la siguiente dirección para ver la lista:

http://www.ncf.carleton.ca/ ~ co378/HomePage.Chalk.html

Computer programs are ideally suited to do the same thing over and over again because of
loops. Los programas de ordenador son ideales para hacer la misma cosa una y otra vez
debido a los lazos. A loop is a statement or set of statements that will be repeated in a
program. Un bucle es una declaración o un conjunto de declaraciones que se repetirá en un
programa. Some loops are set to occur a fixed number of times. Algunos lazos se
producirán un número determinado de veces. Others can loop indefinitely. Otros pueden
bucle indefinidamente. In the Java programs that you write, you will find many
circumstances in which a loop is useful. En los programas de Java que usted escribe, usted
encontrará muchas circunstancias en las que un bucle es útil. You can use them to wait until
a specific thing has taken place, such as a user clicking on a button. Usted puede utilizar
para esperar a que una cosa específica ha tenido lugar, como un usuario hace clic en un
botón. You can also use them to cause the computer to wait and do nothing for a brief
period, such as in an animation program. También se pueden utilizar para hacer que el
equipo que esperar y no hacer nada durante un breve período, como en un programa de
animación.

To create and control loops, you use a loop statement. Para crear bucles y control, se utiliza
una sentencia de bucle. A loop statement causes a computer program to return to the same
place more than once. Una sentencia de bucle hace que un programa de ordenador para
volver al mismo lugar más de una vez. If the term seems unusual to you, think of what a
stunt plane does when it loops: It completes a circle and returns to the place it started the
loop. Si el término parezca inusual para usted, pensar en lo que un avión de acrobacia hace
cuando bucles: Completa un círculo y regresa al lugar que se inició el ciclo. There are three
loop statements in Java: , , and . Hay tres sentencias de bucle en Java: para, hacer, y
mientras lo hacen. These loop statements are often interchangeable in a program
because each can be made to work like the others. Estas declaraciones son a menudo
intercambiables bucle en un programa, porque cada uno puede llegar a funcionar como los
demás. The choice of which loop statement to use in a program often depends on personal
preference, but it's beneficial to learn how all three work. La elección de la sentencia de
bucle para usar en un programa a menudo depende de las preferencias personales, pero es
beneficioso para aprender todo el trabajo de tres. You frequently can simplify a loop
section of a program by choosing the right statement. Con frecuencia puede simplificar de
una sección de bucle de un programa por la elección de la declaración de la derecha.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 Using the loop Utilizando el bucle for


 Using the loop Utilizando el bucle do
 Using the - loop Uso del hacer - bucle while
 Exiting a loop prematurely Salir de un bucle antes de tiempo
 Naming a loop Nombrar a un bucle

for Loops para Loops


The most complex of the loop statements is . El más complejo de las sentencias de bucle es
para. The loop is often used in cases where you want to repeat a section of a program for
a fixed amount of times. El bucle for se utiliza a menudo en los casos en que desea repetir
una sección de un programa por un importe fijo de veces. It also can be used if the number
of times the loop should be repeated is variable. También se puede utilizar si el número de
veces que el ciclo se debe repetir es variable. The following is an example of a loop: El
siguiente es un ejemplo de un bucle for:

for (int number = 0; number < 1000; number++) { for (int


numero = 0; número <1000, el número + +) {
if (number % 12 == 0) if (% el número 12 == 0)
System.out.println("#: " + number);
System.out.println ("#:" + numero);
} }

This loop displays every number from 0 to 999 that is evenly divisible by 12. Este bucle
muestra cada número del 0 al 999 que es divisible por 12. Every loop has a variable that is
used to determine when the loop should begin and end. Cada bucle tiene una variable que
se utiliza para determinar cuando el bucle debe comenzar y terminar. This variable often is
called the counter. Esta variable a menudo se llama el mostrador. The counter in the
preceding loop is . El contador en el bucle anterior es el número.

The example illustrates the three parts of a statement: El ejemplo ilustra las tres partes de
una sentencia for:
 The initialization section: In the first part, the variable is initialized with a value of 0. La
sección de inicialización: En la primera parte, la variable número se inicia con un valor de
0.
 The conditional section: In the second part, there is a conditional test like one you might
use in an statement. La sección condicional: En la segunda parte, hay una prueba
condicional como uno podría utilizar en una sentencia if. The test is . La prueba es el
número <10000.
 The change section: The third part is a statement that changes the value of the variable by
using the increment operator. La sección de cambio: La tercera parte es una declaración
que los cambios en el valor de la variable número utilizando el operador de incremento.

In the initialization section, you can set up the counter variable that you want to use in the
statement. En la sección de inicialización, puede establecer la variable de contador que
desee utilizar en la instrucción for. You can create the variable inside the statement, as the
variable was created in the example, or you can create the variable elsewhere in the
program. Usted puede crear la variable dentro de la declaración, como la variable número
fue creado en el ejemplo, o puede crear la variable en el resto del programa. In either case,
the variable should be given a starting value in this section of the statement. En cualquier
caso, la variable se debe dar un valor inicial de esta sección de la sentencia for. The
variable will have this value when the loop starts. La variable tendrá este valor cuando
comience el bucle.

The conditional section contains a test that must remain true for the loop to continue
looping. La sección condicional contiene una prueba que debe seguir siendo válido para el
circuito de continuar bucle. Once the test is false, the loop will end. Una vez que la prueba
es falsa, el bucle terminará. In this example, the loop will end when the variable is no
longer smaller than 1,000. En este ejemplo, el bucle se termina cuando la variable de
número no es menor que 1000.

The last section of the statement contains a Java statement that changes the value of the
counter variable in some way. La última sección de la instrucción contiene una declaración
de Java que cambia el valor de la variable de contador de alguna manera. This statement is
handled each time the loop goes around. Esta declaración se maneja cada vez que el bucle
recorre. The counter variable has to change in some way, or the loop will never end. La
variable de contador tiene que cambiar de alguna manera, o el bucle nunca terminará. For
instance, in this example, is incremented by one using the increment operator in the
change section. Por ejemplo, en este ejemplo, el número se incrementa en uno con el
operador de incremento + + en la sección de cambio. If were not changed, it would stay at
its original value, 0, and the conditional would always be true. Si el número no se
modificaron, se quedaría en su valor original, 0, y el número condicional <1000 siempre
sería verdad.
The statements inside the bracket marks( ) are also executed during each trip through the
loop. Los estados dentro de la marca del soporte ({}) también se ejecutan en cada viaje a
través del lazo. The bracketed area is usually where the main work of the loop takes place,
although some loops do all of their work in the change section. El texto entre corchetes es
generalmente donde el trabajo principal del circuito se lleva a cabo, aunque algunos lazos
de hacer todo su trabajo en la sección de cambio.

The preceding example had two statements within the and marks: El ejemplo anterior
tiene dos estados dentro de los {y} marcas:

if (number % 12 == 0) if (% el número 12 == 0)
System.out.println("#: " + number);
System.out.println ("#:" + numero);

These statements will be executed 1,000 times. Estas declaraciones se ejecutarán 1.000
veces. The loop starts by setting the variable equal to 0. El ciclo se inicia mediante el
establecimiento de la variable número igual a 0. It then adds 1 each pass through the loop
and stops when is no longer less than 1000. A continuación, agrega una de cada pasada por
el bucle y se detiene cuando el número no es inferior a 1000. Every time is evenly divisible
by 12, the number is displayed next to the text . Cada vez el número es divisible por 12, el
número aparece junto al texto #:.

An unusual term that you might hear in connection with loops is iteration. Un término de
fantasía que usted puede escuchar en relación con los lazos se iteración. An iteration is a
single trip through a loop. Una iteración es un viaje único a través de un bucle. The counter
variable that is used to control the loop is often called an iterator. La variable contador que
se utiliza para controlar el bucle se llama a menudo un iterador.

Each section of a loop is set off from the other sections with a semicolon ( ). Cada sección
de un bucle for se pone en marcha de las otras secciones con un punto y coma (;). A loop
can have more than one variable set up during the initialization section and more than one
statement in the change section, as in the following: Un bucle for puede tener más de una
variable establecido en la sección de inicialización y más de una declaración en la sección
de cambio, como en lo siguiente:

for (i = 0, j = 0; i * j < 1000; i++, j += 2) { for (i =


0, j = 0; i * j <1000; i + +, + j = 2) {
System.out.println(i + " * " + j + " = " i * j);
System.out.println (i + "*" + j + "=" i * j);
} }
These multiple statement sections of the loop are set off by commas, as in . Estas
secciones múltiples declaración del bucle for son separados por comas, como en i = 0, j
= 0. This loop will display a list of equations where the variable is multiplied by the
variable. Este bucle se mostrará una lista de ecuaciones donde la variable se multiplica la i
por la variable j. The variable increases by 1, and the variable increases by 2 during each
trip through the loop. Los aumentos variable i en 1, y los aumentos de la variable j por 2
en cada viaje a través del lazo. Once multiplied by is no longer less than 1,000, the loop
will end. Una vez que multiplicado por j ya no menos de 1.000, el bucle terminará.

Sections of a loop can be empty. Secciones de un bucle for puede estar vacío. An example
of this would be if the counter variable has already been created with an initial value in
another part of the program, as in the following: Un ejemplo de esto sería si la variable de
contador ya se ha creado con un valor inicial en otra parte del programa, como en lo
siguiente:

for ( ; displayCount < endValue; displayCount++) { // loop


statements would be here } for (; EndValue <displayCount;
displayCount + +) {/ / sentencias de bucle estaría aquí}

Caution: Because many Java statements end with a semicolon, an easy mistake to make is putting
a semicolon at the end of a statement, as in the following: Precaución: Debido a que muchos
estados de Java final con un punto y coma, un error fácil de hacer es poner un punto y coma al
final de una sentencia, como en el siguiente:

for (int i = 0; i < 100; i++); { for (int i = 0; i <100; i + +) {


value = value + i; valor = valor + i;
}}

In this example, the semicolon puts the statements in the brackets, , outside of the loop. En
este ejemplo, pone el punto y coma los estados en los soportes, el valor = valor + i;,
fuera del bucle. As a result, nothing will happen as the loop is handled. Como resultado, no
pasará nada como el bucle for se maneja. The program will compile without any errors, but
you won't get the results you expect when it runs. El programa se compila sin ningún error,
pero no obtendrá los resultados esperados cuando se ejecuta.

while Loops mientras que los bucles


The loop does not have as many different sections to set up as the loop. El bucle while no
tiene tantas secciones diferentes de configurar como el bucle for. The only thing it needs is
a conditional test, which accompanies the statement. Lo único que necesita es una prueba
condicional, que acompaña a la sentencia while. The following is an example of a loop:
El siguiente es un ejemplo de un bucle while:
while ( gameLives > 0) { while (gameLives> 0) {
// the statements inside the loop go here / / Las
sentencias dentro del bucle haga clic aquí
} }

This loop will continue repeating until the variable is no longer greater than 0. Este lazo
seguirá repitiendo hasta que la variable gameLives ya no es mayor que 0. The statement
tests the condition at the beginning of the loop, before any statements of the loop have been
handled. La declaración, mientras que las pruebas de la condición al inicio del bucle,
antes de las declaraciones del bucle han sido manipulados.

When a program reaches the statement for the first time, if the tested condition is false, the
statements inside the loop will be ignored. Cuando un programa llega a la instrucción,
mientras que por primera vez, si la condición probada es falsa, los estados dentro del
bucle será ignorado. If the condition is true, the loop goes around once and tests the
condition again. Si la condición, mientras que es cierto, el bucle gira alrededor de una
vez pruebas de la condición, mientras que otra vez. If the tested condition never
changes inside the loop, the loop will keep looping indefinitely. Si la condición probada
nunca cambia dentro del bucle, el bucle se mantenga indefinidamente en bucle.

do-while Loops do-while Bucles


The - loop is similar in function to the loop, but the conditional test goes in a different
place. El hacer - bucle while es similar en funciones al bucle while, pero la prueba
condicional va en un lugar diferente. The following is an example of a - loop: El siguiente
es un ejemplo de hacer - bucle while:

do { do {
// the statements inside the loop go here / / Las
sentencias dentro del bucle haga clic aquí
} while ( gameLives > 0 ); } While (gameLives> 0);

Like the previous loop, this loop will continue looping until the variable is no longer
greater than 0. Al igual que el bucle while anterior, este ciclo continuará hasta que la
variable de bucle gameLives ya no es mayor que 0. The - loop is different because the
conditional test is conducted after the statements inside the loop instead of before them. El
hacer - bucle while es diferente porque la prueba condicional se lleva a cabo después de
las instrucciones dentro del bucle en vez de delante de ellos.

When the loop is reached for the first time as a program runs, the statements between the
and the are handled automatically. Cuando el bucle do se alcanza por primera vez como un
programa se ejecuta, las declaraciones entre el hacer y el tiempo se manejan de forma
automática. Then the condition is tested to determine whether the loop should be repeated.
Entonces la condición mientras se prueba para determinar si el bucle se debe repetir. If the
condition is true, the loop goes around one more time. Si la condición, mientras que es
cierto, el bucle va, una vez más. If the condition is false, the loop ends. Si la condición es
falsa, el bucle termina. Something must happen inside the and statements that changes the
condition tested with , or the loop will continue indefinitely. Algo debe ocurrir dentro del
hacer y al mismo tiempo las declaraciones que cambia la condición de prueba con
tiempo, o el bucle continuará indefinidamente. The statements inside a - loop will always
be handled at least once. Las declaraciones dentro de un hacer - bucle while siempre se
tratará al menos una vez.

If you're still confused about the difference between a loop and a - loop, engage in a little
role-playing and pretend you're a teenager who wants to borrow your father's car. Si todavía
está confundido acerca de la diferencia entre un bucle while y un hacer - bucle while,
participar en un papel poco juego y simular que eres un adolescente que quiere pedir
prestado el coche de su padre. If you are a teenager with a case of car envy, all the better. Si
usted es un adolescente con un caso de envidia coche, mejor que mejor. There are two
strategies that you can take: Hay dos estrategias que puede tomar:

1. Borrow the car first and tell Dad later that you did it. 1. Obtención de Préstamos del
primer coche y decirle a papá después de que usted lo hizo.

2. Ask Dad before you borrow the car. 2. Pide papá antes de pedir prestado el coche.

Strategy 1 has an advantage over Strategy 2 because you get to use the car once even if Dad
doesn't want to let you use it. Estrategia 1 tiene una ventaja sobre Estrategia 2 porque se
llega a utilizar el coche una vez, incluso si el papá no quiere dejar de usarlo. The - loop is
like Strategy 1 because something happens once even if the loop condition is false the first
time is encountered. El hacer - bucle while es como una estrategia porque algo pasa una
vez, incluso si la condición del bucle es falsa la primera vez, mientras que se encuentra.
The loop is like Strategy 2 because nothing will happen unless the condition at the
beginning is true. El bucle while es como Estrategia 2 porque no pasará nada menos que la
condición, mientras que al principio es cierto. It all depends on the situation in your
program. Todo depende de la situación en su programa. Sams.net makes no warranties
express nor implied that your father will be happy if you borrow his car without telling him
first. Sams.net no hace ninguna garantía expresa o implícita de que tu padre estará
encantado si usted pide prestado su automóvil sin antes hablar con él primero.

Exiting a Loop Salir de un bucle


The normal way to exit a loop is for the condition that is tested to become false. La forma
normal de salir de un bucle es para la condición de que se prueba para llegar a ser falso.
This is true of all three types of loops in Java: , , and - . Este es el caso de los tres tipos de
bucles en Java, porque, al mismo tiempo, y - al mismo tiempo. However, there
might be times when you want a loop to end immediately even if the condition being tested
is still true. Sin embargo, puede haber ocasiones en las que quieres un bucle para poner fin
de inmediato, incluso si la afección que se estudia es cierto. You can do this with a
statement, as shown in the following code: Usted puede hacer esto con una sentencia
break, como se muestra en el siguiente código:

while (index <= 1000) { mientras que (índice <= 1000) {


index = index + 5; índice = índice + 5;
if (index == 400) if (indice == 400)
break; break;
System.out.println("The index is " + index);
System.out.println ("El índice es" + índice);
} }

This loop will continue looping until the value of the variable is greater than 1,000. Este
ciclo continuará en bucle hasta que el valor de la variable índice es mayor de 1.000.
However, a special case causes the loop to end even if the variable is less than or equal to
1,000: If equals 400, the loop ends immediately. Sin embargo, un caso especial hace que el
bucle final, incluso si la variable del índice es menor o igual a 1000: Si el índice es igual
a 400, el bucle finaliza inmediatamente.

Another special-circumstance statement that you can use inside a loop is . -Otra
circunstancia declaración especial que se puede utilizar dentro de un bucle es continuar.
The statement causes the loop to exit its current trip through the loop and start over at the
first statement of the loop. La sentencia continue hace que el bucle para salir de su actual
viaje a través del bucle y volver a empezar en la primera instrucción del bucle. Consider the
following loop: Considere el siguiente bucle:

while (index <= 1000) { while (Índice general <= 1000) {


index = index + 5; índice = índice + 5;
if (index == 400) if (indice == 400)
continue; continuar;
System.out.println("The index is " + index);
System.out.println ("El índice es" + índice);
} }
In this loop, the statements will be handled normally unless the value of equals 400. En
este ciclo, los estados se manejan normalmente a menos que el valor del índice es igual a
400. In that case, the statement causes the loop to go back to the statement instead of the
statement. En ese caso, la causa continuará la declaración del bucle para volver a la
sentencia while en lugar de los System.out.println () declaración. Because of the
statement, the loop will never display the following text: Debido a la sentencia continue,
el bucle nunca se mostrará el texto siguiente:

The index is 400 El índice es de 400

You can use the and statements with all three kinds of Java loop statements. Usted puede
utilizar el break y continue con los tres tipos de sentencias de bucle de Java.

Naming a Loop Nombrar a un bucle


Like other statements in Java programs, loops can be put inside of each other. Al igual que
otros estados en los programas de Java, los lazos se pueden poner dentro de cada uno. The
following shows a loop inside of a loop: A continuación se muestra un bucle en el interior
de un bucle while:

while ( totalCoconuts < 100) { while (totalCoconuts <100)


{
for ( int count = 0; count < 10; count++) { for (int
cuenta = 0; contador <10; cuenta + +) {
totalCoconuts = totalCoconuts + count;
totalCoconuts = totalCoconuts + count;
if (totalCoconuts > 400) if (totalCoconuts> 400)
break; break;
} }
} }

The statement will cause the loop to end if the variable equals 400 or greater. La
sentencia break hará que el bucle for para poner fin a si la variable es igual a
totalCoconuts 400 o mayor. However, there might be a case where you want to out of
both loops for some reason. Sin embargo, puede haber un caso en el que desea salir de los
bucles, por alguna razón. To make this possible, you have to give the outer loop--the
statement--a name. Para hacer esto posible, hay que dar el lazo externo - al mismo tiempo
de datos - un nombre. To name a loop, put the name on the line before the beginning of the
loop and follow it with a colon ( ). Para nombrar un bucle, poner el nombre en la línea
antes del comienzo del bucle y seguir con dos puntos (:).
Once the loop has a name, you can use the name after the or statement to indicate which
loop the or statement applies to. Una vez que el bucle tiene un nombre, puede utilizar el
nombre después de la pausa o continuar declaración para indicar que la ruptura del lazo
o continue se aplica a. Note that although the name of the loop is followed by a colon at
the spot where the loop begins, the colon is not used with the name in a or statement.
Tenga en cuenta que aunque el nombre del ciclo es seguido por dos puntos en el lugar
donde comienza el bucle, el colon no se utiliza con el nombre en un break o continue
comunicado. The following example repeats the previous one with the exception of one
thing: If the variable equals 400 or more, both loops are ended. En el ejemplo siguiente se
repite la anterior, con la excepción de una cosa: Si la variable totalCoconuts es igual a
400 o más, tanto los lazos que se terminan.

coconutLoop: coconutLoop:
while ( totalCoconuts < 100) { while (totalCoconuts <100)
{
for ( int count = 0; count < 10; count++) { for (int
cuenta = 0; contador <10; cuenta + +) {
totalCoconuts = totalCoconuts + count;
totalCoconuts = totalCoconuts + count;
if (totalCoconuts > 400) if (totalCoconuts> 400)
break coconutLoop; coconutLoop descanso;
} }

} }

Workshop: Teaching Your Computer a Lesson Taller: Enseñanza de la computadora una


lección
This hour's workshop provides evidence that you cannot punish your computer in the same
way that Bart Simpson is punished at the beginning of each episode of The Simpsons. Este
taller hora demuestra que no se puede castigar a su equipo de la misma manera que Bart
Simpson es castigado al inicio de cada episodio de Los Simpson. Pretend you're a teacher,
and the computer is the kid who contaminated your morning cup of coffee with Thorium
230. Imagina que eres un maestro, y el equipo es el chico que contaminados mañana su taza
de café con torio 230. Even if you're the most strident liberal, you realize that the computer
must be taught a lesson--it's not acceptable behavior to give the teacher radiation poisoning.
Incluso si usted es el liberal más estridentes, te das cuenta de que el equipo debe ser una
lección - no es un comportamiento aceptable para dar el envenenamiento por radiación
maestro. Your computer must be punished, and the punishment is to display the same
sentence over and over again. El equipo debe ser castigado, y el castigo es para mostrar la
misma frase una y otra vez.

The program will use a loop statement to handle a statement again and again. El programa
de repetición se utiliza una instrucción de bucle para manejar un System.out.println
() Declaración de una y otra vez. Once the computer has been dealt this punishment for
25,000 sentences or one minute, whichever comes first, it can stop running and think about
the error of its ways. Una vez que el equipo se ha tratado este castigo para 25.000 frases o
un minuto, lo que ocurra primero, se puede dejar de correr y pensar en el error de sus
formas.

A topic of heated debate here at Sams.net concerns whether the punishment is severe
enough. Un tema de debate aquí, en las preocupaciones Sams.net si el castigo es lo
suficientemente grave. Thorium is a silver-white metal that has a half-life of 80,000 years.
El torio es un metal blanco plateado que tiene una vida media de 80.000 años. Some
scientists believe that it is as toxic as plutonium, and if it finds a home in someone's liver,
bone marrow, or lymphatic tissue, Thorium 230 can cause cancer, leukemia, or lung cancer.
Algunos científicos creen que es tan tóxico como el plutonio, y si encuentra un hogar en el
hígado de alguien, la médula ósea o del tejido linfático, torio 230 puede causar cáncer,
leucemia, o cáncer de pulmón. A student who irradiates a teacher probably should receive
three hours of in-school detention, at least. Un estudiante que irradia un maestro
probablemente deberían recibir tres horas de detención en la escuela, por lo menos.

Use your word processor to create a new file called . Use su procesador de textos para
crear un nuevo archivo llamado Repeat.java. Enter the text of Listing 8.1 and save the
file when you're done. Introduzca el texto del listado 8.1 y guardar el archivo cuando haya
terminado.

Listing 8.1. Listado 8.1. The full source code of Repeat.java. El código fuente completo
de Repeat.java.
1: import java.util.*; 2: 3: class Repeat { 4: public
static void main(String arguments[]) { 5: String sentence =
"Thorium 230 is not a toy."; 6: int count = 0; 7:
GregorianCalendar start = new GregorianCalendar(); 8: int
startMinute = start.get(Calendar.MINUTE); 9: int
startSecond = start.get(Calendar.SECOND); 10:
start.roll(Calendar.MINUTE, true); 11: int nextMinute =
start.get(Calendar.MINUTE); 12: int nextSecond =
start.get(Calendar.SECOND); 13: while (count++ <= 25000)
{ 14: System.out.println(sentence); 15: GregorianCalendar
now = new GregorianCalendar(); 16: if
(now.get(Calendar.MINUTE) >= nextMinute) 17: if
(now.get(Calendar.SECOND) >= nextSecond) 18: break; 19: }
20: System.out.println("\nI wrote the sentence " + count +
" times."); 21: System.out.println("I have learned my
lesson."); 22: } 1: import java.util .*; 2: 3: Repita la
clase {4: public static void principal (argumentos String
[]) {5: String frase = "torio 230 no es un juguete."; 6:
int cuenta = 0 ; 7: inicio GregorianCalendar nueva =
GregorianCalendar (); 8: startMinute int = start.get
(Calendar.MINUTE); 9: startSecond int = start.get
(Calendar.SECOND); 10: start.roll (Calendar.MINUTE,
verdadera ); 11: nextMinute int = start.get
(Calendar.MINUTE); 12: nextSecond int = start.get
(Calendar.SECOND), 13: while (cuenta + + <= 25000) {14:
System.out.println (frase) ; 15: GregorianCalendar ahora =
GregorianCalendar nuevo (); 16: if (now.get
(Calendar.MINUTE)> = nextMinute) 17: if (now.get
(Calendar.SECOND)> nextSecond =) 18: descanso; 19:} 20:
System.out.println ("\ nI escribió la frase" + cuenta +
"veces."); 21: System.out.println ("He aprendido mi
lección."); 22:} 23:}

The following things are taking place in this program: Los siguientes factores están
teniendo lugar en este programa:

 Line 1: The statement makes the group of classes available to this program. Línea 1: La
declaración de importación hace que el grupo de java.util de clases disponibles
para este programa. You're going to use two of them, and , in order to keep track of time
while the program is running. Vas a usar dos de ellos, Calendario y
GregorianCalendar, a fin de mantener la noción del tiempo mientras que el programa
se está ejecutando.
 Lines 2 and 3: The class is declared, and the block of the program begins. Las líneas 2 y 3:
La clase Repita se declara, y principal) de bloque de (el programa se inicia el.
 Lines 5 and 6: The variable is set up with the text of the punishment sentence, and the
variable is created with a value of 0. Las líneas 5 y 6: La variable frase se configura con el
texto de la sentencia de castigo, y la variable de recuento se crea con un valor de 0.
 Line 7: Using the class, which is used to retrieve the time information, the variable is
created with the current time. Línea 7: Utilización de la clase GregorianCalendar, que
se utiliza para recuperar la información del tiempo, la variable de inicio se crea con la
hora actual.
 Lines 8 and 9: The method of the class is used to retrieve the current minute and second
and store them in the variables and . Las líneas 8 y 9: El método get () de la clase
GregorianCalendar se utiliza para recuperar los minutos y segundos y almacenarlos en
el startMinute variables y startSecond.
 Line 10: The method is used to roll the value of the variable one minute forward in time.
Línea 10: El rollo de GregorianCalendar () se utiliza para enrollar el valor de la
variable de avance minutos comenzará en el tiempo.
 Lines 11 and 12: The method is used again to retrieve the minute and second for and
store them in the variables and . Las líneas 11 y 12: El método get () se utiliza de nuevo
para recuperar el minuto y segundo de inicio y almacenarlos en el nextMinute
variables y nextSecond.
 Line 13: The statement begins a loop using the variable as the counter. Línea 13: La
declaración, mientras que comienza un bucle que utiliza la variable de cuenta
como el contador. When hits 25,000, the loop will end. Al contabilizar los accesos y
25.000, el bucle terminará.
 Line 14: The punishment text, stored in the string variable , is displayed. Línea 14: El texto
castigo, almacenada en la oración variable de cadena, se muestra.
 Line 15: Using the class, the variable is created with the current time. Línea 15: Utilización
de la clase GregorianCalendar, la variable ahora se crea con la hora actual.
 Lines 16-18: Using one statement inside of another, the program tests to see whether one
minute has passed by comparing the current minute and second to the values of and .
Líneas 16-18: El uso de una sentencia if dentro de otro, las pruebas del programa para
ver si ha pasado un minuto mediante la comparación de los minutos y el segundo a los
valores de nextMinute y nextSecond. If it has passed, ends the loop. Si ha pasado,
romper los extremos del bucle while.
 Line 19: The marks the end of the loop. Línea 19:} marca el final del bucle while.
 Lines 20 and 21: The computer displays the number of times it repeated the punishment
sentence and claims to be rehabilitated. Líneas 20 y 21: El equipo muestra el número de
veces que se repite la frase castigo y dice ser rehabilitados.
 Lines 22 and 23: The block of the program and the program are closed out with marks.
Líneas 22 y 23: El () bloque principal del programa y el programa se cerró con}
marcas.

Compile the program with the compiler tool and then give it a try by typing the following
at the command line: Compilar el programa con la herramienta del compilador javac y
luego darle una oportunidad al escribir lo siguiente en la línea de comandos:

java Repeat Repita java

Run this program several times to see how many sentences are displayed in a minute's time.
Ejecutar este programa varias veces para ver cuántas sentencias se muestran en tiempo de
un minuto. The program is an excellent way to see whether your computer is faster than
mine. El programa de repetición es una excelente manera de ver si su computadora es
más rápida que la mía. During the testing of this workshop program, usually displayed
from 8,700 to 9,100 sentences in a minute's time. Durante las pruebas de este programa de
talleres, repetir por lo general aparecen de 8.700 a 9.100 sentencias en el minuto de una
hora. If your computer displays the sentence more times than mine does, don't just send me
your condolences. Si el equipo muestra la hora de la oración más que la mía no, no me
acaba de enviar sus condolencias. Buy more of my books so I can upgrade. Comprar más
de mis libros, así que se puede actualizar.

Caution: Although most of the programs that you will write in this book will work under version
1.0.2 of the Java Developer's Kit, the program will not compile successfully unless you use version
1.1 of the Kit. Precaución: Aunque la mayoría de los programas que va a escribir en este libro de
trabajo bajo la versión 1.0.2 de Java Developer Kit, el programa no se compilará Repita con éxito
a menos que utilice la versión 1.1 del Kit. This program uses the class, which, like many other new
features, was introduced with 1.1 and does not exist in 1.0.2. Este programa utiliza la clase
GregorianCalendar, que, como muchas otras nuevas características, se introdujo con 1.1 y no
existe en la 1.0.2. JavaSoft encourages the use of new features like this because they make
improvements on the language. JavaSoft fomenta el uso de las nuevas características como esta,
ya que hacer mejoras en el lenguaje. For example, is part of JavaSoft's effort to enable
programmers to use different calendar systems in Java programs. Por ejemplo,
GregorianCalendar es parte del esfuerzo de JavaSoft para permitir a los programadores utilizar
el calendario de los distintos sistemas en los programas de Java.

Summary Resumen
The information presented in this chapter is information that you will be coming back to
again and again and again when you write programs. La información presentada en este
capítulo es la información que se va a volver una y otra vez y otra vez al escribir
programas. Loops are a fundamental part of most programming languages. Los lazos son
una parte fundamental de la mayoría de los lenguajes de programación. In several of the
hours to come, you'll get a chance to manipulate graphics so that you can produce animated
effects. En varias de las próximas horas, usted tendrá la oportunidad de manipular gráficos,
para que pueda producir efectos de animación. You couldn't do this without loops. No se
podía hacer esto sin bucles.

Q&A Q & A
Q Should the counter variable used in a for loop be created inside the for statement or
before the loop begins? Q caso de que la variable de contador utilizado en un bucle for
se creará dentro de la de declaración o antes de que comience el bucle?

A The only time the counter should be created outside of the loop, or any other loop for
that matter, is when it needs to be used in another part of the program. La única vez que
El debe ser la lucha contra creados fuera del bucle for, o cualquier otro lazo para el caso,
es cuando se debe utilizar en otra parte del programa. A variable that is created in a loop
or other kind of block statement only exists inside that block. Una variable que se crea en
un bucle o de otro tipo de bloque de sentencias sólo existe dentro de ese bloque. You
can't use the value in any other part of the program. Usted no puede utilizar el valor en
cualquier otra parte del programa. This is good programming practice because it makes it
harder to misuse variables--you can't set their value in one part of the program and use
them somewhere else incorrectly. Esta es una práctica deseable, ya que hace más difícil a
las variables de desviación - no se puede establecer su valor en una parte del programa y
utilizarlos en otro lugar incorrecto. The concept of a variable existing in one part of a
program and not existing anywhere else is called scope, and it's covered fully during Hour
11, "Describing What Your Object Is Like." El concepto de una variable existente en una
parte de un programa y no existentes en ningún otro lugar se llama alcance, y es cubierto
en su totalidad durante la hora 11, "Describiendo lo que su objeto es como."

Q The term initialization has been used in several places. Q La inicialización término se
ha utilizado en varios lugares. What does it mean? ¿Qué significa?

A It means to give something an initial value and set it up. Un Esto significa dar algo de un
valor inicial y la levantó. When you create a variable and assign a starting value to it, you
are initializing the variable. Cuando se crea una variable y asignar un valor inicial a la
misma, que son la inicialización de la variable.

Q If a loop never ends, how does the program stop running? Q Si un bucle no termina
nunca, ¿cómo funciona el programa deje de funcionar?

A Usually in a program where a loop does not end, something else in the program is set up
to stop execution in some way. A lo general en un programa donde un bucle no termina,
otra cosa en el programa está configurado para detener la ejecución de alguna manera.
For example, a loop could continue indefinitely while the program waits for the user to
click a button labeled . Por ejemplo, un bucle podría continuar indefinidamente, mientras
que el programa espera a que el usuario haga clic en un botón Salir. However, if a
program isn't working correctly, one bug you'll run into during testing is a loop that cannot
be stopped. Sin embargo, si un programa no funciona correctamente, un error que se
quedará en durante el ensayo es un bucle que no se puede detener. This bug is called an
infinite loop because the program will loop happily forever. Este error se llama un bucle
infinito, porque el programa se repetirá felices para siempre. If one of the Java programs
you run from the command line is stuck in an infinite loop, press Ctrl + C. Si uno de los
programas de Java se ejecuta desde la línea de comandos se ha quedado atascado en un
bucle infinito, pulse Ctrl + C.

Quiz Quiz
The following questions will test your knowledge of loops. Las siguientes preguntas se
pondrá a prueba su conocimiento de los bucles. In the spirit of the subject matter, repeat
each of these until you get them right. En el espíritu de la materia, repetir cada uno de estos
hasta que les salga bien.

Questions Preguntas

1. What must be used to separate each section of a statement? 1. Lo que se debe utilizar
para separar cada sección de una sentencia?

(a) Commas (A) comas


(b) Semicolons (B) punto y coma
(c) Off-duty police officers (C) Derecho de los agentes de policía-Off

2. Which statement causes a program to go back to the statement that began a loop and
then keep going from there? 2. ¿Qué declaración hace un programa para volver a la
afirmación de que comenzó un lazo y luego seguir adelante a partir de ahí?

(a) (A) continúe


(b) (B) siguiente
(c) (C) acceder

3. When it comes to borrowing a car from your father, what lesson did you learn during
this hour? 3. Cuando se trata de pedir prestado un coche de su padre, ¿qué lección ha
aprendido durante esta hora?

(a) Don't even think about it. (A) ¿ni siquiera pensar en ello.
(b) Speak softly and carry a big stick. (B) Habla suavemente y lleva un gran garrote.
(c) It's better to beg forgiveness than to ask permission. (C) Es mejor pedir perdón que
pedir permiso.

Answers Respuestas

1. b. 1. B. Commas are used to separate things within a section, but semicolons separate
sections. Las comas se utilizan para cosas distintas dentro de una sección, pero punto y
coma secciones separadas.

2. a. 2. A. The statement ends a loop entirely, and skips to the next go-around of the
loop. La sentencia break termina un ciclo completo, y continuar salta al siguiente y al
aire del ciclo.

3. c. 3. C.

Activities Actividades
If your head isn't going in circles from all this looping, review the topics of this hour with
the following activities: Si la cabeza no va en los círculos de todo este bucle, revise los
temas de esta hora con las siguientes actividades:

 Modify the program so that it uses a loop instead of a loop and compare the efficiency of
each approach. Modificar el programa Repita para que utilice un bucle en lugar de un
bucle while y comparar la eficiencia de cada enfoque.
 Write a short program using loops that finds the first 400 prime numbers. Escriba un
programa corto con bucles que encuentra los primeros 400 números primos.

 9 horas
o Almacenamiento de información con matrices
 Creación de matrices de
 Uso de matrices
 Las matrices multidimensionales
 Taller: Matriz de Premios hecho
 Listado 9.1. El código fuente completo de Wheel.java.
 Listado 9.2. La salida del programa de la rueda.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades
Hour 9 9 horas

Storing Information with Arrays Almacenamiento de


información con matrices

No one benefits more from the development of the computer than Santa Claus. Nadie se
beneficia más con el desarrollo del equipo de Santa Claus. For centuries, humankind has
put an immense burden on him to gather and process information. Durante siglos, la
humanidad ha puesto una gran carga sobre él para recoger y procesar la información. Old
St. Nick has to keep track of the following things: Old St. Nick tiene que hacer un
seguimiento de las siguientes cosas:

 Naughty children Niños traviesos


 Nice children los niños de Niza
 Gift requests Peticiones de regalos
 Homes with impassable chimneys Las casas con chimeneas intransitables
 Women who want more from Santa than Mrs. Claus is willing to let him give Las mujeres
que quieren más que la señora de Santa Claus está dispuesto a dejar que le dan
 Countries that shoot unidentified aircraft first and ask questions later Los países que
disparar aeronave no identificada primero y preguntar después

Computers must have been a great boon at the North Pole because they are ideal for the
storage, categorization, and study of information. Los ordenadores deben haber sido una
gran ayuda en el Polo Norte, ya que son ideales para el almacenamiento, clasificación y
estudio de la información.

The most basic way that information is stored in a computer program is by putting it into a
variable. La forma más básica que la información se almacena en un programa de
ordenador es poniéndolo en una variable. However, this method is limited to relatively
simple usage. Sin embargo, este método se limita al uso relativamente simple. If Santa had
to give each naughty child his or her own variable name, he'd be working on the program
for the next 12 holiday seasons at least, to say nothing of the effect on his jolly disposition
or his carpal tunnel nerves. Si Santa tuvo que dar a cada niño travieso su propio nombre de
la variable, que estaría trabajando en el programa para las temporadas de vacaciones
próximos 12 al menos, por no hablar del efecto sobre su carácter alegre o los nervios del
túnel carpiano. The list of naughty children is an example of a collection of similar
information. La lista de niños traviesos es un ejemplo de una colección de información
similar. Each child's name is a string of text or some kind of Santa Information System ID
number. El nombre de cada niño es una cadena de texto o algún tipo de Sistema de
Información de Santa número de identificación. In order to keep track of a list of this kind,
you can use arrays. Con el fin de no perder de vista una lista de este tipo, puede utilizar las
matrices.

Arrays are groups of related variables that share the same type. Las matrices son grupos de
variables relacionadas que comparten el mismo tipo. You can have arrays of any type of
information that can be stored as a variable. Usted puede tener arreglos de cualquier tipo de
información que puede ser almacenado como una variable. Arrays can be used to keep
track of more sophisticated types of information than a single variable, but they are almost
as easy to create and manipulate as variables are. Las matrices se pueden utilizar para
realizar un seguimiento de tipos más sofisticados de la información de una sola variable,
sino que son casi tan fáciles de crear y manipular variables como son.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 Creating an array Creación de una matriz


 What a dimension of an array is Lo que una dimensión de una matriz es
 Giving a value to an array element Dar un valor a un elemento de la matriz
 Changing the information in an array Cambio de la información en una matriz
 Making multidimensional arrays Hacer arreglos multidimensionales

Creating Arrays Creación de matrices de


Arrays are variables that are grouped together under a common name. Las matrices son
variables que se agrupan bajo un nombre común. The term should be familiar to you though
the meaning might not be so clear--think of a salesman showing off his array of fabulous
cleaning products or a game show with a dazzling array of prizes. El plazo debe ser familiar
para usted si el significado no puede ser tan evidentes - pensar en un vendedor de mostrar
su variedad de fabulosos productos de limpieza o un programa de juegos con una
deslumbrante variedad de premios. Like variables, arrays are created by stating the type of
the variable being organized into an array and the name of the array. Al igual que las
variables, las matrices se crean indicando el tipo de la variable que se organizan en una
matriz y el nombre de la matriz. The difference lies in the addition of the square bracket
marks and . La diferencia radica en la incorporación de la plaza del soporte de las marcas
[y].

You can create arrays for any type of information that can be stored as a variable. Usted
puede crear matrices de cualquier tipo de información que puede ser almacenado como una
variable. For example, the following statement creates an array of string variables: Por
ejemplo, la siguiente instrucción crea una matriz de variables de cadena:

String[] naughtyChild; String [] naughtyChild;


Here are a few more examples: Éstos son algunos ejemplos más:

int[] reindeerWeight; int [] reindeerWeight;


boolean[] hostileAirTravelNations; Boolean []
hostileAirTravelNations;

Java is flexible about where the square brackets are placed when an array is being created.
Java es flexible en cuanto a que los corchetes se colocan en una matriz que se está creando.
You can put them after the variable name instead of after the variable type, as in the
following: Usted puede poner después del nombre de variable en lugar de después de que el
tipo de variable, como en lo siguiente:

String niceChild[]; NiceChild cadena [];

To make arrays easier for humans to spot in your programs, you probably should stick to
one style rather than switching back and forth, though Java allows both styles of usage.
Para hacer arreglos más fácil para los seres humanos de ver en sus programas, que
probablemente deberá continuar con un estilo en vez de cambiar de ida y vuelta, a pesar de
Java permite a los estilos de uso.

The previous examples create arrays, but they do not store any values in them initially. Los
ejemplos anteriores crear matrices, pero no almacenan ningún valor en ellos inicialmente.
To do this, you must use the statement along with the variable type or store values in the
array within and marks. Para ello, debe utilizar la nueva declaración, junto con el tipo de
variable o almacenar valores en la matriz dentro de {y} marcas. You also must specify how
many different items will be stored in the array. También debe especificar el número de
elementos diferentes se almacenarán en la matriz. Each item in an array is called an
element. Cada elemento en una matriz se denomina elemento. The following statement
creates an array and sets aside space for the values that it will hold: La siguiente instrucción
crea una matriz y deja de lado un espacio para los valores que se llevará a cabo:

int[] elfSeniority = new int[250]; int] elfSeniority [=


new int [250];

This example creates an array of integers called . En este ejemplo se crea una matriz de
enteros llamado elfSeniority. The array has 250 elements in it that can be used to store
the number of months that each of Santa's elves has been employed at the Pole. La matriz
tiene 250 elementos en ella que se puede utilizar para almacenar el número de meses que
cada uno de los elfos de Santa Claus se ha empleado en el Polo. If the rumors are true and
Santa runs a union shop, this information is extremely important to keep track of. Si los
rumores son ciertos y Santa tiene una tienda de la unión, esta información es sumamente
importante no perder de vista.

When you create an array with the statement, you must specify the number of elements.
Cuando se crea una matriz con la nueva declaración, debe especificar el número de
elementos. Each element of the array is given an initial value when it is set up with ; the
value depends on the type of the array. Cada elemento de la matriz se le da un valor inicial
cuando se configura con los nuevos, el valor depende del tipo de la matriz. All numeric
arrays have the value , arrays have the value , and boolean arrays have the value . Todas
las matrices numéricas tienen el valor 0, matrices de caracteres tienen el valor '\ 0', y
las matrices booleanas tienen el valor falso. A array and all other objects are created with
the initial value of . Una matriz de cadenas y todos los demás objetos se crean con el valor
inicial de null.

For arrays that are not extremely large, you can set up their initial values at the same time
that you create them. Para los arreglos que no son extremadamente grandes, puede
configurar sus valores iniciales, al mismo tiempo que se crean. The following example
creates an array of strings and gives them initial values: En el ejemplo siguiente se crea una
matriz de cadenas y les da los valores iniciales:

String [reindeerNames] = {"Dasher", "Danzarín", "Prancer", "Vixen",


"Cometa", "Cupido", "Donner", "Blitzen"};

The information that should be put into elements of the array is put between and brackets,
and commas separate each element. La información que debe ser puesto en elementos de la
matriz se coloca entre corchetes {y}, y las comas separan cada elemento. The number of
elements in the array is not specified in the statement because it is set to the number of
elements in the comma-separated list. El número de elementos de la matriz no se especifica
en el pliego, ya que se establece en el número de elementos en la lista separada por comas.
Each element of the array in the list must be of the same type. Cada elemento de la matriz
en la lista deben ser del mismo tipo. The preceding example uses a string for each of the
reindeer names. El ejemplo anterior utiliza una cadena para cada uno de los nombres de los
renos.

Once the array is created, you cannot make more space and add another variable to the
array. Una vez que la matriz se crea, no se puede hacer más espacio y añade otra variable a
la matriz. Even if you recall the most famous reindeer of all, you couldn't add "Rudolph" as
the ninth element of the array. Incluso si usted recuerda el famoso reno sobre todo, no se
podría añadir "Rudolph" como elemento de sesiones de la matriz reindeerNames. The
compiler won't let poor Rudolph join in any . El compilador javac no permitirá que los
pobres Rudolph participar en cualquier reindeerNames.
Using Arrays Uso de matrices
You use arrays in a program as you would use any variable, except for the element number
in between the square brackets next to the array's name. Utilizar matrices en un programa
del mismo modo que cualquier variable, a excepción del número del elemento entre los
corchetes al lado del nombre de la matriz. Once you refer to the element number, you can
use an array element anywhere that a variable could be used. Una vez que se refieren al
número de elementos, puede utilizar un elemento de la matriz en cualquier lugar que una
variable podría ser utilizado. The following statements all use arrays that have been defined
already in this hour's examples: Las siguientes declaraciones uso de todas las matrices que
se han definido ya en los ejemplos de esta hora:

elfSeniority[193] += 1; elfSeniority [193] + = 1;


niceChild[94287612] = "Jonathan Bourne"; niceChild
[94287612] = "Jonathan Bourne";
if ( hostileAirTravelNations[currentNation] == true) si (]
hostileAirTravelNations [currentNation == true)
sendGiftByMail(); sendGiftByMail ();

An important thing to note about arrays is that the first element of an array is numbered 0
instead of 1. Una cosa importante tener en cuenta acerca de las matrices es que el primer
elemento de una matriz es el número 0 en vez de 1. This means that the highest number is
one less than you might expect. Esto significa que el número más alto es uno menos de lo
que cabría esperar. For example, consider the following statement: Por ejemplo, considere
la siguiente declaración:

String[] topGifts = new String[10]; String [] topGifts =


new String [10];

This statement creates an array of variables that are numbered from 0 to 9. Esta sentencia
crea una matriz de variables de cadena que están numerados del 0 al 9. If you referred to a
somewhere else in the program, you would get an error message like the following when
you run the program: Si usted se ha referido a una topGifts [10] en otro lugar en el
programa, usted recibirá un mensaje de error como el siguiente cuando se ejecuta el
programa:

java.lang.ArrayIndexOutOfBoundsException:
java.lang.ArrayIndexOutOfBoundsException:

at SantaGifts.main(SantaGifts.java:4); en SantaGifts.main
(SantaGifts.java: 4);
Like all of the error messages Java generates, this one's a bit hard to decipher. Al igual que
todos los mensajes de error de Java genera, este es un poco difícil de descifrar. The key
thing to note is the part that mentions an exception because exceptions are another word for
errors in Java programs. La clave a tener en cuenta es la parte que menciona una excepción
porque las excepciones son un sinónimo de errores en los programas de Java. This
exception is an "array out of bounds" error, which means that the array has gone beyond its
defined boundaries. Esta excepción es una "matriz fuera de los límites" de error, lo que
significa que la matriz ha ido más allá de sus límites definidos.

If you want to see what the upper limit of an array is during a program so that you can
avoid going beyond the limit, you can use a variable called that is associated with each
array that is created. Si quieres ver lo que el límite superior de una matriz es durante un
programa, para que pueda evitar ir más allá del límite, se puede utilizar una llama de
longitud variable que se asocia a cada matriz que se crea. The variable is an integer that
returns the number of elements that an array can hold. La longitud variable es un entero
que devuelve el número de elementos que puede contener una matriz. The following
example creates an array and then reports its length: En el ejemplo siguiente se crea una
matriz y luego informa de su longitud:

String[] reindeerNames = { "Dasher", "Dancer", "Prancer",


"Vixen", String [reindeerNames] = {"Dasher", "Danzarín",
"Prancer", "Vixen",
"Comet", "Cupid", "Donner", "Blitzen", "Rudolph" };
"Comet", "Cupido", "Donner", "Blitzen", "Rudolph"};
System.out.println("There are " + reindeerNames.length + "
reindeer."); System.out.println ("Hay" + +
reindeerNames.length "renos.");

In this example, the value of is 9, which means that the highest element number you can
specify is 8. En este ejemplo, el valor de reindeerNames.length es de 9, lo que significa
que el elemento número más alto se puede especificar es de 8.

Multidimensional Arrays Las matrices multidimensionales


The arrays you have been introduced to thus far in the hour all have one dimension; one
line of numbers ranging from 0 to the largest element number is used to refer to an array.
Los arreglos que se han introducido hasta ahora en la hora tienen una dimensión, una línea
de números que van del 0 al número más grande de elemento se utiliza para referirse a una
matriz. But some types of information require more dimensions to store adequately as
arrays. Sin embargo, algunos tipos de información que requieren más dimensiones para
almacenar adecuadamente como matrices. An example would be the (x,y) coordinate
system that's a staple of any math class. Un ejemplo sería el (x, y) el sistema de
coordenadas que es un elemento básico de cualquier clase de matemáticas. If you needed to
store a list of x and y coordinates that have a point marked on them, you could use a two-
dimensional array. Si usted necesita para almacenar una lista de coordenadas x e y que
tienen un punto marcado en ellos, puede utilizar una matriz de dos dimensiones. One
dimension of the array could store the x coordinate, and the other dimension could store the
y coordinate. Una dimensión de la matriz podría almacenar la coordenada x, y la otra
dimensión podría almacenar la coordenada.

To create an array that has two dimensions, you must use an additional set of square
brackets when creating and using the array. Para crear una matriz que tiene dos
dimensiones, debe utilizar un conjunto adicional de corchetes en la creación y el uso de la
matriz. Consider the following: Considere lo siguiente:

boolean[][] selectedPoint = new int[50][50]; Boolean []]


selectedPoint [= new int [50] [50];
selectedPoint[4][13] = true; selectedPoint [4] [13] =
true;
selectedPoint[7][6] = true; selectedPoint [7] [6] = true;
selectedPoint[11][22] = true; selectedPoint [11] [22] =
true;

This example creates an array of Boolean values called . En este ejemplo se crea una
matriz de valores booleanos llamado selectedPoint. The array has 50 elements in its first
dimension and 50 elements in its second dimension, so there are 2,500 individual array
elements that can hold values (50 multiplied by 50). La matriz cuenta con 50 elementos en
su primera dimensión y 50 elementos en su segunda dimensión, por lo que hay 2,500
elementos de la matriz individuales que pueden contener valores (50 multiplicado por 50).
When the array is created, each element is given the default value of . Cuando se crea la
matriz, cada elemento se le da el valor predeterminado de false. Three elements are then
given the value of : A point at the (x,y) position of (4,13), one at (7,6), and one at (11,22).
Tres elementos se da entonces el valor de verdad: Un punto en el (, x) la posición de
(4,13), de uno en uno (7,6), y uno al (11,22).

Arrays can have as many dimensions as you need, but keep in mind that they take up a lot
of memory if they're extremely large. Las matrices pueden tener tantas dimensiones como
usted necesita, pero ten en cuenta que ocupan mucha memoria si son muy grandes. Creating
the 50 by 50 array was equivalent to creating 2,500 individual variables. La creación de los
50 por el arsenal selectedPoint 50 fue equivalente a la creación de 2.500 variables
individuales.
Workshop: Array of Prizes Indeed Taller: Matriz de Premios hecho
Watch the syndicated game show Wheel of Fortune for any length of time and you'll be
surprised at how predictable the contestants are. Vea el sindicado demostración del juego
de la rueda de la fortuna para cualquier longitud de tiempo y usted se sorprenderá de lo
predecible de los concursantes son. In the years that this show has been one of the world's
most successful television programs, fortune seekers have worked the puzzle-solving
process into an exact science. En los años que este espectáculo ha sido uno de los
programas del mundo de la televisión de más éxito, buscadores de fortuna han trabajado el
proceso de resolución de enigmas en una ciencia exacta. Wheel contestants typically guess
the same letters when they are starting out on a puzzle: R, S, T, L, and N. In the final round,
when these letters and the vowel E are given to the players right away, they usually choose
four other letters: C, D, M, and the vowel O. The reason for this predictablity is that these
are the letters that appear most often in English words. participantes de la rueda suele
adivinar las letras mismo cuando se inician en un rompecabezas: R, S, T, L y N. En la
ronda final, cuando estas cartas y el correo vocal se dan a los jugadores de inmediato, por lo
general eligen otros cuatro letras: C, D, M, y la vocal O. La razón de esto predictablity es
que estas son las letras que aparecen con mayor frecuencia en las palabras Inglés. The
contestants are stifling their desire for spontaneity in order to better their chances to win a
trip to Bermuda, cash, and a Yamaha Waverunner. Los concursantes están sofocando su
deseo de espontaneidad en el fin de mejorar sus posibilidades de ganar un viaje a las
Bermudas, en efectivo, y una Yamaha Waverunner.

In case you're unfamiliar with the show, Wheel of Fortune is a game in which three
contestants try to guess the letters of a phrase, name, quote, or other memorable item. En
caso de que usted no está familiarizado con el espectáculo, Rueda de la Fortuna es un juego
en el que tres concursantes tratan de adivinar las letras de una frase, nombre, presupuesto, o
un elemento memorables. If they get a letter right and it's a consonant, they win the amount
of money they spun on a big wheel. Si consiguen un derecho escrito y es una consonante,
que ganar la cantidad de dinero que girar en una noria. To re-create the experience, play
hangman with some of your friends in front of a studio audience, hand out random amounts
of money when someone guesses a letter in the secret word or phrase, and give the winner a
new Ford Explorer. Para volver a crear la experiencia, el juego ahorcado con algunos de sus
amigos frente a una audiencia en el estudio, entregar cantidades de dinero al azar cuando
alguien adivina una letra en la palabra secreta o una frase, y dar al ganador un nuevo Ford
Explorer.

Your Java workshop during this hour will test the most-common-letter theory by looking at
as many different phrases and expressions as you care to type. Su taller de Java durante esta
hora pondrá a prueba la teoría más común letras mirando como muchas frases y
expresiones diferentes como quiera que escriba. An array will be used to count the number
of times that each letter appears. Una matriz se utiliza para contar el número de veces que
aparece cada letra. When you're done, the program will present each letter and the number
of times it appears in the phrases you entered. Cuando haya terminado, el programa
presentará cada letra y el número de veces que aparece en las frases que ha entrado. It also
will present some clues about which letters to avoid entirely unless you suspect that a
puzzle's answer is the Aztec priest-ruler Quetzalcoatl or the fire god Xiuhtecuhtle. También
se presentarán algunas pistas sobre la que las letras de evitar por completo a menos que
usted sospecha que la respuesta de un rompecabezas es el azteca Quetzalcóatl sacerdote-
gobernante o el dios del fuego Xiuhtecuhtle.

Open up a new file in your word processor and call it . Abra un archivo nuevo en su
procesador de textos y lo llaman Wheel.java. Enter Listing 9.1 and save the file when
you're done. Introduzca Listado 9.1 y guardar el archivo cuando haya terminado.

Listing 9.1. Listado 9.1. The full source code of Wheel.java. El código fuente completo de
Wheel.java.

1: class Wheel { 1: clase de ruedas {


2: public static void main(String arguments[]) { 2:
static public void principal (String argumentos []) {
3: String phrase[] = { 3: String frase [] = {
4: "A STITCH IN TIME SAVES NINE", 4: "Una puntada a
tiempo ahorra nueve",
5: "DON'T EAT YELLOW SNOW", 5: "No comas la nieve
amarilla",
6: "JUST DO IT", 6: "Just do it",
7: "EVERY GOOD BOY DOES FINE", 7: "CADA NIÑO BUENO HACE
BIEN",
8: "I WANT MY MTV", 8: "Quiero que mi MTV",
9: "HOW `BOUT THEM COWBOYS", 9: "COMO" LOS VAQUEROS
COMBATE ",
10: "PLAY IT AGAIN, SAM", 10: "Play It Again, Sam",
11: "FROSTY THE SNOWMAN", 11: "Frosty the Snowman",
12: "ONE MORE FOR THE ROAD", 12: "One More for the Road",
13: "HOME FIELD ADVANTAGE", 13: "VENTAJA DE JUGAR EN
CASA",
14: "VALENTINE'S DAY MASSACRE", 14: "DIA DE MASACRE DE SAN
VALENTÍN"
15: "GROVER CLEVELAND OHIO", 15: "Grover Cleveland, Ohio",
16: "WONDERFUL WORLD OF DISNEY", 16: "MARAVILLOSO MUNDO DE
DISNEY",
17: "COAL MINER'S DAUGHTER", 17: "LA HIJA DEL CARBÓN
MINER",
18: "WILL IT PLAY IN PEORIA" 18: "LO JUEGA EN PEORIA"
19: }; 19:};
20: int[] letterCount = new int[26]; 20: int] letterCount
[= new int [26];
21: for (int count = 0; count < phrase.length; count++) {
21: for (int cuenta = 0; phrase.length contador <; cuenta +
+) {
22: String current = phrase[count]; 22: String = frase
corriente [cuenta];
23: char[] letters = current.toCharArray(); 23: char [] =
current.toCharArray letras ();
24: for (int count2 = 0; count2 < letters.length; count2+
+) { 24: for (int count2 = 0; count2 <letters.length;
count2 + +) {
25: char lett = letters[count2]; 25: lett char = letras
[count2];
26: if ( (lett >= `A') & (lett < `Z') ) { 26: if ((> lett
= 'A') y (<lett `Z ')) {
27: letterCount[lett - `A']++; 27: lett [letterCount -
`Un']++;
28: } 28:}
29: } 29:}
30: } 30:}
31: for (char count = `A'; count <= `Z'; count++) { 31:
for (cuenta char = 'A'; contador <= "Z"; cuenta + +) {
32: System.out.print(count + ": " + 32: System.out.print
(cuenta + ":" +
33: letterCount[count - `A'] + +] A 33: letterCount
[cuenta - `'
34: "\t"); 34: "\ t");
35: } 35:}
36: System.out.println(); 36: System.out.println ();
37: } 37:}
38:}
After you compile the file and run it, the output should resemble Listing 9.2. Después de
compilar el archivo y ejecutarlo, la salida debe ser similar de venta 9.2.

Listing 9.2. Listado 9.2. The output of the Wheel program. La salida del programa de la
rueda.
A: 22 B: 3 C: 5 D: 13 E: 28 F: 6 G: 5 H: 8 I: 18 J: 1 K: 0
L: 13 M: 10 N: 19 O: 27 P: 3 Q: 0 R: 13 S: 15 T: 19 A: 22
B: 3 C: 5 D: 13 E: 28 F: 6 G: 5 H: 8 I: 18 J: 1 K: 0 L: 13
M: 10 N: 19 O: P 27: 3 Q: 0 R: 13 S: 15 T: 19 U: 4 V: 7 W: 9
X 0 Y: 10 Z: 0

The following things are taking place in the program: Los siguientes factores están
teniendo lugar en el programa de la rueda:

 Lines 1 and 2: The program and the block of the program begin. Las líneas 1 y 2: El
programa de la rueda y el () bloque principal del programa de empezar.
 Lines 3-19: Phrases are stored in a array called . Líneas 3-19: Las frases son almacenados
en una matriz de String llamado frase. Every phrase between the on Line 3 and the
on Line 19 will be stored in its own element of the array, beginning with in . Cada frase
entre el {en la Línea 3 y el} en la línea 19 se almacena en su propio elemento de la
matriz, comenzando con una puntada a tiempo ahorra nueve en la frase [0].
 Line 20: An integer array called is created with 26 elements. Línea 20: Una llamada matriz
letterCount entero se crea con 26 elementos. This array will be used to store the
number of times each letter appears. Esta matriz se utiliza para almacenar el número de
veces que aparece cada letra. The order of the elements is from A to Z. will store the
count for letter A, will store the count for B, and so on up to for Z. El orden de los
elementos es de la A a la Z. letterCount [0] almacenará el número por la letra A,
letterCount [1] para almacenar la cuenta B, y así sucesivamente hasta letterCount
[25] para la Z.
 Line 21: A loop is begun that cycles through the phrases stored in the array. Línea 21: Un
bucle se inicia que los ciclos a través de las frases almacenadas en la matriz de la frase.
The variable is used in the statement to end the loop after the last phrase is reached. La
variable phrase.length se utiliza en la declaración para poner fin al ciclo después de la
última frase que se llegó.
 Line 22: A variable named is created and set with the value of the current element of the
array. Línea 22: Una variable de cadena con nombre actual se crea y se establece con
el valor del elemento actual de la matriz frase.
 Line 23: A character array is created that stores all of the characters in the current phrase.
Línea 23: Una matriz de caracteres se crea que almacena todos los personajes en la frase
actual.
 Line 24: A loop is begun that cycles through the letters of the current phrase. Línea 24: Un
bucle se inicia que los ciclos a través de las letras de la frase actual. The variable is used to
end the loop after the last letter is reached. La variable letters.length se utiliza para
finalizar el bucle después de la última carta que se llegó.
 Line 25: A character variable called is created with the value of the current letter. Línea
25: Una variable llamada lett carácter se crea con el valor de la carta actual. In addition
to their text value, characters have a numeric value. Además de su valor de texto, los
personajes tienen un valor numérico. Because elements of an array are numbered, the
numeric value of each character will be used to determine its element number. Dado que
los elementos de un array están numerados, el valor numérico de cada personaje se
utilizará para determinar su número de elemento.
 Lines 26-28: An statement is used to weed out all characters that are not part of the
alphabet, such as punctuation and spaces. Líneas 26-28: Una sentencia if se utiliza para
eliminar todos los caracteres que no forman parte del alfabeto, como la puntuacion y
espacios. An element of the array is increased by 1 depending on the numeric value of the
current character, which is stored in . Un elemento de la matriz letterCount se
incrementa en 1 en función del valor numérico del carácter actual, que se almacena en
lett. The numeric values of the alphabet range from 65 for to 90 for . Los valores
numéricos de la gama de alfabeto de 65 años para 'A' a 90 para `Z '. Because the
array begins at 0 and ends at 25, (65) is subtracted from to determine which array
element to increase. Debido a que la matriz letterCount comienza en 0 y termina a las
25, `A '(65) se resta de lett para determinar qué elemento de la matriz para
aumentar.
 Line 29: One pass through the inner loop ends, and the loop returns to Line 24 to get the
next letter in the current phrase, if there is one. Línea 29: Un pase por el interior de los
extremos del lazo, y el ciclo vuelve a la línea 24 para obtener la siguiente letra en la frase
actual, si hay uno.
 Line 30: One pass through the outer loop ends, and the loop returns to Line 21 to get the
next phrase, if there is one. Línea 30: Un pase por el exterior con fines de bucle, y las
vueltas del lazo de la línea 21 para obtener la frase siguiente, si es que existe.
 Line 31: A loop is used to cycle through the alphabet from to . Línea 31: Un bucle for se
utiliza para desplazarse por el alfabeto de la 'A' a 'Z'.
 Lines 32-34: The current letter is displayed followed by a semicolon and the number of
times the letter appeared in the phrases stored in the array. Líneas 32-34: La carta actual
se muestra seguido de un punto y coma y el número de veces que la carta apareció en las
frases almacenadas en la matriz de la frase. The inserts a Tab character. El t inserta \
un carácter de tabulador.
 Line 35: One pass through the loop ends, and the loop returns to Line 31 to get the next
character in the alphabet, unless has been reached. Línea 35: Un paso a través de los
extremos de bucle, y las vueltas del lazo a la línea 31 para obtener el siguiente carácter en
el alfabeto, a menos que "Z" se ha alcanzado.
 Lines 36-38: A blank line is displayed, followed by the end of the program's block, and the
end of the program. Líneas 36-38: Una línea en blanco se muestra, seguido por el final de
() de bloque del programa principal, y el final del programa.

This workshop project shows how two nested loops can be used to cycle through a group
of phrases one letter at a time. Este proyecto de taller muestra cómo dos bucles for
anidados se puede utilizar para desplazarse por un grupo de frases de una carta a la vez.
Java attaches a numeric value to each character; this value is easier to use than the character
inside arrays. Java asigna un valor numérico a cada carácter, este valor es más fácil de usar
que el personaje dentro de las matrices. Using the variable makes it possible for you to add
as many phrases as desired within the and marks. Uso de la longitud variable permite
que usted agregue como frases que se desee dentro de la {y} marcas. The letters in each of
the new phrases that you add will be analyzed, and you can build up a better idea of what it
takes to make a small fortune in 30 minutes on television. Las letras en cada una de las
frases nuevas que se agregan se analizarán y se puede construir una mejor idea de lo que se
necesita para hacer una pequeña fortuna en 30 minutos en la televisión.
Summary Resumen
Arrays make it possible to store complicated types of information in a program and
manipulate that information. Las matrices permiten almacenar tipos complicados de la
información en un programa y manipular esa información. They're ideal for anything that
can be arranged in a list and can be accessed easily using the loop statements that you
learned about during Hour 8, "Repeating an Action with Loops." Son ideales para cualquier
cosa que se puede organizar en una lista y se puede acceder fácilmente con las
declaraciones del lazo que aprendieron durante 8 horas, "Repetición de una acción con
lazos."

The information processing needs of Santa Claus possibly have outgrown arrays. El
tratamiento de la información debe de Santa Claus posiblemente ya no caben en las
matrices. There are more children being manufactured each year, and the gifts they want
are increasing in complexity and expense. Hay más niños que se fabrican cada año, y los
regalos que quieres están aumentando en complejidad y costo. Tickle Me Elmo alone
created a logistical nightmare for him in Christmas 1996. Tickle Me Elmo sólo creó una
pesadilla logística para él en la Navidad de 1996. Your programs are likely to use arrays to
store information that is unwieldy to work with through variables, even if you're not
making any lists or checking them twice. Sus programas son susceptibles de utilizar
matrices para almacenar información que es difícil de manejar para trabajar a través de
variables, incluso si usted no está haciendo ninguna lista o control dos veces.

Q&A Q & A
Q Do arrays have to begin with an element 0, or could they range from a higher
minimum number to a higher maximum number, such as 65 to 90? Q ¿matrices tienen
que comenzar con un elemento 0, o podrían ir desde un mínimo número superior a un
número máximo superior, como 65 a 90?

A No, but it is more efficient to do so because it takes up less memory in the computer to
store arrays that begin with 0. R No, pero es más eficiente para hacerlo porque tiene
menos memoria en el ordenador para almacenar las matrices que empiezan con 0. You
can use arrays of a higher index number simply by referring to the numbers you want to
use. Usted puede utilizar matrices de un número de índice superior simplemente haciendo
referencia a los números que desea utilizar. For example, if you created a loop that cycled
from array element 65 to element 90, you could disregard any other element numbers.
Por ejemplo, si ha creado un bucle que un ciclo de elemento de matriz de 65 a 90
elementos, que podía pasar por alto los números de otro elemento. However, there still
will be array elements numbered from 0 to 64 taking up space in memory, even if you
don't use them for anything. Sin embargo, todavía habrá elementos de la matriz
numeradas 0-64 ocupando espacio en la memoria, incluso si usted no los usa para
cualquier cosa.

Q Why are some errors called exceptions? Q ¿Por qué algunos errores llamado
excepciones?
A The significance of the term is that a program normally runs without any problems, and
the exception signals an exceptional circumstance that must be dealt with. A la
importancia de la expresión es que un programa se ejecuta normalmente sin ningún
problema, y la excepción de las señales de una circunstancia excepcional que debe ser
tratado. Exceptions are warning messages that are sent from within a Java program. Las
excepciones son los mensajes de advertencia que se envían desde un programa Java.

Q Can the length variable be set to increase or decrease the size of an array after it has
been Q ¿Puede la longitud variable se establece en aumentar o disminuir el tamaño de
una matriz después de haber sido
created? creado?

A There's no way to modify the size of an array after it has been created; is strictly used to
find out an array's upper boundary. A No hay manera de modificar el tamaño de una
matriz después de haber sido creada, la longitud es estrictamente utilizado para
determinar el límite superior de una matriz.

Quiz Quiz
If the brain were an array, you could test its by answering each of the following questions
about arrays. Si el cerebro fuera una matriz, podría poner a prueba su longitud,
respondiendo a cada una de las siguientes preguntas acerca de las matrices.

Questions Preguntas

1. What types of information are arrays best suited for? 1. ¿Qué tipo de información son
las matrices más adecuado?

(a) Lists (A) Las listas


(b) Pairs of related information (B) Los pares de la información relacionada
(c) Trivia (C) Trivia

2. What variable can be used to check the upper boundary of an array? 2. ¿Qué variables
se pueden utilizar para comprobar el límite superior de una matriz?

(a) (A) arriba


(b) (B) la longitud
(c) (C) limitar

3. Who is the famous Aztec priest-ruler? 3. ¿Quién es el famoso sacerdote-gobernante


azteca?

(a) Quisp (A) Quisp


(b) Quetzalcoatl (B) Quetzalcóatl
(c) Quichelorraine (C) Quichelorraine
Answers Respuestas

1. a. 1. A. Lists that contain nothing but the same type of information--strings, numbers,
and so on--are well-suited for storage in arrays. Las listas que contienen nada más que el
mismo tipo de información - cadenas, números, y así sucesivamente - son muy adecuados
para el almacenamiento en matrices.

2. b. 2. B.

3. b. 3. B. It's also the name of a god of learning and civilization who is depicted as an
approaching storm whose winds kick up dust before the rain comes. Es también el nombre
de un dios de aprendizaje y de la civilización que se representa como una tormenta cuyos
vientos levantan el polvo antes de la lluvia viene.

Activities Actividades
To give yourself an array of experiences to draw from later on, you can expand your
knowledge of this hour's topics with the following activities: Para darse una serie de
experiencias para sacar de más adelante, usted puede ampliar su conocimiento de temas de
esta hora con las siguientes actividades:

 Create a program that uses a multidimensional array to store student grades. Crear un
programa que utiliza una matriz multidimensional para almacenar las calificaciones del
estudiante. The first dimension should be a number for each student, and the second
dimension should be for each student's grades. La primera dimensión debe ser un número
para cada estudiante, y la segunda dimensión debe ser para los grados de cada estudiante.
Display the average of all the grades earned by each student and an overall average for
every student. Muestra el promedio de todas las calificaciones obtenidas por cada alumno
y un promedio general de cada estudiante.
 Write a program that stores the first 400 prime numbers in an array. Escriba un programa
que almacena los primeros 400 números primos en una matriz.

 10 horas
o Creación de su primer objetivo
 ¿Cómo Programación orientada a objetos de Obras
 Los objetos en Acción
 ¿Qué objetos son
 Comprender la herencia
 Construcción de una jerarquía de herencia
 Taller: Creación de un objeto
 Listado de 10.1. El texto completo de Mammal.java.
 Listado de 10.2. El texto completo de Dog.java.
 Listado de 10.3. El texto completo de MorleySafer.java.
 Listado de 10.4. El texto completo de Speak.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 10 10 horas

Creating Your First Object Creación de su primer


objetivo

One of the more fearsome items of jargon that you'll encounter during these 24 hours is
object-oriented programming. Uno de los artículos más temibles de la jerga que usted va a
encontrar durante estas 24 horas es la programación orientada a objetos. This is a
complicated term for an elegant way of describing what a computer program is and how it
works. Este es un término complicado de una manera elegante de describir lo que un
programa de ordenador es y cómo funciona. Before object-oriented programming,
computer programs were usually described under the simplest definition you've learned in
this book: sets of instructions that are listed in a file and handled in some kind of reliable
order. Antes de la programación orientada a objetos, los programas de ordenador se
describe generalmente bajo la definición más simple que has aprendido en este libro:
conjuntos de instrucciones que se enumeran en un archivo y manipulados en una especie de
orden fiable. Whether the program is big or small, the programmer's job is largely the
same--write instructions for each thing the computer must do. Si el programa es grande o
pequeño, el trabajo del programador es básicamente el mismo - escribe las instrucciones
para cada cosa que el equipo debe hacer. By thinking of a program as a collection of objects
instead, you can figure out the tasks a program must accomplish and assign the tasks to the
objects where they belong best. Al pensar en un programa como una colección de objetos
en su lugar, usted puede averiguar las tareas de un programa debe cumplir con las tareas y
asignar a los objetos donde deben estar los mejores.

During this hour, the following topics will be covered: Durante esta hora, los siguientes
temas serán cubiertos:

 Understanding objects Comprender los objetos


 How attributes describe an object ¿Cómo describir los atributos de un objeto
 What determines how objects behave Lo que determina cómo los objetos se comportan
 Combining objects Combinación de objetos
 Inheriting from other objects Herencia de otros objetos
 Creating an object Creación de un objeto
How Object-Oriented Programming Works ¿Cómo Programación orientada a objetos de
Obras
The programs that you create with Java can be thought of as objects just like any other
objects in the world, such as nails, skateboards, Liquid Paper, glue, or 60 Minutes cohost
Morley Safer. Los programas que se crean con Java puede ser considerada como objetos al
igual que cualquier otro objeto en el mundo, tales como clavos, monopatines, Liquid Paper,
pegamento, o 60 minutos co-anfitrión Morley Safer. An object is made up of smaller
objects--in the case of Mr. Safer, two legs, two arms, a torso, a head, and a reporter's
notebook. Un objeto se compone de objetos más pequeños - en el caso del Sr. Segura, dos
piernas, dos brazos, un torso, una cabeza, y una libreta de reportero. Each object has things
that make it different from other objects. Cada objeto tiene cosas que la hacen diferente de
otros objetos. Morley's legs are long and angular; they bend in the middle and end in feet.
Morley piernas son largas y angulares, se doblan en la mitad y al final en los pies. His arms
end in hands and are shorter than the legs. Su fin en las manos y los brazos son más cortos
que las piernas. Each object also has specific jobs it has to do. Cada objeto tiene también
trabajos específicos que tiene que hacer. Morley's legs are used for movement and support,
and his arms are used to grab things, take notes, and hail taxicabs. las piernas de Morley se
utilizan para el movimiento y apoyo, y sus brazos se utilizan para agarrar cosas, tomar
notas, y los taxis granizo. If you break down computer programs in the same way that you
have broken down Morley Safer, you are engaging in object-oriented programming. Si
usted analiza los programas de ordenador de la misma manera que se han roto Morley
Safer, que están participando en la programación orientada a objetos. It's a much less
complicated concept than it originally sounds. Es un concepto mucho menos complicado de
lo que inicialmente parece.

In object-oriented programming, an object contains two things: attributes and behavior. En


la programación orientada a objetos, un objeto contiene dos cosas: los atributos y el
comportamiento. Attributes are things that describe the object and show how it is different
from other objects. Los atributos son las cosas que describen el objeto y mostrar en qué se
diferencia de otros objetos. Behavior is what an object does. La conducta es lo que un
objeto no.

You create objects in Java by using a class as a template. Puede crear objetos en Java
utilizando una clase como una plantilla. The class is a master copy of the object that is
consulted to determine which attributes and behavior an object should have. La clase es una
copia maestra del objeto que se consulta para determinar qué atributos y el comportamiento
de un objeto debe tener. The term class should be familiar to you because every Java
program that you have written thus far has been called a class. La clase plazo debería ser
familiar para usted, porque todos los programas de Java que he escrito hasta ahora se ha
llamado una clase. Every program that you create with Java will be a class because each
one could be used as a template for the creation of new objects. Cada programa que se crea
con Java será una clase porque cada uno podría ser utilizado como una plantilla para la
creación de nuevos objetos. As an example, any Java program that uses strings is using the
class. A modo de ejemplo, cualquier programa de Java que utiliza cadenas está utilizando la
clase String. This class contains attributes that determine what a object is and behavior
that controls what objects can do. Esta clase contiene los atributos que determinan lo que
es un objeto String y el comportamiento que controla lo que los objetos String puede
hacer.

With object-oriented programming, any computer program is a group of objects that work
together to get something done. Con la programación orientada a objetos, cualquier
programa de computadora es un grupo de objetos que trabajan juntos para hacer algo. Some
simple programs may seem as though they consist of only one object--the class file.
Algunos programas de simple puede parecer que sólo consisten en un objeto - el archivo de
clase. However, even those programs are using other objects to get their work done. Sin
embargo, incluso los programas están utilizando otros objetos para hacer su trabajo.

Objects in Action Los objetos en Acción


Consider the case of a dice-rolling program. Consideremos el caso de un programa de
dados del balanceo. Rolling a six-sided die is a simple thing to do in the real world--you
toss a cube and check the uppermost side of the cube when it stops rolling. Lanzar un dado
de seis caras es una cosa fácil de hacer en el mundo real - que tirar un cubo y compruebe la
parte superior del cubo cuando se deja de rodar. When you make a computer do the same
thing, you can think of the die as an object. Al hacer que un equipo haga lo mismo, puede
pensar en la muerte como un objeto. In fact, during Hour 21, "Playing Games with Java,"
you will be using a object as you teach the computer to play the dice-rolling game called
craps. De hecho, durante la hora 21, "Jugando con Java", que va a utilizar un dado objeto a
medida que enseñar a la computadora para jugar el juego de los dados de laminación
llamado dados.

A object could consist of the following: Un objeto de morir podría consistir en lo


siguiente:

 A behavior to roll the die and figure out the result Un comportamiento a tirar el dado y
averiguar el resultado de la
 An attribute to store the result of a die roll Un atributo para almacenar el resultado de una
tirada

When you compare a six-sided die in the real world to a object in a computer program, it
might seem odd to ask the object to roll itself. Cuando se compara un dado de seis caras en
el mundo real de morir de un objeto en un programa de ordenador, puede parecer extraño
para pedir al morir objeto a sí mismo rollo. Dice don't roll themselves in the real world.
Dice no se despliegue en el mundo real. However, objects in object-oriented programming
work for themselves whenever possible. Sin embargo, los objetos en el trabajo de
programación orientado a objetos por sí mismos siempre que sea posible. This quality
makes them more useful because you can incorporate them in other programs without
having as many things to teach them. Esta cualidad los hace más útiles porque se pueden
incorporar en otros programas sin tener tantas cosas para enseñar. If a object did not know
how to roll itself, for instance, every time you used that object somewhere you would have
to create behavior to roll it. Si un objeto de morir no sabía a sí mismo rollo, por ejemplo,
cada vez que se utiliza que morir en algún objeto que tendría que crear un comportamiento
a rodar.

For another example of object-oriented programming, consider the autodialer program that
Matthew Broderick's character used in WarGames to find computers he could hack into.
Para otro ejemplo de la programación orientada a objetos, considere el programa de
marcador automático de caracteres que Matthew Broderick se utiliza en Juegos de guerra
para encontrar equipos que podrían introducirse en. If you're unfamiliar with the term, an
autodialer is software that uses a modem to dial a series of phone numbers in sequence. Si
no está familiarizado con el término, un marcador automático es un software que utiliza un
módem para marcar una serie de números de teléfono en secuencia. The purpose of such a
program is to find other computers that answer their own phone, so you can call them up
later to see what they are. El propósito de este programa es encontrar otros equipos que
responden a su propio teléfono, por lo que se les puede llamar más tarde para ver lo que
son.

Using an autodialer today practically guarantees you'll be on a first-name basis with your
local phone company. El uso de un marcador automático hoy prácticamente le garantiza
que será por orden de nombre-con su compañía telefónica local. In the early '80s, it was a
good way to be rebellious without actually leaving the house. En los años 80, era una buena
manera de ser rebelde sin tener que salir de la casa. David Lightman (Broderick) used his
autodialer to look for a videogame company's private computer system. David Lightman
(Broderick) utilizó su marcador automático de mirar para el sistema de una compañía de
videojuegos de ordenador privado. He wanted to play the new game they were working on.
Él quería jugar el nuevo juego que estaban trabajando. Instead, Lightman found a secret
government computer that could play everything from chess to Global Thermonuclear War.
En cambio, Lightman que se encuentran una computadora del gobierno secreto que podría
jugar de todo, desde el ajedrez a la Segunda Guerra Mundial termonuclear.

An autodialer, like any computer program, can be thought of as a group of objects that
work together. Un marcador automático, como cualquier programa de ordenador, se puede
considerar como un grupo de objetos que trabajan juntos. It could be broken down into the
following: Podría dividirse en las siguientes:
 A object, which knows how to make the modem dial a number and how to report when
another computer system has answered a call Un objeto de módem, que sabe cómo hacer
que el módem marque un número y cómo informar al otro sistema informático ha
respondido a una llamada
 A object, which keeps track of what numbers were called and which ones were successful
and can save this information for inspection later Un objeto de Monitor, que realiza un
seguimiento de qué números se llama y cuales fueron exitosos y se puede guardar esta
información para una inspección posterior

Each object exists independently of the other. Cada objeto existe independientemente de los
demás. The object does its job without requiring any help from the object. El objeto del
módem hace su trabajo sin necesidad de ninguna ayuda del objeto Monitor.

One of the advantages of having a completely independent object is that it could be used in
other programs that need modem functionality. Una de las ventajas de tener un módem
objeto independiente por completo es que podría ser utilizado en otros programas que
necesitan funcionalidad de módem. If Broderick's character returns to hacking in
WarGames 1997 after a bitter divorce from Ally Sheedy's character, he could use the
object as part of an elaborate ATM fraud scheme. Si el personaje vuelve Broderick Juegos
de guerra a la piratería en 1997, tras un amargo divorcio de Sheedy el personaje de Ally,
que podía utilizar el objeto módem como parte de un esquema de fraude de cajeros
automáticos más detalles.

Another reason to use self-contained programs such as objects is that they are easier to
debug. Otra razón para el uso autónomo de programas tales como los objetos es que son
más fáciles de depurar. Computer programs quickly become unwieldy in size. Los
programas de ordenador se convierten rápidamente en un tamaño difícil de manejar. If your
program is just one big list of instructions, you can't change one part without making sure it
won't damage the performance of other parts that are dependent on it. Si su programa es
sólo una gran lista de instrucciones, no se puede cambiar una parte sin asegurarse de que no
dañará el desempeño de otras partes que dependen de ella. If you're debugging something
like a object, though, you know it's not dependent on anything else. Si usted es algo así
como la depuración de un objeto de módem, sin embargo, usted sabe que no es dependiente
de ninguna otra cosa. You can focus on making sure the object does the job it's supposed to
do and holds the information that it needs to do its job. Puede concentrarse en hacer que el
objeto del módem hace el trabajo que tiene que hacer y tiene la información que necesita
para hacer su trabajo.

For these reasons, object-oriented programming is becoming the norm in many areas of
software development. Por estas razones, la programación orientada a objetos se está
convirtiendo en la norma en muchas áreas de desarrollo de software. Learning an object-
oriented language like Java as your first programming language can be an advantage in
some ways because you're not unlearning the habits of other styles of programming.
Aprender un lenguaje orientado a objetos como Java como su primer lenguaje de
programación puede ser una ventaja en algunos aspectos, porque no estás desaprender los
hábitos de otros estilos de programación. The main disadvantage is that an object-oriented
language can be more challenging to learn than a non-object-oriented language such as
Visual Basic. La principal desventaja es que un lenguaje orientado a objetos puede ser más
difícil de aprender que un idioma no orientado a objetos como Visual Basic.

What Objects Are ¿Qué objetos son


As stated, objects are created by using a class of objects as a guideline. Como se ha
indicado, los objetos se crean mediante una clase de objetos como una guía. The following
is an example of a class: El siguiente es un ejemplo de una clase:

public class Dog { public class Perro {


} }

Any object created from this class can't do anything because it doesn't have any attributes
or behavior yet. Cualquier objeto creado a partir de esta clase no puede hacer nada porque
no tiene los atributos o comportamiento todavía. You need to add those or this class that
won't be terribly useful. Usted necesita agregar los o esta clase que no será terriblemente
útil. You could expand the class into the following: Se podría ampliar la clase en el texto
siguiente:

public class Dog { public class Perro {


String name; String nombre;

public void speak() { public void habla () {


System.out.println("Arf! Arf!");
System.out.println ("Arf Arf!");
} }
} }

The class now should be recognizable to you because it looks a lot like the programs you
have written during Hours 1 through 9. La clase de perro ahora se dará a conocer a usted
porque se parece mucho a los programas que ha escrito durante las horas del 1 al 9. The
class begins with a statement, as your programs have, except that it has a statement
alongside it. La clase Perro comienza con una declaración de clase, ya que sus
programas tienen, excepto que tiene una declaración pública junto a él. The statement
means that the class is available for use by the public--in other words, by any program that
wants to use objects. La declaración pública significa que la clase está disponible para su
uso por el público - en otras palabras, cualquier programa que quiere usar los objetos para
perros.

The first part of the class creates a string variable called . La primera parte de la clase
Perro crea una variable llamada nombre de la cadena. This variable is an attribute of the
object; the name is one of the things that distinguishes a dog from other dogs. Esta variable
es un atributo del objeto, el nombre es una de las cosas que distingue a un perro de otros
perros. The second part of the class is a method called . La segunda parte de la clase de
perro es un método llamado hablar (). This method has one statement, a statement that
displays the text, Este método tiene una declaración, un System.out.println () que
muestra el texto, Arf! Arf!

If you wanted to use a object in a program, you would create the object much like you
would create a variable. Si desea utilizar un objeto de perros en un programa, debe crear el
objeto al igual que se crearía una variable. You could use the following statement: Usted
podría utilizar la siguiente declaración:

Dog firstDog = new Dog(); Perro firstDog = new Perro ();

This statement creates a object called . Esta sentencia crea un objeto perro llamado
firstDog. You can now use the object in the program; you can set its variables and call its
methods. Ahora puede usar el objeto en el programa, usted puede establecer sus variables y
llamar a sus métodos. To set the value of the variable of the object, you could use the
following statement: Para establecer el valor de la variable de nombre del objeto
firstDog, podría utilizar la siguiente declaración:

firstDog.name = "Checkers"; firstDog.name = "Damas";

To make this dog speak by calling the method, you could use the following code: Para
hacer este perro hablar llamando al hablar () método, puede utilizar el código siguiente:

firstDog.speak(); firstDog.speak ();

Like a well-trained pet, the object would respond to this statement by displaying the text,
Como un capacitados para mascotas, así, el objeto del perro responda a esta declaración,
mostrando el texto, Arf! Arf!

Understanding Inheritance Comprender la herencia


The final selling point to object-oriented programming is called inheritance. El punto de
venta final a la programación orientada a objetos se denomina herencia. Inheritance is the
way one object can inherit behavior and attributes from other objects that are similar to it.
La herencia es la forma de un objeto puede heredar el comportamiento y los atributos de
otros objetos que son similares a ella.

When you start creating objects for use in other programs, you will find that some new
objects you want are a lot like other objects that have already been developed. Cuando se
inicia la creación de objetos para su uso en otros programas, usted encontrará que algunos
objetos nuevos que desea se parecen mucho a otros objetos que ya se han desarrollado. For
example, if David Lightman does not run afoul of the law because of his ATM scheme, he
might want to create an object that can handle error correction and other advanced modem
features that weren't around back in 1983 when WarGames was released. Por ejemplo, si
David Lightman no ir en contra de la ley debido a su sistema de cajero automático, que
puede ser que desee crear un objeto que puede controlar la corrección de errores y otras
características avanzadas del módem que no estaban alrededor de la espalda en 1983,
cuando fue puesto en libertad Juegos de guerra.

Lightman could create a new object by copying the statements of the object and revising
them. Lightman podría crear un nuevo objeto ErrorCorrectionModem reproduce creando
copias de las declaraciones del objeto de módem y su revisión. However, if most of the
behavior and attributes of are the same as those of , this is a lot of unnecessary work. Sin
embargo, si la mayor parte del comportamiento y los atributos de ErrorCorrectionModem
son las mismas que las de módem, se trata de una gran cantidad de trabajo innecesario. It
also means that Lightman will have to maintain two separate programs if something needs
to be changed or debugged later on. También significa que Lightman tendrá que mantener
dos programas por separado si algo necesita ser cambiado o eliminado errores más
adelante. Through inheritance, a programmer can create a new class of objects by defining
only how it is different from an existing class. A través de la herencia, un programador
puede crear una nueva clase de objetos mediante la definición sólo en qué se diferencia de
una clase existente. Lightman could make inherit from , and all he would have to write are
the things that make error-correction modems different than previous modems. Lightman
puede hacer ErrorCorrectionModem heredar de módem, y todo lo que tendría que escribir
son las cosas que hacen que la corrección de los módems de error diferente a los módems
anteriores.

The way that a class of objects inherits from another class is through the statement. La
forma en que una clase de objetos hereda de otra clase se extiende a través de la
declaración. The following is a skeleton of an class that inherits from the class: El
siguiente es un esqueleto de una clase ErrorCorrectionModem que hereda de la clase del
módem:

class ErrorCorrectionModem extends Modem { clase


ErrorCorrectionModem extiende módem {
// program goes here / / Aquí va el programa

} }

Building an Inheritance Hierarchy Construcción de una jerarquía de herencia


Inheritance enables a variety of related classes to be developed without a lot of redundant
work. La herencia permite una variedad de clases relacionadas que se desarrolle sin mucho
trabajo redundante. Inheritance can be passed down from one class to another class to
another class. La herencia puede ser transmitido de una clase a otra clase a otra clase. This
system of classes is called a class hierarchy, and all of the standard classes that you can use
in your Java programs are part of a hierarchy. Este sistema de clases que se llama una
jerarquía de clases, y todas las clases estándar que puede utilizar en sus programas Java son
parte de una jerarquía.

Understanding a hierarchy is easier if you understand what subclasses and superclasses are.
Entender la jerarquía es más fácil si usted entiende lo que subclases y superclases son. A
class that inherits from another class is called a subclass, and the class that it is inherited
from is called a superclass. Una clase que hereda de otra clase que se llama una subclase, y
la clase que se hereda se denomina superclase. In the preceding WarGames example, the
class is the superclass of the class, and is the subclass of . Juegos de guerra en el ejemplo
anterior, la clase del módem es la superclase de la clase ErrorCorrectionModem y
ErrorCorrectionModem es la subclase de módem. A class can have more than one class
that inherits from it in the hierarchy--another subclass of might be , for example, if ISDN
modems have behavior or attributes that make them different from error-correcting
modems. Una clase puede tener más de una clase que hereda de él en la jerarquía - otra
subclase de módem puede ser ISDNModem, por ejemplo, si los módems RDSI tienen un
comportamiento o los atributos que los hacen diferentes de módems de corrección de
errores. If there were a subclass of , such as , it would inherit from all the classes above
it--both and . Si hubiera una subclase de ErrorCorrectionModem, como
InternalErrorCorrectionModem, que heredaría de todas las clases por encima de ella -
tanto ErrorCorrectionModem y módem.

The programs that you write as you are learning about Java won't use complicated class
hierarchies. Los programas que se escribe a medida que están aprendiendo acerca de Java
no va a usar complicados jerarquías de clases. However, the classes that are part of the
standard Java language make full use of inheritance. Sin embargo, las clases que forman
parte del estándar Java hacer un uso completo de la herencia. Understanding it is essential
to making the most of the classes that come with Java. Entendiendo que es esencial para
sacar el máximo partido de las clases que vienen con Java. You'll learn more about
inheritance during Hour 12, "Inheriting Methods from Other Classes." Usted aprenderá más
sobre la herencia durante la hora 12, "La herencia de los métodos de otras clases."

Workshop: Creating an Object Taller: Creación de un objeto


To see a working example of classes and inheritance, you will create classes that represent
two types of objects: dogs and Morley Safer. Para ver un ejemplo práctico de las clases y
herencia, va a crear clases que representan dos tipos de objetos: los perros y más segura
Morley. For the sake of simplicity, the workshop will focus on a few simple attributes and
behavior for these objects: En aras de la simplicidad, el taller se centrará en unos pocos
atributos simples y el comportamiento de estos objetos:

1. 1. 1. Each object should have a name and be able to remember it. Cada objeto debe tener
un nombre y ser capaz de recordar.
2. 2. 2. Each object should snore when it sleeps. Cada objeto debe ronca cuando duerme.

1. 3. 3. Each object should speak in an accurate way. Cada objeto debe hablar de una manera
precisa. Although dogs and Morley Safer can remember their own names and snore in the
same manner, they do not speak in the same manner. Aunque los perros y más segura
Morley puede recordar su propio nombre y el ronquido de la misma manera, no hablan de
la misma manera.

The first two things are shared in common between dogs and Morley Safer. Las dos
primeras cosas que se comparten en común entre los perros y más segura Morley. Because
of this, you can create a superclass that both the class and the class can inherit from.
Debido a esto, puede crear una superclase que tanto la clase Perro y la clase puede heredar
de MorleySafer. Call this class . Llame a esta clase de mamíferos. Using your word
processor, create a new file and save it as . Utilizando el procesador de textos, crear un
nuevo archivo y guardarlo como Mammal.java. Enter Listing 10.1 and save the file.
Introduzca Listado 10.1 y guardar el archivo.

Listing 10.1. Listado de 10.1. The full text of Mammal.java. El texto completo de
Mammal.java.

1: public class Mammal { 1: public class Mamífero {


2: String name; 2: String nombre;
3: 3:
4: public void sleep() { 4: public void sleep () {
5: System.out.println("ZZZZ ZZZZZZ ZZZZ"); 5:
System.out.println ("ZZZZ ZZZZ ZZZZZZ");
6: } 6:}
7:}
Compile this file with the compiler tool to produce a file called . Compilar este archivo
con la herramienta del compilador javac para producir un archivo llamado Mammal.class.
Although you cannot run this program with the interpreter, you will be able to use it in
other classes. Aunque no se puede ejecutar este programa con el intérprete, que será capaz
de utilizarlo en otras clases. You now have a class that can handle both of the things that
the and class have in common. Ahora tiene una clase de mamíferos que pueden manejar
las dos cosas que el perro y la clase MorleySafer tienen en común. By using the
statement when you are creating the and classes, you can make each of them a subclass of
. Mediante el uso de la declaración se extiende cuando se crea el perro y las clases
MorleySafer, usted puede hacer cada uno de ellos una subclase de mamíferos.

Start a new file in your word processor and save it as . Iniciar un nuevo archivo en el
procesador de texto y guardarlo como Dog.java. Enter Listing 10.2, and then save and
compile the file. Introduzca listado 10.2, a continuación, guarde y compile el archivo.

Listing 10.2. Listado de 10.2. The full text of Dog.java. El texto completo de Dog.java.

1: public class Dog extends Mammal { 1: public class Perro


extends Mammal {
2: public void speak() { 2: public void habla () {
3: System.out.println("Arf! Arf!"); 3: System.out.println
("Arf Arf!");
4: } 4:}
5:}

Create a third file with your word processor, and save it as . Cree un tercer archivo con su
procesador de texto, y guardarlo como MorleySafer.java. Enter Listing 10.3, and then
save and compile the file when you're done. Introduzca Listado 10.3, a continuación,
guarde y compile el archivo cuando haya terminado.

Listing 10.3. Listado de 10.3. The full text of MorleySafer.java. El texto completo de
MorleySafer.java.

1: public class MorleySafer extends Mammal { 1: public


class MorleySafer extiende Mamíferos {
2: public void speak() { 2: public void habla () {
3: System.out.println("Can I ask you a few questions about
your 1987 tax statement?"); 3: System.out.println ("¿Puedo
hacerle algunas preguntas acerca de su declaración de
impuestos de 1987?");
4: } 4:}
5:}

Once you have compiled all three of these files with the compiler tool, you will have three
class files: , , and . Una vez que haya recopilado todos los tres de estos archivos con la
herramienta del compilador javac, que contará con tres archivos de clase: Mammal.class,
Dog.class y MorleySafer.class. However, you cannot run any of these class files at the
command line with the interpreter tool because they do not have blocks. Sin embargo, no
se puede ejecutar cualquiera de estos archivos de clase en la línea de comandos con la
herramienta intérprete de Java, ya que no tiene main () bloques. You need to create a
short Java program to test out the class hierarchy you have just built. Es necesario crear un
corto programa Java para probar la jerarquía de clases que acaba de construir. Return to
your word processor and create a new file called . Regreso a su procesador de textos y
crear un nuevo archivo llamado Speak.java. Enter Listing 10.4. Introduzca Listado 10.4.

Listing 10.4. Listado de 10.4. The full text of Speak.java. El texto completo de Speak.java.

1: class Speak { 1: Habla la clase {


2: public static void main(String arguments[]) { 2:
static public void principal (String argumentos []) {
3: Dog doggie = new Dog(); 3: perrito perro = new Perro
();
4: MorleySafer morley = new MorleySafer(); 4: morley
MorleySafer nueva MorleySafer = ();
5: doggie.name = "Cujo"; 5: doggie.name = "Cujo";
6: morley.name = "Morley Safer"; 6: morley.name = "Morley
Safer";
7: System.out.println("First we'll get the dog to
speak:"); 7: System.out.println ("Primero vamos a conseguir
que el perro a hablar:");
8: doggie.speak(); 8: doggie.speak ();
9: System.out.println("Now it's Morley's turn to
speak:"); 9: System.out.println ("Ahora es el turno de
Morley a hablar:");
10: morley.speak(); 10: morley.speak ();
11: System.out.println("Time for both to sleep:"); 11:
System.out.println ("El tiempo para dormir:");
12: doggie.sleep(); 12: doggie.sleep ();
13: morley.sleep(); 13: morley.sleep ();
14: } 14:}
15:}

Save and compile the file when you're done. Guarde y compile el archivo cuando haya
terminado. When you run it, the output should resemble the following: Cuando se ejecuta,
la salida debe ser similar a lo siguiente:

First we'll get the dog to speak: En primer lugar vamos a


conseguir que el perro a hablar:
Arf! Arf! Arf! Arf!
Now it's Morley's turn to speak: Ahora es el turno de
Morley a hablar:
Can I ask you a few questions about your 1987 tax
statement? ¿Puedo preguntarle algunas preguntas acerca de
su declaración de impuestos de 1987?
Time for both to sleep: Tiempo para dormir:
ZZZZ ZZZZZZ ZZZZ ZZZZ ZZZZ ZZZZZZ
ZZZZ ZZZZZZ ZZZZ ZZZZ ZZZZ ZZZZZZ

Note the following statements in this program: Tenga en cuenta las siguientes declaraciones
en este programa:

 Lines 3 and 4: Two new objects are created, a object called and a object called . Las
líneas 3 y 4: Dos nuevos objetos se crean, un objeto perro llamado perrito y
MorleySafer un objeto llamado Morley.
 Line 5: The variable of the object is set to . Línea 5: La variable nombre del perro del
perrito objeto se establece en Cujo.
 Line 6: The variable of the object is set to . Línea 6: La variable nombre de la morley
objeto MorleySafer se establece en Morley Safer.
 Line 8: The method of the object is called. Línea 8: El habla () de el objeto del
perrito se llama. Looking at the method of the class of objects, you can see that it
displays the text, En cuanto a la palabra () de la clase de perro de los objetos, se
puede ver que muestra el texto, Arf! . Arf!.
 Line 10: The method of the object is called, resulting in the display of the following text:
Línea 10: El habla () de morley el objeto se llama, lo que resulta en la pantalla el
siguiente texto: ¿Puedo hacerle algunas preguntas acerca de su
declaración de impuestos de 1987?
 Lines 12 and 13: The methods of and then are called. Las líneas 12 y 13: El sueño () de
perro y luego Morley se llaman. If you look at the class or the class, you won't find a
method. Si nos fijamos en la clase de perros o la clase MorleySafer, usted no
encontrará un sueño () método. However, because and both inherit from the class,
you should look there to see if it has a method that could have been inherited by its
subclasses. Sin embargo, como perros y MorleySafer ambas heredan de la clase
Mammal, usted debe buscar allí para ver si tiene un sueño () que podría haber sido
heredado por sus subclases. The class does have a method, so the snoring text, , is
displayed twice. La clase de los mamíferos tiene un sueño () método, por lo que el
texto de los ronquidos, ZZZZ ZZZZ ZZZZZZ, aparece dos veces.

Summary Resumen
After creating your first class of objects and arranging several classes into a hierarchy, you
ought to be more comfortable with the term object-oriented programming. Después de crear
su primera clase de objetos y la organización de varias clases en una jerarquía, que debe ser
más cómodo con el término de programación orientada a objetos. You will be learning
more about object behavior and attributes in the next two hours as you start creating more
sophisticated objects. Usted va a aprender más sobre el comportamiento y atributos de
objetos en las próximas dos horas, como empezar a crear los objetos más sofisticados.

Terms such as program, class, and object will make more sense as you have more
experience with object-oriented development. Términos tales como el programa, la clase, y
el objeto tendrá más sentido a medida que tienen más experiencia en el desarrollo orientado
a objetos. It's a concept that takes some time to get used to. Es un concepto que toma algún
tiempo para acostumbrarse. Once you have mastered it, you'll find that it's an effective way
to design, develop, and debug computer programs. Una vez que haya dominado, usted
encontrará que es una manera eficaz de diseñar, desarrollar y depurar los programas de
ordenador.

Q&A Q & A
Q Can classes inherit from more than one class? Q clases pueden heredar de más de una
clase?

A It's possible with some programming languages but not Java. Una es posible con algunos
lenguajes de programación, pero no Java. Multiple inheritance is a powerful feature, but it
also makes object-oriented programming a bit harder to use and to learn. La herencia
múltiple es una característica de gran alcance, pero también hace que la programación
orientada a objetos un poco más difícil de usar y aprender. Java's developers decided to
limit inheritance to one superclass for any class, although a class can have numerous
subclasses. los desarrolladores de Java decidió limitar la herencia de una superclase de
cualquier clase, aunque una clase puede tener subclases numerosas.

Q Why are object-oriented programs easier to debug? Q ¿Por qué se orientan los
programas-objeto más fácil de depurar?

A Object-oriented programs enable you to focus on a smaller part of a computer program


when figuring out where an error is happening. Una orientada a programas de objetos le
permiten centrarse en una parte más pequeña de un programa de ordenador averiguar
donde un error que está sucediendo. Because a related group of tasks are handled by the
same object, you can focus on that object if the tasks aren't being performed correctly.
Debido a que un grupo relacionado de tareas son manejadas por el mismo objeto, puede
centrarse en ese objeto, si las tareas no se realizan correctamente. You don't have to
worry about any other parts of the program. Usted no tiene que preocuparse por otras
partes del programa.

Q When would you want to create a class that isn't public? Q Cuando se desea crear una
clase que no es público?

A The main time you would not want to make a class of objects available to other Una vez
la principal que no quieres hacer una clase de objetos a disposición de otros
programs is when the class is strictly for the use of one program you're writing. programas
es cuando la clase es estrictamente para el uso de un programa que está escrito. If you're
creating a game program and your class of objects is highly specific to the game you're
writing, it could be a private class. Si va a crear un programa de juego y su clase
ReloadGun de los objetos es altamente específico para el juego que estás escribiendo,
podría ser una clase privada. To make a class private, leave off the statement in front of .
Para hacer una clase privada, dejar fuera de la declaración pública frente a la clase.

Quiz Quiz
The following questions will test your knowledge of objects and the programs that use
them. Las siguientes preguntas se pondrá a prueba su conocimiento de los objetos y los
programas que los utilizan.

Questions Preguntas

1. What statement is used to enable one class to inherit from another class? 1. ¿Qué
comando se usa para que una clase que hereda de otra clase?

(a) (A) hereda


(b) (B) se extiende
(c) (C) handitover

2. Why are compiled Java programs saved with the file extension? 2. ¿Por qué se
compilan los programas Java que se almacenan con la extensión de archivo de clase.?

(a) Java's developers think it's a classy language. a) los desarrolladores de Java (creo que
es un lenguaje de clase.
(b) It's a subtle tribute to the world's teachers. (B) Es un sutil homenaje al mundo de los
profesores.
(c) Every Java program is a class. (C) Cada programa de Java es una clase.

3. What are the two things that make up an object? 3. ¿Cuáles son las dos cosas que hacen
que un objeto?

(a) attributes and behavior (A) los atributos y el comportamiento


(b) commands and data files (B) los comandos y archivos de datos
(c) spit and vinegar (C) escupir y vinagre

Answers Respuestas
1. b. 1. B. The statement is used because the subclass is an extension of the attributes and
behavior of the superclass and of any superclasses above that in the class hierarchy. La
sentencia extends se utiliza debido a que la subclase es una extensión de los atributos y
el comportamiento de la superclase y de cualquier superclases superior a la de la jerarquía
de clases.

2. c. 2. C. Your programs will always be made up of at least one main class and any other
classes that are needed. Sus programas siempre se compone de por lo menos una clase
principal y de otras clases que se necesitan.

3. a. 3. A. In a way, b is also true because commands are comparable to behavior, and data
files are analogous to attributes. En cierto modo, b también es cierto porque los comandos
son comparables con el comportamiento, y archivos de datos son análogos a los atributos.

Activities Actividades
If you don't object, you can your knowledge of this hour's topics with the following
activity: Si usted no se opone, puede amplía sus conocimientos de hora de los temas de
este con la siguiente actividad:

 Create a few more classes of objects to go under the class alongside and . Cree un poco
más clases de objetos para pasar por debajo de la clase Mammal junto a perros y
MorleySafer. Add classes for ducks, horses, 60 Minutes correspondent Mike Wallace,
and owls that do not snore. Añadir clases de patos, caballos, corresponsal de 60 Minutes
Mike Wallace, y los búhos que no roncan. By creating an class that inherits from and
putting a new method in , you can create your own special snoring statement for that
creature. Al crear una clase que hereda de búho Mamíferos y poniendo un sueño nuevo
() en Búho, usted puede crear sus propios ronquidos declaración especial de esa
criatura.

 11 horas
o Describiendo lo que su objeto es como
 Creación de variables
 Creación de variables de clase
 Creación de comportamiento con métodos
 La declaración de un método
 Métodos similares con argumentos diferentes
 Constructor Métodos
 La clase Methods
 Ámbito de aplicación variable dentro de los métodos
 Uso de la palabra clave de este
 Taller: Uso de Métodos de la clase y variables
 Listado de 11.1. El texto completo de Virus.java.
 Listado de 11.2. El texto completo de VirusLook.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 11 11 horas

Describing What Your Object Is Like Describiendo lo


que su objeto es como

As you learned during last hour's introduction to object-oriented programming, an object is


a way of organizing a program so that it has everything it needs to accomplish a task. Como
ha aprendido durante la introducción en la última hora de la programación orientada a
objetos, un objeto es una forma de organizar un programa para que tenga todo lo necesario
para realizar una tarea. Objects need two things to do their jobs: attributes and behavior.
Los objetos necesitan dos cosas para hacer su trabajo: los atributos y el comportamiento.

Attributes are the information stored within an object. Los atributos son la información
almacenada en un objeto. They can be variables such as integers, characters, Boolean
values, or even other objects. Ellos pueden ser variables, tales como enteros, caracteres,
valores booleanos, o incluso otros objetos. Behavior is the groups of statements used to
handle specific jobs within the object. El comportamiento es el público de los estados para
realizar trabajos específicos en el objeto. Each of these groups is called a method. Cada uno
de estos grupos se llama un método.

Up to this point, you have been working with the methods and variables of objects without
knowing it. Hasta este momento, ha estado trabajando con los métodos y variables de los
objetos sin saberlo. Any time your statement had a period in it that wasn't a decimal point
or part of a string, chances are an object was involved. Cada vez que su declaración había
un período en que eso no era un punto decimal o parte de una cadena, es probable que un
objeto estaba involucrado. You'll see this during this hour as the following topics are
covered: Usted verá esto durante esta hora como la tratan los siguientes temas:
 Creating variables for an object Creación de variables de un objeto
 Creating variables for a class Creación de variables para una clase
 Using methods with objects and classes El uso de métodos con los objetos y clases
 Calling a method in a statement Llamar a un método en un comunicado
 Returning a value with a method Devolver un valor con un método
 Creating constructor methods Creación de métodos constructores
 Sending arguments to a method El envío de los argumentos de un método
 Using to refer to an object El uso de este para hacer referencia a un objeto
 Creating new objects Creación de nuevos objetos

For the purposes of this hour's examples, you'll be looking at a class of objects called
whose sole purpose in life is to reproduce in as many places as possible--much like some of
the people I went to college with. A efectos de la hora de ejemplos de esto, se le busca en
una clase de objetos llamados virus cuyo único propósito en la vida es para reproducir en
tantos lugares como sea posible - al igual que algunas de las personas que fueron a la
universidad con. A has several different things it needs in order to do its work, and these
will be implemented as the behavior of the class. Un virus tiene varias cosas diferentes
que necesita para hacer su trabajo, y estos se llevarán a cabo como el comportamiento de la
clase. The information that's needed for the methods will be stored as attributes. La
información que se necesita para los métodos se almacenan como atributos.

Caution: The example in this hour will not teach actual virus writing, though it might provide some
insight into how virus programs work as they wreak havoc on the file systems of the computer-
loving world. Atención: El ejemplo de esta hora no enseñar a escribir virus real, aunque podría dar
una idea de cómo los programas de trabajo como el virus que causan estragos en los sistemas de
archivos de la amante del mundo de la informática. Sams.net had scheduled Teach Yourself Virus
Programming in a Three-Day Weekend for spring of this year, but the book has been postponed
because the author's hard drive was unexpectedly erased on Michaelangelo's birthday. Sams.net
había programado Teach Yourself Virus de programación en un fin de semana de tres días para la
primavera de este año, pero el libro ha sido pospuesto debido a el disco duro del autor fue
borrado inesperadamente en el cumpleaños de Miguel Ángel.

Creating Variables Creación de variables


The attributes of an object represent any variables that are needed in order for the object to
function. Los atributos de un objeto representan las variables que se necesitan para que el
objeto de función. These variables could be simple data types such as integers, characters,
and floating-point numbers, or they could be arrays or objects of the or classes. Estas
variables pueden ser tipos de datos simples, como enteros, caracteres y números de punto
flotante, o pueden ser matrices u objetos de las clases String o gráficos. An object's
variables can be used throughout its program in any of the methods the object includes.
variables de un objeto puede ser utilizado a través de su programa en cualquiera de los
métodos del objeto incluye. You create variables immediately after the statement that
creates the class and before any methods. Puede crear variables inmediatamente después de
la declaración de clase que crea la clase y antes de cualquier método.

One of the things that a object needs is a way to indicate that a file has already been
infected. Una de las cosas que un objeto virus necesita es una manera de indicar que un
archivo ha sido infectado. Some computer viruses change the field that stores the time a file
was last modified; for example, a virus might move the time from to . Algunos virus
informáticos cambiar el campo que almacena la vez que un archivo fue modificado por
última vez, por ejemplo, un virus puede mover el tiempo de 13:41:20 a 13:41:61.
Because no normal file would be saved on the 61st second of a minute, the time is a sign
that the file was infected. Porque no hay ningún archivo normal sería guardado en el
segundo 61 de un minuto, el tiempo es una señal de que el archivo estaba infectado. The
object will use as the seconds field of a file's modification time because "86 it" is slang that
means to throw something away--exactly the kind of unpleasant antisocial connotation
we're going for. El objeto Virus utilizará 86 como el campo de segundos de la
modificación de archivos en tiempo debido a un "86" es la jerga que significa tirar algo -
exactamente el tipo de connotación antisocial desagradables que estamos buscando. The
value will be stored in an integer variable called . El valor se almacena en una variable
entera llamada newSeconds.

The following statements begin a class called with an attribute called and two other
attributes: Las siguientes declaraciones comenzar una clase llamada Virus con un atributo
llamado newSeconds y dos otros atributos:

public class Virus { public class Virus {


public integer newSeconds = 86; entero newSeconds
pública = 86;
public String author = "Sam Snett"; públicos autor
String = "Sam Snett";
integer maxFileSize = 30000; entero MaxFileSize =
30000;

All three variables are attributes for the class: , , and . Las tres variables son los atributos
de la clase: newSeconds, MaxFileSize, y el autor.

The variable has a starting value of 86, and the statement that creates it has in front of it.
La variable newSeconds tiene un valor inicial de 86, y la afirmación de que crea que ha de
enfrente de ella. Making a variable makes it possible to modify the variable from another
program that is using the object. Realización de una variable pública hace que sea posible
modificar la variable de otro programa que utiliza el objeto virus. If the other program
attaches special significance to the number , for instance, it can change to that value. Si el
otro programa concede especial importancia al número 92, por ejemplo, puede cambiar
newSeconds a ese valor. If the other program creates a object called , it could set that
object's variable with the following statement: Si el otro programa crea un objeto llamado
virus de la gripe, que podría sentar objeto newSeconds variable que con la siguiente
declaración:

influenza.newSeconds = 92; influenza.newSeconds = 92;

The variable also is , so it can be changed freely from other programs. La variable de
autor también es pública, por lo que se puede cambiar libremente de otros programas.
The other variable, , can only be used within the class itself. La otra variable,
MaxFileSize, sólo se puede utilizar dentro de la clase de virus en sí.

When you make a variable in a class , the class loses control over how that variable is used
by other programs. Cuando usted hace una variable en un público de clase, la clase pierde
el control sobre la forma en que la variable es utilizada por otros programas. In many cases,
this might not be a problem. En muchos casos, esto podría no ser un problema. For
example, the variable can be changed to any name or pseudonym that identifies the author
of the virus, and the only restriction is aesthetic. Por ejemplo, la variable de autor se puede
cambiar a cualquier nombre o pseudónimo que identifique al autor del virus, y la única
restricción es estético. The name might eventually be used on court documents if you're
prosecuted, so you don't want to pick a dumb one. El nombre con el tiempo podría ser
utilizado en documentos de la corte si usted está procesado, por lo que no quiere elegir una
muda. The State of Ohio v. LoveHandles doesn't have the same ring to it as Ohio v. April
Mayhem. El Estado de Ohio v. LoveHandles no tiene el mismo anillo a ella como Ohio v.
Mayhem abril.

Restricting access to a variable keeps errors from occurring if the variable is set incorrectly
by another program. Restringir el acceso a una variable mantiene los errores que se
produzcan si la variable no está bien ajustada por otro programa. With the class, if is set to
a value of 60 or less, it won't be reliable as a way to tell that a file is infected. Con la clase
de virus, si newSeconds se establece en un valor de 60 o menos, no será confiable como
una manera de decir que un archivo está infectado. Some files may be saved with that
number of seconds regardless of the virus, and they'll look infected to . Algunos archivos
se pueden guardar con ese número de segundos sin importar el virus, y van a ver infectada
con el virus. If the class of objects needs to guard against this problem, you need to do
these two things: Si la clase de virus de los objetos tiene que evitar este problema, que
tiene que hacer estas dos cosas:

 Switch the variable from to or . Cambie la variable de público a privado protegido


o privado.
 Add behavior to change the value of the variable and report the value of the variable to
other programs. Añadir el comportamiento para cambiar el valor de la variable y
comunicar el valor de la variable a otros programas.

A variable can only be used in the same class as the variable or any subclasses of that
class. Una variable protegida privada sólo se puede utilizar en la misma clase que la
variable o subclases de dicha clase. A variable is restricted even further--it can only be
used in the same class. Una variable privada se restringe aún más - que sólo se puede
utilizar en la misma clase. Unless you know that a variable can be changed to anything
without affecting how its class functions, you probably should make the variable or . A
menos que sepa que una variable puede cambiar a cualquier cosa sin afectar cómo sus
funciones de clase, probablemente deba realizar la variable privada o privados
protegidos.

The following statement makes a variable: La siguiente declaración hace newSeconds una
variable protegida privada:

private protected int newSeconds = 86; privado newSeconds


int protegidas = 86;

If you want other programs to use the variable in some way, you'll have to create behavior
that makes it possible. Si desea otros programas para usar la variable newSeconds de
alguna manera, usted tendrá que crear un comportamiento que hace que sea posible. This
task will be covered later in the hour. Esta tarea se describe más adelante en la hora.

Creating Class Variables Creación de variables de clase


When you create an object, it has its own version of all the variables that are part of the
object's class. Cuando se crea un objeto, tiene su propia versión de todas las variables que
forman parte de la clase del objeto. Each object created from the class of objects has its
own version of the , , and variables. Cada objeto creado a partir de la clase de virus de
los objetos tiene su propia versión de la newSeconds, MaxFileSize, y las variables de
autor. If you modified one of these variables in an object, it would not affect the same
variable in another object. Si ha modificado una de estas variables en un objeto, no
afectaría a la misma variable en otro objeto virus.

There are times when an attribute has more to do with an entire class of objects than a
specific object itself. Hay momentos en que un atributo tiene más que ver con toda una
clase de objetos de un objeto específico en sí. For example, if you wanted to keep track of
how many objects were being used in a program, it would not make sense to store this
value repeatedly in each object. Por ejemplo, si desea realizar un seguimiento de cuántos
objetos virus estaban siendo utilizadas en un programa, no tendría sentido para almacenar
este valor en varias ocasiones en cada objeto virus. Instead, you can use a class variable
to store this kind of information. En su lugar, puede utilizar una variable de clase para
almacenar este tipo de información. You can use this variable with any object of a class, but
only one copy of the variable exists for the whole class. Usted puede utilizar esta variable
con un objeto de una clase, pero sólo una copia de la variable existe para toda la clase. The
variables you have been creating for objects thus far can be called object variables, because
they are tied to a specific object. Las variables que han sido la creación de objetos hasta el
momento se puede llamar las variables de objeto, porque están atadas a un objeto
específico. Class variables refer to a class of objects as a whole. Las variables de clase se
refieren a una clase de objetos como un todo.

Both types of variables are created and used in the same way, except that is used in the
statement that creates class variables. Ambos tipos de variables se crean y utilizan de la
misma manera, excepto que estática se utiliza en la declaración que crea las variables de
clase. The following statement creates a class variable for the example: La siguiente
sentencia crea una variable de clase para el ejemplo del virus:

static int virusCount = 0; int virusCount estática = 0;

Changing the value of a class variable is no different than changing an object's variables.
Cambiar el valor de una variable de clase no es diferente al cambio de las variables de un
objeto. If you have a object called , you could change the class variable with the
following statement: Si usted tiene un objeto llamado Virus tuberculosis, usted podría
cambiar el virusCount variable de clase con la siguiente declaración:

tuberculosis.virusCount++; tuberculosis.virusCount + +;

Because class variables apply to an entire class instead of a specific object, you can use the
name of the class instead: Dado que las variables de clase se aplican a toda una clase en
lugar de un objeto específico, puede utilizar el nombre de la clase en su lugar:

Virus.virusCount++; Virus.virusCount + +;

Both statements accomplish the same thing, but there's an advantage to using the second
one. Ambas declaraciones conseguir lo mismo, pero hay una ventaja de usar la segunda. It
shows immediately that is a class variable instead of an object's variable because you can't
refer to object variables with the name of a class. Esto demuestra inmediatamente que
virusCount es una variable de clase en lugar de un objeto variable, ya que no puede hacer
referencia a variables de objeto con el nombre de una clase. That's only possible with class
variables. Eso sólo es posible con las variables de clase.
Creating Behavior with Methods Creación de comportamiento con métodos
Attributes are the way to keep track of information about a class of objects, but they don't
take any action. Los atributos son la manera de llevar un registro de información sobre una
clase de objetos, pero no toman ninguna acción. For a class to do the things it was created
to do, you must create behavior. Para una clase para hacer las cosas que se creó para hacer,
debe crear el comportamiento. Behavior describes all of the different sections of a class that
accomplish specific tasks. Comportamiento describe todas las diferentes secciones de una
clase que realizar tareas específicas. Each of these sections is called a method. Cada una de
estas secciones se llama un método.

You have been using methods throughout your programs up to this point without knowing
it, including two in particular: in Java applications and in applets. Usted ha estado
utilizando los métodos a través de sus programas hasta el momento, sin saberlo, dos de
ellas en particular: println () en aplicaciones Java y drawString () en los applets.
These methods display text on-screen. Estos métodos de visualización de texto en pantalla.
Like variables, methods are used in connection with an object or a class. Al igual que las
variables, los métodos se utilizan en relación con un objeto o una clase. The name of the
object or class is followed by a period and the name of the method, as in or . El nombre
del objeto o una clase es seguida por un punto y el nombre del método, como en
screen.drawString () o Integer.parseInt ().

The method might seem confusing because it has two periods instead of one. El
System.out.println () método puede parecer confuso, ya que tiene dos períodos en vez
de uno. This is because two classes are involved in the statement--the class and the class.
Esto se debe a dos clases están involucrados en la declaración - la clase System y la clase
PrintStream. The class has a variable called that is a object. is a method of the class.
La clase System tiene una variable llamada que es un objeto PrintStream. Println ()
es un método de la clase PrintStream. The statement means, in effect, "Use the method
of the variable of the class." El System.out.println () significa, en efecto, "Usar el
método println () de la variable de la clase del sistema". You can chain together
references to variables and methods in this way. Puede encadenar referencias a las variables
y métodos de esta manera.

Declaring a Method La declaración de un método

You create methods with a statement that looks similar to the statement that begins a class.
Puede crear métodos con una declaración que se parece a la afirmación de que comience la
clase. Both can take arguments between parentheses after their names, and both use and
marks at the beginning and end. Ambos pueden tener argumentos entre paréntesis después
de sus nombres, y ambos utilizan {y} marcas al principio y al final. The difference is that
methods can send back a value after they are handled. La diferencia es que los métodos
pueden devolver un valor después de que se manejan. The value can be one of the simple
types such as integers or Booleans, or it can be a class of objects. El valor puede ser uno de
los tipos simples, como enteros o booleanos, o puede ser una clase de objetos. If a method
should not return any value, use the statement . Si un método no devuelve ningún valor,
utilice el vacío comunicado.

The following is an example of a method the class can use to infect files: El siguiente es un
ejemplo de un método de la clase de virus puede utilizar para infectar los archivos:

boolean public infectFile(String filename) { pública


infectFile booleano (String nombre) {
boolean success = false; éxito boleano = false;
// file-infecting statements would be here / /
Infectar a las declaraciones de archivo estaría aquí
return success; retorno éxito;
} }

The method is used to add a virus to a file. El infectFile () se utiliza para añadir un
virus en un archivo. This method takes a single argument, a string variable called , and this
variable represents the file that should be attacked. Este método toma un solo argumento,
una variable de cadena denominada nombre de archivo y esta variable representa el
archivo que debe ser atacado. The actual code to infect a file is omitted here due to the
author's desire to stay on the good side of the US Secret Service. El código real para
infectar un archivo se omite aquí por deseo del autor a permanecer en el lado bueno del
Servicio Secreto de los EE.UU.. The only thing you need to know is that if the infection is a
success, the variable is set to a value of . Lo único que usted necesita saber es que si la
infección es un éxito, la variable de éxito se establece en un valor de verdad.

By looking at the statement that begins the method, you can see preceding the name of the
method, . Al mirar a la afirmación de que comienza el método, se puede ver booleano que
precede al nombre del método, infectFile. This statement signifies that a value will be
sent back after the method is handled. Esta declaración significa que un valor booleano
serán devueltos después de que el método se maneja. The statement is what actually sends
a value back. La sentencia return es lo que realmente envía un valor de nuevo. In this
example, the value of is returned. En este ejemplo, el valor de éxito se devuelve.

When a method returns a value, you can use the method as part of an assignment statement.
Cuando un método devuelve un valor, puede utilizar el método como parte de una
instrucción de asignación. For example, if you created a object called , you could use
statements such as these: Por ejemplo, si ha creado un objeto llamado Virus de la
malaria, se puede usar frases como estas:

if (malaria.infectFile(currentFile)) if
(malaria.infectFile (currentFile))
System.out.println(currentFile + " has been
infected!"); System.out.println (currentFile + "ha sido
infectado!");
else más
System.out.println("Curses! Foiled again!");
System.out.println ("¡Maldición Frustrado otra vez!");

Any method that returns a value can be used at any place a value or variable could be used
in a program. Cualquier método que devuelve un valor puede ser usado en cualquier lugar
de un valor o una variable podría ser utilizado en un programa.

Earlier in the hour, you switched the variable to to prevent it from being set by other
programs. A principios de la hora, le cambian la variable newSeconds como privado para
evitar que se está estableciendo con otros programas. However, because you're a virus
writer who cares about people, you still want to make it possible for to be used if it is used
correctly. Sin embargo, porque usted es un creador de virus que se preocupa por la gente,
usted todavía desea hacer posible que newSeconds que se utilizará si se usa correctamente.
The way to do this is to create methods in the class that use . La manera de hacer esto es
crear métodos públicos en la clase de virus que newSeconds uso. Because these methods
are , they can be used by other programs. Debido a que estos métodos son públicos,
pueden ser utilizados por otros programas. Because they're in the same class as , they can
modify it. Porque están en la misma clase que newSeconds, pueden modificarlo.

Consider the following two methods: Considere los siguientes dos métodos:

int public getSeconds() { int getSeconds público () {


return newSeconds; newSeconds retorno;
} }

void public setSeconds(int newValue) { vacío setSeconds


público (newValue int) {
if (newValue > 60) if (newValue> 60)
newSeconds = newValue; newSeconds = newValue;
} }
The method is used to send back the current value of . El getSeconds () se utiliza para
devolver el valor actual de newSeconds. The method is necessary because other programs
can't even look at because it is . El getSeconds () es necesaria porque los programas de
otros, incluso puede no mirar newSeconds porque es privado. The method does not have
any arguments, but it still must have parentheses after the method name. El getSeconds ()
no tiene argumentos, pero aún debe haber entre paréntesis después del nombre del método.
Otherwise, when you were using in a program, the method would look no different than a
variable. De lo contrario, cuando se estaban utilizando getSeconds en un programa, el
método no sería diferente de una variable.

The method takes one argument, an integer called . El setSeconds () toma un


argumento, un entero llamado newValue. This integer contains the value that a program
wants to change to. Este entero contiene el valor que un programa quiere cambiar a
newSeconds. If is 61 or greater, the change will be made. Si newValue es de 61 o mayor,
el cambio se hará. The method has preceding the method name, so it does not return any
kind of value. El setSeconds () método vacío precedente del nombre del método, por lo
que no devuelve ningún tipo de valor.

Similar Methods with Different Arguments Métodos similares con argumentos


diferentes

As you have seen with the method, you can send arguments to a method to affect what it
does. Como se ha visto con la setSeconds () método, usted puede enviar argumentos a un
método para afectar lo que hace. Different methods in a class can have different names, but
methods can also have the same name if they have different arguments. Diferentes métodos
en una clase puede tener diferentes nombres, pero los métodos también pueden tener el
mismo nombre si se tienen argumentos diferentes.

Two methods can have the same name if they have a different number of arguments, or the
specific arguments are of different variable types. Dos métodos pueden tener el mismo
nombre si tienen un número diferente de argumentos, o los argumentos específicos de los
tipos de variables diferentes. For example, it might be useful for the class of objects to
have two methods. Por ejemplo, podría ser útil para la clase de virus de los objetos para
tener dos tauntUser () métodos. One could have no arguments at all and would deliver a
generic taunt. Uno no podía tener argumentos en absoluto, y emitiría un insulto genérico.
The other could specify the taunt as a string argument. El otro podría especificar la burla
como un argumento de cadena. The following statements could implement these methods:
Las declaraciones siguientes se pueden aplicar estos métodos:

void tauntUser() { tauntUser void () {


System.out.println("The problem is not with your set,
but with yourselves."); System.out.println ("El problema no
es con su aparato, pero con vosotros mismos.");
} }

void tauntUser(String taunt) { vacío tauntUser (burla


String) {
System.out.println(taunt); System.out.println
(burlarse);
} }

Constructor Methods Constructor Métodos

When you want to create an object in a program, use the statement, as in the following:
Cuando desee crear un objeto en un programa, utilice la nueva declaración, como en el
siguiente:

Virus typhoid = new Virus(); Virus de la fiebre tifoidea =


new virus ();

This statement creates a new object called , and it uses a special method in the class
called a constructor. Esta sentencia crea un nuevo objeto llamado Virus fiebre
tifoidea, y utiliza un método especial en la clase de virus que se llama un constructor.
Constructors are methods that are used when an object is first being created. Los
constructores son métodos que se utilizan cuando un objeto es el primer ser creado. The
purpose of a constructor is to set up any variables and other things that need to be
established. El objetivo de un constructor es la constitución de las variables y otras cosas
que necesitan ser establecidas.

The following are two constructor methods for the class of objects: Los siguientes son dos
métodos de constructor de la clase de virus de objetos:

public Virus() { pública Virus () {


maxFileSize = 30000; MaxFileSize = 30000;
} }

public Virus(String name, int size) { pública Virus


(String nombre, int size) {
author = name; autor = nombre;
maxFileSize = size; MaxFileSize = tamaño;
} }

Like other methods, constructors can use the arguments they are sent as a way to have more
than one constructor in a class. Al igual que otros métodos, los constructores pueden
utilizar los argumentos que se envían como una manera de tener más de un constructor en
una clase. In this example, the first constructor would be used with a statement such as the
following: En este ejemplo, el primer constructor que se utiliza con una declaración como
la siguiente:

Virus mumps = new Virus(); Virus de las paperas Virus =


new ();

The other constructor could be used only if a string and an integer were sent as arguments,
as in this statement: El constructor de otros podría ser utilizado sólo si una cadena y un
entero fueron enviados como argumentos, como en esta declaración:

Virus rubella = new Virus("April Mayhem", 60000); Virus de


la rubéola = new virus ("Abril Mayhem", 60000);

If you only had the preceding two constructor methods, you could not use the statement
with any other type or number of arguments within the parentheses. Si sólo había en los
últimos dos métodos constructores, que no podía usar la nueva declaración con cualquier
otro tipo o el número de argumentos entre los paréntesis.

Class Methods La clase Methods

Like class variables, class methods are a way to provide functionality associated with an
entire class instead of a specific object. Al igual que las variables de clase, métodos de clase
son una manera de proporcionar la funcionalidad asociadas a toda una clase en lugar de un
objeto específico. Use a class method when the method does nothing that affects an
individual object of the class. Utilice un método de clase cuando el método no hace nada
que afecta a un objeto individual de la clase. One example that you have used in a previous
hour was the method of the class. Un ejemplo que ha utilizado en una hora anterior fue el
parseInt () de la clase Integer. This method is used to convert a string to a variable of
the type , as in the following: Este método se utiliza para convertir una cadena a una
variable de tipo int, como en lo siguiente:

int time = Integer.parseInt(timeText); int tiempo =


Integer.parseInt (timeText);
To make a method into a class method, use in front of the method name, as in the
following: Para hacer que un método en un método de clase, uso estático frente al
nombre del método, como en lo siguiente:

static void showVirusCount() { showVirusCount static void


() {
System.out.println("There are " + virusCount + "
viruses."); System.out.println ("Hay" + + virusCount
"virus.");
} }

The class variable was used earlier to keep track of how many objects have been created
by a program. La variable de clase virusCount se utilizó anteriormente para realizar un
seguimiento de cuántos objetos virus han sido creados por un programa. The method is a
class method that displays this total, and it should be called with a statement such as the
following: El showVirusCount () es un método de clase que muestra este total, y debe ser
llamada con una declaración como la siguiente:

Virus.showVirusCount(); Virus.showVirusCount ();

Variable Scope Within Methods Ámbito de aplicación variable dentro de los métodos

When you create a variable or an object inside a method in one of your classes, it is usable
only inside that method. Cuando se crea una variable o un objeto dentro de un método en
una de sus clases, se puede usar sólo dentro de ese método. The reason for this is the
concept of variable scope. La razón de esto es el concepto de alcance variable. Scope is the
section in which a variable exists in a program. Ámbito de aplicación es la sección en la
que una variable existe en un programa. If you go outside of the part of the program defined
by the scope, you can no longer use the variable. Si usted sale de la parte del programa
definido por el alcance, ya no se puede utilizar la variable.

The and statements in a program define the boundaries for a variable. La {y}
declaraciones en un programa de definir los límites de una variable. Any variable created
within these marks cannot be used outside of them. Cualquier variable creada dentro de
estas marcas no se pueden utilizar fuera de ellos. For example, consider the following
statements: Por ejemplo, considere las siguientes afirmaciones:

if (numFiles < 1) { if (numFiles <1) {


String warning = "No files remaining."; advertencia
String = "No hay archivos restantes.";
} }
System.out.println(warning); System.out.println (alerta);

This example does not work correctly because the variable was created inside the brackets
of the block statement. Este ejemplo no funciona correctamente porque la variable de
alerta fue creada dentro de los corchetes de la declaración de bloque, si. The variable
does not exist outside of the brackets, so the method cannot use as an argument. La
variable no existe fuera de los soportes, por lo que el System.out.println () no puede
utilizar como argumento de alerta.

One of the areas that can lead to errors in a program is when a variable has a different value
than you expected it to have. Una de las áreas que pueden conducir a errores en un
programa es cuando una variable tiene un valor diferente de lo que esperaba que tuviera. In
a large program written with many programming languages, this area can be difficult to fix
because any part of the program might use the variable. En un programa grande escrito con
muchos lenguajes de programación, esta área puede ser difícil de corregir porque cualquier
parte del programa podría utilizar la variable. Rules that enforce scope make programs
easier to debug because scope limits the area in which a variable can be used. Las reglas
que cumplir el alcance que los programas más fácil de depurar, ya alcance los límites de la
zona en la que puede ser una variable utilizada.

This concept applies to methods because a variable created inside a method cannot be used
in other methods. Este concepto se aplica a los métodos ya que una variable creada dentro
de un método no puede ser utilizado en otros métodos. You can only use a variable in more
than one method if it was created as an object variable or class variable after the statement
at the beginning of the program. Sólo se puede utilizar una variable en más de un método,
si se creó como una variable de objeto o variable de clase después de la instrucción de
clase al comienzo del programa.

Using the this Keyword Uso de la palabra clave de este


Because you can refer to variables and methods in other classes along with variables and
methods in your own class, it can easily become confusing. Debido a que usted puede hacer
referencia a las variables y métodos en otras clases junto con las variables y métodos en una
clase propia, que puede causar confusión. One way to make things a little clearer is with the
statement. Una forma de hacer las cosas un poco más claro es con la declaración de esta.
The statement is a way to refer in a program to the program's own object. La declaración
de esta es una manera de referirse en un programa para el propio objeto del programa.

When you are using an object's methods or variables, you put the name of the object in
front of the method or variable name, separated by a period. Cuando usted está utilizando
los métodos de un objeto o variables, se pone el nombre del objeto en frente del nombre del
método o variable, separados por un punto. Consider these examples: Considere estos
ejemplos:

Virus chickenpox = new Virus(); Virus de la varicela = new


virus ();
chickenpox.name = "LoveHandles"; chickenpox.name =
"LoveHandles";
chickenpox.setSeconds(75); chickenpox.setSeconds (75);

These statements create a new object called , set the variable of , and then use the
method of . Estas declaraciones crear un nuevo objeto virus llamado varicela,
establecer la variable de nombre de la varicela, y luego usar el setSeconds () de la
varicela.

There are times in a program where you need to refer to the current object--in other words,
the object represented by the program itself. Hay veces en un programa en el que usted
necesita para hacer referencia al objeto actual - en otras palabras, el objeto representado por
el propio programa. For example, inside the class, you might have a method that has its
own variable called : Por ejemplo, dentro de la clase de virus, puede tener un método
que tiene su propia variable llamada autor:

void public checkAuthor() { public void checkAuthor () {


String author = null; autor String = null;

} }

A variable called exists within the scope of the method, but it isn't the same variable as an
object variable called . Un autor llamado variable existe en el ámbito de la checkAuthor
() método, pero no es la misma variable como una variable llamada autor objeto. If you
wanted to refer to the current object's variable, you have to use the statement, as in the
following: Si usted quisiera hacer referencia a objetos autor variable de la corriente, usted
tiene que utilizar la instrucción de este, como en lo siguiente:

System.out.println(this.author); System.out.println
(this.author);

By using , you make it clear which variable or method you are referring to. Mediante el
uso de esto, que quede claro qué variable o método que usted se refiere. You can use
anywhere in a class that you would refer to an object by name. Usted puede utilizar esta en
cualquier parte de una clase que se haría referencia a un objeto por su nombre. If you
wanted to send the current object as an argument in a method, for example, you could use a
statement such as the following: Si quería enviar el objeto actual como un argumento a un
método, por ejemplo, puede utilizar una declaración como la siguiente:

verifyData(this); verifydata (este);

In many cases, the statement will not be needed to make it clear that you're referring to an
object's variables and methods. En muchos casos, la declaración no será necesaria para
dejar claro que te refieres a las variables de un objeto y métodos. However, there's no
detriment to using any time you want to be sure you're referring to the right thing. Sin
embargo, no hay perjuicio a la utilización de este en cualquier momento usted quiere estar
seguro de que te refieres a lo correcto.

Workshop: Using Class Methods and Variables Taller: Uso de Métodos de la clase y
variables
At the insistence of every attorney and management executive in the Macmillan family of
computer publishers, the workshop for this hour will not be the creation of a working virus
program. Ante la insistencia de cada abogado y ejecutivo de la gestión en la familia
Macmillan equipo de editores, el taller para esta hora no será la creación de un programa de
trabajo del virus. Instead, you'll create a simple object that can do only one thing: Count
the number of objects that a program has created and report the total. En su lugar, creará un
simple objeto de virus que pueden hacer sólo una cosa: Cuente el número de objetos de
virus que un programa ha creado y la memoria del total.

Load your word processor and create a new file called . Cargue el procesador de texto y
crear un nuevo archivo llamado Virus.java. Enter Listing 11.1 into the word processor
and save the file when you're done. Introduzca listado 11.1 en el procesador de texto y
guarde el archivo cuando haya terminado.

Listing 11.1. Listado de 11.1. The full text of Virus.java. El texto completo de Virus.java.

1: public class Virus { 1: public class Virus {


2: static int virusCount = 0; ; 0 estática: 2 int
virusCount =
3: 3:
4: public Virus() { 4: Virus pública () {
5: virusCount++; 5: virusCount + +;
6: } 6:}
7: 7:
8: static int getVirusCount() { 8: getVirusCount static
int () {
9: return virusCount; 9: virusCount retorno;
10: } 10:}
11:}

Compile the file, and then return to your word processor. Compilar el archivo y, a
continuación, volver a su procesador de textos. You need to create a short program that will
create objects and ask the class to count them. Es necesario crear un programa corto que
va a crear objetos de virus y pregunte a la clase de virus de contarlos. Open up a new
file and enter Listing 11.2. Abra un archivo nuevo y entrar en lista 11.2. Save the file as
when you're done. Guarde el archivo como VirusLook.java cuando haya terminado.

Listing 11.2. Listado de 11.2. The full text of VirusLook.java. El texto completo de
VirusLook.java.

1: class VirusLook { 1: clase {VirusLook


2: public static void main(String arguments[]) { 2: static
public void principal (String argumentos []) {
3: Virus smash = new Virus(); 3: aplastar Virus = new
virus ();
4: Virus crash = new Virus(); 4: accidente Virus = new
virus ();
5: Virus crumble = new Virus(); 5: el virus se desmoronan
= new virus ();
6: System.out.println("There are " + Virus.getVirusCount()
+ " 7: viruses."); 6: System.out.println ("Hay" +
Virus.getVirusCount () + "7: los virus.");
8: } 8:}
9:}

Compile the file, and then run it with the interpreter by typing the following command:
Compile el archivo VirusLook.java, y luego lo ejecuta con el intérprete de Java, escriba
el siguiente comando:

java VirusLook java VirusLook

The output should be the following: El resultado debería ser el siguiente:

There are 3 viruses. Hay tres virus.


Summary Resumen
You now have completed two of the three hours devoted to object-oriented concepts in this
book. Ahora ha completado dos de las tres horas dedicadas a los conceptos orientados a
objetos en este libro. You've learned how to create an object and give behavior and
attributes to the object and to its own class of objects. Usted ha aprendido cómo crear un
objeto y darle el comportamiento y los atributos del objeto y de su propia clase de objetos.
Thinking in terms of objects is one of the tougher challenges of the Java programming
language. Pensar en términos de objetos es uno de los retos más dura del lenguaje de
programación Java. Once you start to understand it, however, you realize that the entire
language makes use of objects and classes. Una vez que empiece a entender, sin embargo,
te das cuenta de que todo el lenguaje hace uso de objetos y clases.

During the next hour, you'll learn how to give your objects parents and children. Durante la
hora siguiente, usted aprenderá cómo dar a sus padres los objetos y los niños.

Q&A Q & A
Q Can constructor methods send back a value like other methods? Q métodos
constructores se puede enviar de nuevo un valor como otros métodos?

A No, because there's no way to receive that value. R No, porque no hay manera de recibir
ese valor. Unlike other methods that can be used as part of an equation, the argument of
a method, or other statements, constructors are only handled in response to a statement.
A diferencia de otros métodos que pueden utilizarse como parte de una ecuación, el
argumento de un método, u otras declaraciones, los constructores sólo se tramitan en
respuesta a una nueva declaración. There's no way for that statement to receive a value
that would be sent by the method. No hay manera de que la declaración para recibir un
valor que sería enviado por el método.

Q Do you have to create an object to use class variables or methods? Q ¿Hay que crear
un objeto de utilizar las variables de clase o métodos?

A Because class variables and methods aren't associated with a specific object, you don't
Un Dado que las variables de clase y los métodos no están asociados con un objeto
específico, no
need to create an object solely for the purpose of using them. necesidad de crear un
objeto con el único fin de utilizarlos. The use of the method is an example of this because
you don't have to create a new object just to convert a string to an value. El uso de la
Integer.parseInt () es un ejemplo de esto porque usted no tiene que crear un
nuevo objeto entero sólo para convertir una cadena en un valor int.

Q What's the difference between the Integer object and the int variable type? Q ¿Cuál es
la diferencia entre el objeto entero y el tipo de variable int?

A The first is an object, and the second is a simple variable type. Una primera es la de un
objeto, y el segundo es un tipo de variable simple. Each of the variable types such as , ,
and has a corresponding object. Cada uno de los tipos de variables tales como, char,
int y float tiene un objeto correspondiente. The object is used when you want to use
an object's methods or treat the variable like an object. El objeto se utiliza cuando se
desea utilizar métodos de un objeto o tratar la variable como un objeto. Because an
object can do things in a program that the variable type cannot, it is convenient to have
both. Debido a un objeto entero puede hacer las cosas en un programa que el tipo de
variable int no puede, es conveniente tener ambos.

Quiz Quiz
The following questions will test whether you have the attributes and behavior to
understand object-oriented programming techniques. Las siguientes preguntas se pondrá a
prueba si tiene los atributos y comportamiento para entender las técnicas de programación
orientada a objetos.

Questions Preguntas

1. What is a method an example of in a Java class? 1. ¿Qué es un método en un ejemplo


de una clase Java?

(a) attributes (A) los atributos


(b) statements (B) las declaraciones
(c) behavior (C) el comportamiento

2. If you want to make a variable a class variable, what statement must you use when it is
created? 2. Si desea realizar una variable de una variable de clase, lo que la declaración
debe utilizar cuando se crea?

(a) (A) nuevo


(b) (B) públicos
(c) (C) estática

3. What is the name for the part of a program in which a variable lives? 3. ¿Cuál es el
nombre de la parte de un programa en el que vive una variable?

(a) its nest (A) su nido


(b) the scope (B) el alcance
(c) variable valley (C) del valle variable

Answers Respuestas

1. c. 1. C. A method is made up of statements, but it's an example of behavior. Un método


se compone de los estados, pero es un ejemplo de comportamiento.

2. c. 2. C.

3. b. 3. B.
Activities Actividades
If all this talk of viruses didn't make you sick, you can increase your knowledge of this
hour's topics with the following activity: Si todo esto hablar de los virus no hacer que se
enferme, usted puede aumentar su conocimiento de temas de esta hora con la siguiente
actividad:

 Add a variable to the class that stores an integer called . Añadir una variable privada a
la clase de virus que almacena un entero llamado newSeconds. Create methods to
return the value of and change the value of only if the new value is between 60 and 100.
Crear métodos para devolver el valor de newSeconds y cambiar el valor de newSeconds
sólo si el nuevo valor es de entre 60 y 100.

 12 horas
o Métodos heredar de otras clases
 El poder de la herencia
 Figura 12.1.
 La herencia de comportamiento y atributos
 Anulación de métodos
 El establecimiento de la herencia
 Taller: Creación de una subclase
 Listado de 12.1. El texto completo de Point3D.java.
 Listado de 12.2. El texto completo de TryPoints.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 12 12 horas
Inheriting Methods from Other Classes Métodos heredar
de otras clases

This might be a surprise to you, but your Java objects are ideally suited for childbearing.
Esto podría ser una sorpresa para usted, pero los objetos de Java son ideales para la
procreación. When you create a program as an object--a set of attributes and behavior--you
have designed something that's ready to pass these qualities on to offspring. Cuando se crea
un programa como un objeto - un conjunto de atributos y comportamientos - se han
diseñado algo que está listo para pasar estas cualidades a la descendencia. Like most
offspring, these child objects will take on a lot of the attributes and behavior of their parent.
Como la mayoría de la descendencia, estos objetos secundarios se enfrentará a muchos de
los atributos y el comportamiento de sus padres. They also can do some things differently
than their parent does and can add some extra attributes and behavior that pop is incapable
of. También pueden hacer algunas cosas de manera diferente que sus padres y se puede
agregar algunos atributos extra y un comportamiento que es incapaz de pop.

This system is called inheritance, and it's something every superclass parent gives to its
subclass children. Este sistema se denomina herencia, y es algo que todos los padres
superclase da a sus hijos subclase. Inheritance is one of the most useful aspects of object-
oriented programming, and you'll be learning more about it during this hour. La herencia es
uno de los aspectos más útiles de la programación orientada a objetos, y usted aprenderá
más acerca de ella durante esta hora.

The following topics will be covered: Los siguientes temas serán cubiertos:

 Superclasses and subclasses Superclases y subclases


 An inheritance hierarchy Una jerarquía de herencia
 Overriding methods Sustitución de métodos
 Creating a subclass La creación de una subclase
 Positioning behavior Posicionamiento comportamiento

The Power of Inheritance El poder de la herencia


Without knowing it, you have used inheritance every time you used one of the standard
Java classes such as or . Sin saberlo, usted ha utilizado la herencia cada vez que utiliza una
de las clases estándar de Java como String o Matemáticas. Java classes are organized
into a pyramid-shaped hierarchy of classes in which all classes descend from the class.
clases de Java se organizan en una jerarquía en forma de pirámide de las clases en todas las
clases que descienden de la clase Object.

A class of objects inherits from all superclasses that are above it. Una clase hereda de
objetos de todas las superclases que están por encima de ella. To get a working idea of how
this works, look at the class. Para tener una idea de trabajo de cómo funciona esto, mira la
clase Applet. This class is the superclass of all applets, which are Java programs that you
will write for the World Wide Web. Esta clase es la superclase de todos los subprogramas,
que son programas Java que se escriben para la World Wide Web. The family tree of is
shown in Figure 12.1. El árbol genealógico del applet se muestra en la Figura 12.1. Each
of the boxes is a class, and the lines connect a superclass above to any subclasses that it has
below. Cada una de las cajas es una clase, y las líneas de conectar un superclase la parte
superior para las subclases que tiene debajo.

Figura 12.1. The family tree of the class. El árbol genealógico de la clase Applet.

At the top is the class. has four superclasses above it in the hierarchy: , , , and . En la
parte superior es la clase de objetos:. Subprograma tiene cuatro superclases por encima
en la jerarquía del Grupo Especial, de contenedores, componentes y objetos. The
class inherits attributes and behavior from each of these classes because each is directly
above it in the hierarchy of superclasses. does not inherit anything from the five shaded
classes in Figure 12.1, which include and , because they are not above it in the hierarchy.
El Applet hereda la clase los atributos y el comportamiento de cada una de estas clases
porque cada uno es directamente encima de él en la jerarquía de las superclases. Applet no
hereda nada de las cinco clases sombreada en la figura 12.1, que incluyen diálogo y
Marco, porque no están por encima de ella en la jerarquía.

If this seems confusing, think of the hierarchy as a family tree. will inherit from its parents,
their parents, and on upward. Si esto le parece confuso, piensa en la jerarquía como un
árbol genealógico. Applet hereda de sus padres, sus padres, y hacia arriba. It even might
inherit some things from its great- great-grandparent . Incluso podría heredar algunas cosas
de su-bisabuelo de objetos grandes. The class won't inherit from its siblings or its
cousins, however. La clase Applet no hereda de sus hermanos o sus primos, sin embargo.

Setting up a complicated hierarchy of classes is a difficult thing, but it makes it easier to


create new programs later on. El establecimiento de una jerarquía compleja de clases es una
cosa difícil, pero hace más fácil para crear nuevos programas más adelante. The amount of
work you need to do to write a new class of objects is reduced. La cantidad de trabajo que
tiene que hacer para escribir una nueva clase de objetos se reduce. Creating a new class
boils down to the following task: You only have to define the ways in which it is different
from an existing class. Creación de una nueva clase se reduce a la siguiente tarea: Sólo
tiene que definir las formas en que se diferencia de una clase existente. The rest of the work
is done for you. El resto del trabajo está hecho para usted.

As an example, consider the popular video game Tetris. Como ejemplo, considere el
popular juego Tetris de vídeo. It has been adapted for dozens of different operating
systems, processors, and programming languages since being written by Soviet
mathematician Alexey Pajitnov and has been created as a Java class by several
programmers. Ha sido adaptado para las docenas de diferentes sistemas operativos,
procesadores, y lenguajes de programación desde que fue escrito por el matemático
soviético Alexey Pajitnov y ha sido creado como una clase Java por varios programadores.
In case you somehow avoided Tetris during the past decade by lapsing into a coma or
falling into a deep meditative trance, the game works as follows: Blocks of different shapes
fall from the top of the screen, and you must organize them into unbroken horizontal lines
before they stack up too high. En caso de que de alguna manera evitar Tetris durante la
última década por caer en un coma o caer en un trance meditativo profundo, el juego
funciona de la siguiente manera: bloques de diferentes formas caen desde la parte superior
de la pantalla, y usted debe organizarse en ininterrumpida líneas horizontales antes de que
se apilan demasiado alto.

The Java source file for several adaptations of Tetris is available for your use. El archivo de
código fuente de Java para varias adaptaciones de Tetris está disponible para su uso. If you
wanted to create a new version of Tetris based on one of these existing classes, you could
make your game a subclass of an existing Tetris game. Si desea crear una nueva versión de
Tetris basado en una de estas clases ya existentes, podría hacer su juego una subclase de
una ya existente juego de Tetris. All you would have to do is create the things that are new
or different about your version, and you'd end up with a new game. Todo lo que tendría que
hacer es crear las cosas que son nuevas o diferentes acerca de la versión, y que acabaría con
un nuevo juego.

Inheriting Behavior and Attributes La herencia de comportamiento y atributos

The behaviors and attributes of a class are a combination of two things: its own behavior
and attributes and all behavior and attributes it inherited from its superclasses. Los
comportamientos y atributos de una clase son una combinación de dos cosas: su propio
comportamiento y los atributos y el comportamiento de todos y los atributos que hereda de
sus superclases.

The following are some of the behavior and attributes of : Los siguientes son algunos de
los comportamientos y atributos de Applet:

 The method determines whether an object has the same value as another object. El
método equals () determina si un objeto Applet tiene el mismo valor que otro objeto.
 The method sets the background color displayed on the applet window. El
setBackground () método establece el color de fondo que aparecen en la ventana del
applet.
 The method adds user interface components such as buttons and text fields to the
applet. n El método add () añade los componentes de interfaz de usuario tales como
botones y campos de texto para el applet.
 The method displays a line of text in a Web browser's status bar. El showStatus ()
método muestra una línea de texto en la barra de estado del navegador web de un.
The class can use all of these methods, even though is the only one it didn't inherit from
another class. La clase Applet puede utilizar todos estos métodos, aunque showStatus ()
es el único que no heredar de otra clase. The method is defined in , comes from , and
comes from . El método equals () se define en el objeto, setBackground () viene de
componentes, y agregar () viene de contenedores.

Overriding Methods Anulación de métodos

Some of the methods defined in the class of objects also were defined in one of its
superclasses. Algunos de los métodos definidos en la clase Applet de objetos también se
definieron en una de sus superclases. As an example, the method is set up in the class and
the class. A modo de ejemplo, el cambio de tamaño () se creó en la clase Applet y la
clase de componentes. This method calls on the Web browser displaying the applet to
resize the applet's display area. Este método llama en el explorador Web que muestra el
applet para cambiar el tamaño de área de visualización del applet. When a method is
defined in a subclass and its superclass, the subclass method is used. Cuando se define un
método en una subclase y su superclase, el método de la subclase se utiliza. This enables a
subclass to change, replace, or completely wipe out some of the behavior or attributes of its
superclasses. Esto permite a una subclase de cambiar, sustituir o eliminar por completo
algunos de los comportamientos o los atributos de sus superclases.

Creating a new method in a subclass to change behavior inherited from a superclass is


called overriding the method. Creación de un nuevo método en una subclase para cambiar
el comportamiento heredado de una superclase se llama reemplazar el método. You need to
override a method any time the inherited behavior will produce an undesired result. Es
necesario reemplazar un método cada vez que el comportamiento heredado producirá un
resultado no deseado.

Establishing Inheritance El establecimiento de la herencia


You establish a class as the subclass of another class with the statement, as in the
following: Usted establece una clase como la subclase de otra clase con la declaración se
extiende, como en el siguiente:

class AnimatedLogo extends java.applet.Applet { clase


AnimatedLogo extiende java.applet.Applet {
// program goes here / / Aquí va el programa
} }

This statement establishes the class of objects as a subclass of , using the full class name
of . Esta declaración establece la clase AnimatedLogo de objetos como una subclase de
Applet, utilizando el nombre de clase completo de java.applet.Applet. As you will
see during the next hour, all applets in Java must be subclasses of because they need the
functionality this class provides in order to run on a World Wide Web page. Como se puede
ver durante la siguiente hora, todos los applets en Java debe ser subclases de Applet, ya
que necesitan la funcionalidad de esta clase proporciona con el fin de ejecutar en una
página del World Wide Web.

One method that will have to override is the method, which is used to redraw all things
that are shown on the program's display area. Un método que AnimatedLogo tendrá que
reemplazar es el método paint (), que se utiliza para volver a dibujar todas las cosas que se
muestran en el área de visualización del programa. The method is implemented by the
class and is passed all the way down to . El método paint () es implementado por la clase
de componentes y se pasa todo el camino hasta AnimatedLogo. However, the method
does not do anything. Sin embargo, el método paint () no hace nada. It exists so that
subclasses of have a method they can use when the display must be redrawn. Existe para
que las subclases de componente tiene un método que pueden utilizar cuando la pantalla
debe ser dibujada.

To override a method, you must start the method in the same way it started in the superclass
it was inherited from. Para reemplazar un método, debe iniciar el método de la misma
manera que comenzó en la superclase se hereda de. A method must remain public, the
value sent back by the method must be the same, and the number and type of arguments to
the method must not change. Un método público debe seguir siendo pública, el valor
devuelto por el método debe ser el mismo, y el número y tipo de argumentos para el
método no debe cambiar.

The method of the class begins as follows: El método paint () de la clase Component
comienza de la siguiente manera:

public void paint(Graphics g) { public void paint


(Graphics g) {

When overrides this method, it must begin with a statement like this: Cuando
AnimatedLogo reemplaza este método, se debe comenzar con una declaración como esta:

public void paint(Graphics screen) { public void paint


(pantalla de gráficos) {

The only difference is in the name of the object, which does not matter when determining
if the methods are created in the same way. La única diferencia está en el nombre del
objeto Graphics, que no importa la hora de determinar si los métodos se crean de la misma
manera. Because both methods are , return no value because of the statement, and have a
object as their only parameter, they match. Debido a que tanto la pintura () los
métodos son públicos, no devuelven ningún valor debido a la declaración de vacío, y
tener un objeto Graphics como su único parámetro, que coinciden.

Workshop: Creating a Subclass Taller: Creación de una subclase


To see an example of inheritance at work, you will create a class called that represents a
point in three-dimensional space. Para ver un ejemplo de la herencia en el trabajo, creará
una clase llamada Point3D que representa un punto en el espacio de tres dimensiones. A
two-dimensional point can be expressed with an (x,y) coordinate. Un punto en dos
dimensiones se puede expresar con una (x, y) de coordenadas. Applets use an (x,y)
coordinate system to determine where text and graphics should be displayed. Applets
utilizar una (x, y) el sistema de coordenadas para determinar donde el texto y los gráficos se
debe mostrar. Three-dimensional space adds a third coordinate, which can be called z. El
espacio tridimensional añade una tercera coordenada, que se puede llamar z.

The class of objects should do three things: La clase de objetos Point3D debe hacer tres
cosas:

 Keep track of an object's (x,y,z) coordinate. Lleve un registro de un objeto (x, y, z) de


coordenadas.
 Move an object to a new (x,y,z) coordinate when needed. Mover un objeto a un nuevo (x,
y, z) coordinar cuando sea necesario.
 Move an object by a certain amount of x, y, and z values as needed. Mover un objeto por
una cierta cantidad de x, y y z valores según sea necesario.

Java already has a standard class that represents two-dimensional points; it's called . Java
ya tiene un estándar de la clase que representa dimensiones en dos puntos, que se llama
Punto. It has two integer variables called and that store a object's (x,y) location. Cuenta
con dos variables de tipo entero llamada x e y que almacenar un objeto Point (x, y). It also
has a method to place a point at the specified location and a method to move an object by
an amount of x and y values. También tiene un método move () para colocar un punto en
la ubicación especificada y un método translate () para mover un objeto por una cantidad
de valores de x e y.

Run your word processor and create a new file called . Ejecutar el procesador de texto y
crear un nuevo archivo llamado Point3D.java. Enter the text of Listing 12.1 into the file,
and save it when you're done. Introduzca el texto del listado 12.1 en el archivo y guárdelo
cuando haya terminado.

Listing 12.1. Listado de 12.1. The full text of Point3D.java. El texto completo de
Point3D.java.
1: import java.awt.*; 2: 3: public class Point3D extends
Point { 4: public int z; 5: 6: public Point3D(int x, int y,
int z) { 7: super.x = x; 8: super.y = y; 9: this.z = z; 10:
} 11: 12: public void move(int x, int y, int z) { 13:
this.z = z; 14: super.move(x, y); 15: } 16: 17: public void
translate(int x, int y, int z) { 18: this.z += z; 19:
super.translate(x, y); 20: } 1: import java.awt .*; 2: 3:
public class Punto {Point3D se extiende 4: public int z; 5:
6: pública Point3D (int x, int y, int z) {7: super.x = x;
8: super.y = y; 9: this.z = z; 10:} 11:: 13 públicos: 12
sin efecto mover (int x int y, int z) {this.z = z; 14:
super.move (x, y); 15:} 16: 17: public void traducir (int
x, int y, int z) {18: this.z + z = 19;: super.translate (x,
y); 20:} 21:}

Compile this file with the compiler tool, and you will have a class you can use in
programs. Compilar este archivo con la herramienta del compilador javac, y tendrá una
clase que puede utilizar en los programas. The class does not have a block statement, so
you cannot run it with the interpreter. La clase Point3D no tiene un main () sentencia de
bloque, por lo que no se puede ejecutar con el intérprete Java.

The class only has to do work that isn't being done by its superclass, . La clase Point3D
sólo tiene que hacer un trabajo que no se está haciendo por su superclase, punto. This
work primarily involves keeping track of the integer variable and receiving it as an
argument to the method, method, and constructor method. Este trabajo implica sobre todo
no perder de vista la variable z entero y que lo recibe como argumento al método move (),
método translate (), y Point3D () método constructor.

All of the methods use the statements and . Todos los métodos de utilización de las
declaraciones y esta super. The statement is used to refer to the current object, so ; in
Line 9 sets the object variable equal to the value that was sent as an argument to the
method in Line 6. La declaración de esta se utiliza para referirse a la actual objeto
Point3D, por lo que this.z = z, en la línea 9 establece la variable de objeto z igual al
valor de z que se envió como un argumento para el método de la línea 6.

The statement refers to the superclass of the current object, . La sentencia super hace
referencia a la superclase del objeto actual, punto. It is used to set variables and call
methods that were inherited by . Se utiliza para establecer las variables y llamar a métodos
que fueron heredados por Point3D. A subclass that overrides a method still can call the
original method with the statement. Una subclase que reemplaza un método todavía se
puede llamar al método original con la sentencia super. An example of this is Line 14,
which calls the method of to set the (x,y) coordinates of the object. Un ejemplo de esto es
la línea 14, que llama al método move () de punto para establecer el (x, y) las coordenadas
del objeto Point3D. Because already is equipped to handle the x and y axes, it would be
redundant for the class of objects to do the same thing. Debido a que el punto ya está
equipado para manejar los ejes X e Y, sería redundante para la clase Point3D de objetos
para hacer lo mismo.

To test out the class that you have compiled, create a program that uses and objects and
moves them around. Para probar la clase Point3D que han recopilado, crear un programa
que utiliza puntos y objetos Point3D y se mueve a su alrededor. Create a new file in your
word processor and enter Listing 12.2 into it. Crear un nuevo archivo en el procesador de
texto y escriba listado 12.2 en el mismo. Save the file as . Guarde el archivo como
TryPoints.java.

Listing 12.2. Listado de 12.2. The full text of TryPoints.java. El texto completo de
TryPoints.java.
1: import java.awt.*; 2: 3: class TryPoints { 4: public
static void main(String[] arguments) { 5: Point object1 =
new Point(11,22); 6: Point3D object2 = new Point3D(7,6,64);
7: 8: System.out.println("The 2D point is located at (" +
object1.x + ", " 9: + object1.y + ")"); 10:
System.out.println("\tIt's being moved to (4, 13)"); 11:
object1.move(4,13); 12: System.out.println("The 2D point is
now at (" + object1.x + ", " 13: + object1.y + ")"); 14:
System.out.println("\tIt's being moved -10 units on both
the x and y 15: axes"); 16: object1.translate(-10,-10); 17:
System.out.println("The 2D point ends up at (" + object1.x
+ ", " 18: + object1.y + ")\n"); 19: 20:
System.out.println("The 3D point is located at (" +
object2.x + ", " 21: + object2.y + ", " + object2.z +")");
22: System.out.println("\tIt's being moved to (10, 22,
71)"); 23: object2.move(10,22,71); 24:
System.out.println("The 3D point is now at (" + object2.x +
", " 25: + object2.y + ", " + object2.z +")"); 26:
System.out.println("\tIt's being moved -20 units on the x,
y and z 27: axes"); 28: object2.translate(-20,-20,-20); 29:
System.out.println("The 3D point ends up at (" + object2.x
+ ", " 30: + object2.y + ", " + object2.z +")"); 31: } 1:
import java.awt .*; 2: 3: {4 TryPoints clase: public static
void main (String [argumentos]) {5: Punto object1 = new
Punto (11,22); 6: Point3D objeto2 nueva Point3D =
( 7,6,64); 7: 8: System.out.println ("El punto está situado
en 2D (" object1.x + + "," 9: + + object1.y ")"); 10:
Sistema. out.println ("\ tit no sea movido al (4, 13)");
11: object1.move (4,13); 12: System.out.println ("El punto
se encuentra ahora en 2D (" + object1.x + "," 13: + +
object1.y ")"); 14: System.out.println ("\ tit no sea
movido -10 unidades tanto en el X e Y 15: los ejes"); 16:
object1.translate ( -10, -10); 17: System.out.println ("El
punto 2D termina en (" + object1.x + "," 18: + object1.y +
") \ n"); 19: 20: System.out.println ("El punto está
situado en 3D (" object2.x + + "," 21: + object2.y + "" +
object2.z +")"); 22: System.out.println ("\ tit no sea
movido al (10, 22, 71)"); 23: object2.move (10,22,71); 24:
System.out.println ("El punto se encuentra ahora en 3D (" +
objeto2. x + "," 25: + object2.y + "" + object2.z +")");
26: System.out.println ("\ tit no sea movido -20 unidades
en el x, y y z 27: ejes "); 28: object2.translate (-20,
-20, -20); 29: System.out.println (" El punto 3D termina en
("+ object2.x +", "30: + objeto2. y + "," + object2.z
+")"); 31:} 32:}

After you compile this file and run it with the interpreter, the following should be shown:
Después de compilar este archivo y ejecutarlo con el intérprete de Java, se debe
demostrar:

The 2D point is located at (11, 22) El punto está situado


en 2D (11, 22)
It's being moved to (4, 13) Se trata de ser trasladado
a (4, 13)
The 2D point is now at (4, 13) El punto se encuentra ahora
en 2D (4, 13)
It's being moved -10 units on both the x and y axes Se
trata de ser movido -10 unidades en ambos ejes y y x
The 2D point ends up at (-6, 3) El punto 2D termina en (-
6, 3)

The 3D point is located at (7, 6, 64) El punto 3D se


encuentra en (7, 6, 64)
It's being moved to (10, 22, 71) Se trata de ser
trasladado a (10, 22, 71)
The 3D point is now at (10, 22, 71) El punto se encuentra
ahora en 3D (10, 22, 71)
It's being moved -20 units on the x, y and z axes Se
trata de ser movido -20 unidades en el X, Y y Z
The 3D point ends up at (-10, 2, 51) El punto 3D termina
en (-10, 2, 51)

Summary Resumen
When people talk about the miracle of birth, they're probably not speaking of the way a
superclass can give birth to subclasses or the way behavior and attributes are inherited in a
hierarchy of classes. Cuando la gente habla sobre el milagro del nacimiento, que
probablemente no está hablando de la forma en que un superclase puede dar a luz a
subclases o el comportamiento y forma de los atributos se heredan de una jerarquía de
clases. However, if the real world worked the same way that object-oriented programming
does, every grandchild of Mozart would get to choose whether to be a brilliant composer.
Sin embargo, si el mundo real trabajado de la misma manera que la programación orientada
a objetos hace, todos los nietos de Mozart podría llegar a optar por ser un compositor
brillante. All descendants of Mark Twain could wax poetic about Mississippi riverboat life.
Todos los descendientes de Mark Twain podría cera poética sobre la vida fluvial del
Mississippi. Every skill your direct ancestors worked to achieve would be handed to you
without an ounce of toil. Todas las habilidades de sus antepasados directos trabajado para
lograr que se entregará a usted sin una onza de esfuerzo.

On the scale of miracles, inheritance isn't quite up to par compared with continuing the
existence of a species and getting a good tax break. En la escala de los milagros, la herencia
no es exactamente a la altura en comparación con la continuación de la existencia de una
especie y obtener una rebaja de impuestos bien. However, it's an effective way to design
software with a minimum of redundant work. Sin embargo, es una manera eficaz de diseño
de software con un mínimo de trabajo redundante.

Q&A Q & A
Q Can a class have more than one superclass so that it inherits additional methods and
behavior? Q ¿Puede una clase tiene más de una superclase para que herede métodos
adicionales y el comportamiento?

A It is possible with some object-oriented programming languages but not Java. Una es
posible con algunos lenguajes de programación orientada a objeto, pero no Java. One of
the goals when Java was developed was to provide a simpler language than an object-
oriented language such as C++, and limiting inheritance to a single superclass was one way
to acheive this. Uno de los objetivos cuando Java se desarrolló era proporcionar un
lenguaje más sencillo que un lenguaje orientado a objetos como C + +, y la limitación de la
herencia a una superclase single fue una forma de lograr esto. You can use a special type
of class called an interface to inherit behavior that isn't received from superclasses. Usted
puede usar un tipo especial de clase llamada una interfaz de heredar un comportamiento
que no se recibe de superclases.

Q Most Java programs created up to this point have not used extends to inherit from a
superclass. Q mayoría de los programas de Java creado hasta el momento no ha
utilizado se extiende a heredar de una superclase. Does this mean they exist outside of
the class hierarchy? ¿Significa esto que existen fuera de la jerarquía de clases?

A All classes that you create in Java are part of the hierarchy because the default
superclass for the programs you write is . A todas las clases que se crean en Java son parte
de la jerarquía, porque la superclase por defecto para los programas que escribir es
objeto. The and methods are part of the behavior that automatically is inherited from .
El es igual a () y toString () son parte del comportamiento que automáticamente
se hereda de Object.
Q When is the full name of a class, such as java.applet.Applet, needed in an extends
clause instead of a shorter name such as Applet? Q ¿Cuál es el nombre completo de una
clase, como java.applet.Applet, necesario en una cláusula se extiende en lugar de un
nombre más corto como applet?

A You must use the full name whenever you don't use an or statement at the beginning
of your program. Un Debe utilizar el nombre completo siempre que no utilice un
java.applet.Applet de importación, o import.java.applet .*; declaración
al comienzo de su programa. The statement is used solely to make it easier to refer to
class names in programs. La declaración de importación se utiliza exclusivamente para
hacer más fácil para hacer referencia a nombres de clase en los programas. Each class of
objects in Java has a full name that identifies the group of classes it belongs to. Cada clase
de objetos en Java tiene un nombre completo que identifica el grupo de clases al que
pertenece. For instance, the class is part of the group of classes. Por ejemplo, la clase de
matemáticas es parte del grupo de las clases java.lang. A group of classes is also
called a package. Un grupo de clases también se conoce como un paquete.

Quiz Quiz
To determine what kind of knowledge you inherited from the past hour's work, answer the
following questions. Para determinar qué tipo de conocimiento que heredó de trabajo de la
última hora es, contesta las siguientes preguntas.

Questions Preguntas

1. If a superclass handles a method in a way you don't want to use in the subclass, what
can you do? 1. Si una superclase maneja un método de una manera que no desee utilizar
en la subclase, ¿qué puedes hacer?

(a) Delete the method in the superclass. (A) Eliminar el método de la superclase.
(b) Override the method in the subclass. (B) Reemplace el método en la subclase.
(c) Write a nasty letter to the editor of the San Jose Mercury News hoping that Java's
developers will read it. (C) Escriba una carta desagradable al editor del San Jose Mercury
News la esperanza de que los desarrolladores de Java lo leerá.
2. Which of the following is not a superclass of ? 2. ¿Cuál de los siguientes no es una
superclase de Applet?

(a) (A) de diálogo


(b) (B) de contenedores
(c) (C) Componente

3. What statement can you use to refer to the methods and variables of a superclass? 3.
¿Qué declaración se puede utilizar para referirse a los métodos y variables de un
superclase?

(a) (A) el presente


(b) (B) llamar a
(c) (C) super

Answers Respuestas

1. b. 1. B. Because you can override the method, you don't have to change any aspect of
the superclass or the way it works. Debido a que puede reemplazar el método, usted no
tiene que cambiar cualquier aspecto de la superclase o la forma en que funciona.

2. a. has some common superclasses with , but it isn't a superclass, so does not inherit
any behavior or attributes from it. 2. A. diálogo tiene superclases común con applet,
pero no es un superclase, por lo que Applet no hereda ningún comportamiento o los
atributos de la misma.

3. c. 3. C. A statement refers to the current object, and refers to the superclass. Una
declaración se refiere al objeto actual, y super hace referencia a la superclase.

Activities Actividades
If a fertile imagination has birthed in you a desire to learn more, you can spawn more
knowledge of inheritance with the following activities: Si una fértil imaginación ha dado a
luz en ti el deseo de aprender más, puede generar más conocimiento de la herencia con las
siguientes actividades:

 Create a class that adds a coordinate to the (x,y,z) coordinate system created by the
class. Crear una clase Point4D que añade una camiseta de coordenadas a la (x, y, z) el
sistema de coordenadas creada por la clase Point3D. The coordinate stands for time, so
you need to ensure that it does not get set to a negative value. El t coordinar las siglas de
tiempo, por lo que necesita para asegurarse de que no se establece en un valor negativo.
 Take the members of a football team's offense--lineman, wide receiver, tight end, running
back, and quarterback. Tome los miembros de la infracción de un equipo de fútbol - juez
de línea, receptor, ala cerrada, el corredor, y el mariscal de campo. Design a hierarchy of
classes that represent the skills of these players, putting common skills higher up in the
hierarchy. Diseñar una jerarquía de clases que representan las habilidades de estos
jugadores, poniendo habilidades comunes más arriba en la jerarquía. For example,
blocking is behavior that should probably be inherited by the linemen and tight end
classes, and speed is something that should be inherited by wide receivers and running
backs. Por ejemplo, el bloqueo es un comportamiento que probablemente debería ser
heredado por los linieros y clases de ala cerrada, y la velocidad es algo que debe ser
heredados por los receptores abiertos y corredores.

 13 horas
o Aprender applets de trabajo
 Standard Methods Applet
 El método paint ()
 El método init ()
 El inicio () y stop () Los métodos
 El método destroy ()
 Poner un applet en una página Web
 Un applet de ejemplo
 Listado de 13.1. El texto completo de BigDebtApplet.java.
 Uso de la drawString () Método
 Figura 13.1.
 Prueba de la BigDebtApplet Programa
 Listado de 13.2. El texto completo de BigDebtApplet.html.
 Figura 13.2.
 Taller: Mejora el Proyecto BigDebtApplet
 Listado de 13.3. El texto completo de Ouch.java.
 Listado de 13.4. El texto completo de Ouch.html.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 13 13 horas

Learning How Applets Work Aprender applets de


trabajo

Now that Java is making the transition from a child prodigy to an established language, it is
being used for all kinds of large-scale business software and other applications. Ahora que
Java es hacer la transición de niño prodigio a un lenguaje establecido, que está siendo
utilizado para todo tipo de software de negocios a gran escala y otras aplicaciones.
However, the core of interest in the language remains in a new type of program that Java
made possible: the applet. Sin embargo, el núcleo de interés en la lengua se mantiene en un
nuevo tipo de programa de Java que hace posible: el applet. Applets are programs designed
to run as part of a World Wide Web page. Los applets son programas diseñados para
ejecutarse como parte de una página del World Wide Web. When a Java applet is
encountered on a page, it is downloaded to the user's computer and begins running. Cuando
un applet de Java se encuentra en una página, se descarga al ordenador del usuario y en
funcionamiento comienza.

During this hour you'll be introduced to applet programming. Durante esta hora se le
presentó al subprograma de programación. Programming applets with Java is much
different from creating applications with Java. Programación de applets de Java es muy
diferente de la creación de aplicaciones con Java. Because applets must be downloaded off
a page each time they are run, applets are smaller than most applications to reduce
download time. Debido a que los applets se deben descargar de una página cada vez que se
ejecuta, los applets son más pequeños que la mayoría de las aplicaciones para reducir el
tiempo de descarga. Also, because applets run on the computer of the person using the
applet, they have numerous security restrictions in place to prevent malicious or damaging
code from being run. Además, como applets se ejecutan en el equipo de la persona que
utiliza el applet, tienen numerosas restricciones de seguridad para evitar que el código
malicioso o dañino que se ejecuten.

The following topics will be covered: Los siguientes temas serán cubiertos:

 Setting up an applet La creación de un applet


 Displaying information in an applet Visualización de la información en un applet
 Stopping and starting an applet Detener y comenzar un applet
 Putting an applet on a Web page Poner un applet en una página Web
 Using applet HTML tags and attributes Usando applet de etiquetas HTML y atributos

Standard Applet Methods Standard Methods Applet


All applets are subclasses of the subclass, which is part of the package of classes. Todos
los applets son subclases de la subclase Applet, que forma parte del paquete java.applet
de clases. Being part of this hierarchy enables the applets that you write to use all the
behavior and attributes they need to be run off of a World Wide Web page. Ser parte de
esta jerarquía permite a los applets que se escribe a utilizar todos los comportamientos y
atributos que deben ser ejecutados fuera de una página del World Wide Web. Before you
begin writing any other statements in your applets, they will be able to interact with a Web
browser, load and unload themselves, redraw their window in response to changes in the
browser window, and other functions. Antes de empezar a escribir cualquier otra
declaración en los applets, que será capaz de interactuar con un navegador Web carga y
descarga de sí mismos, volver a dibujar la ventana de su respuesta a los cambios en la
ventana del navegador, y otras funciones.

In applications, programs begin running with the first statement of the block statement and
end with the last that closes out the block. En las aplicaciones, los programas empezarán
con la primera declaración de los) bloque de instrucciones (principal y termina con la
última} que cierra el bloque. There is no method in a Java applet, so there is no set
starting place for the program. No hay () el método principal en un applet de Java, así
que no hay lugar de partida establecido para el programa. Instead, an applet has a group of
standard methods that are handled in response to specific events as the applet runs. En
cambio, un applet tiene un grupo de métodos estándares que se manejan en respuesta a
eventos específicos como el applet se ejecuta.
The following are the events that could prompt one of the applet methods to be handled:
Los siguientes son los acontecimientos que podrían llevar uno de los métodos del applet,
para ser manipulados:

 The program is loaded for the first time El programa se carga por primera vez
 Something happens that requires the applet window to be redisplayed Sucede algo que
requiere la ventana del applet se vuelve a mostrar
 The program stops at a specific point El programa se detiene en un punto específico
 The program restarts after a stop Se reinicia el programa después de una parada
 The program is unloaded as it finishes running El programa se descarga, ya que termina de
ejecutarse

The following is an example of a bare-bones applet: El siguiente es un ejemplo de un applet


escueto:

public class Skeleton extends java.applet.Applet { public


class esqueleto se extiende java.applet.Applet {
// program will go here / / Programa haga clic aquí
} }

Note that unlike applications, applet class files must be in order to work. Tenga en cuenta
que a diferencia de las aplicaciones, archivos de clase applet debe ser público para poder
trabajar. (However, if your applet uses other class files of your own creation, they do not
have to be declared .) This class inherits all of the methods that are handled automatically
when needed: , , , , and . (Sin embargo, si el applet utiliza archivos de clase de otros de
su propia creación, que no tienen que ser declaradas públicas.) Esta clase hereda todos
los métodos que se manejan de forma automática cuando es necesario: init (), pintura
(), start () , stop () y destroy (). However, none of these methods do anything.
Sin embargo, ninguno de estos métodos de hacer cualquier cosa. If you want something to
happen in an applet, you have to override these methods with new versions in your applet
program. Si quieres que algo suceda en un applet, usted tiene que reemplazar estos métodos
con nuevas versiones de su programa del applet. The two methods you will override most
often are and . Los dos métodos que se anula con más frecuencia son paint () e init
().

The paint() Method El método paint ()

The method should be a part of almost every applet that you write because you can't
display anything without it. El método paint () debe ser una parte de casi todos los applet
que escribe porque no puede mostrar nada sin ella. Whenever something needs to be
displayed or redisplayed on the applet window, the method handles the task. Cada vez que
algo se tiene que mostrar o vuelve a mostrar en la ventana del applet, el método paint () se
encarga de la tarea. You also can force to be handled with the following statement:
También puede forzar la pintura () para ser manejado con la siguiente declaración:

repaint(); repaint ();

Otherwise, the main reason occurs is when something is changed in the browser or the
operating system running the browser. De lo contrario, la pintura principal razón () se
produce cuando algo cambia en el navegador o el sistema operativo que ejecuta el
navegador. For example, if a Windows 95 user minimizes a Web page containing an applet,
the method will be called to redisplay everything that was on-screen in the applet when the
applet is later restored to full-size. Por ejemplo, si un usuario de Windows 95 reduce al
mínimo una página Web que contiene un applet, el método paint () será llamado para
volver a mostrar todo lo que estaba en pantalla en el applet cuando el applet es tarde
restaurado a tamaño completo.

Unlike the other methods that you will be learning about during this hour, takes an
argument. A diferencia de los otros métodos que usted aprenderá acerca en esta hora, paint
() toma un argumento. The following is an example of a simple method: El siguiente es un
ejemplo de una pintura sencilla () método:

public class paint(Graphics screen) { pintura clase


pública (pantalla de gráficos) {
// display statements go here / / Sentencias pantalla
haga clic aquí
} }

The argument is a object. El argumento es un objeto Graphics. The class of objects is


used to handle all attributes and behavior that are needed to display text, graphics, and other
information on-screen. La clase Graphics de objetos se utiliza para controlar todos los
atributos y comportamientos que son necesarios para mostrar textos, gráficos, y otra
información en la pantalla. (You'll learn about , one of the methods of the class, later this
hour.) If you are using a object in your applet, you have to add the following statement
before the statement at the beginning of the source file: (Usted aprenderá acerca de
drawString (), uno de los métodos de la clase Graphics, más tarde esta hora.) Si está
utilizando un objeto Graphics en el applet, usted tiene que agregar la siguiente sentencia
import antes de la declaración de clase al principio del archivo de origen:

import java.awt.Graphics; java.awt.Graphics de


importación;
If you are using several classes that are a part of the package of classes, use the statement
instead. Si está utilizando varias clases que forman parte del paquete java.awt de clases, el
uso de la instrucción import java.awt .*; en su lugar. It makes all of these classes
available for use in your program. Hace que sea una de estas clases disponibles para su uso
en el programa.

The init() Method El método init ()

The method is handled once--and only once--when the applet is run. El método init () se
maneja una vez - y sólo una vez - cuando el applet se esta ejecutando. As a result, it's an
ideal place to set up values for any objects and variables that are needed for the applet to
run successfully. Como resultado, es un lugar ideal para establecer los valores de los
objetos y las variables que se necesitan para el applet se ejecute correctamente. This
method is also a good place to set up fonts, colors, and the screen's background color. Este
método es también un buen lugar para establecer las fuentes, colores, y el color de la
pantalla de fondo.

Caution: Variables and objects should not be created inside an method because they will only
exist within the scope of that method. Atención: Las variables y los objetos no se debe crear
dentro de un método init () porque sólo existen en el ámbito de aplicación de ese método. For
example, if you create an integer variable called inside the method and try to use it in the
method, you'll get an error when you attempt to compile the program. Por ejemplo, si crea una
variable entera llamada displayRate dentro del método init () y tratar de utilizarlo en el
método paint (), obtendrá un error al intentar compilar el programa. Create any variables that
you need to use throughout a class as object variables right after the statement and before any
methods. Crear las variables que es necesario utilizar toda una clase como variables de objeto
después de la declaración de la clase y antes de cualquier método.

The start() and stop() Methods El inicio () y stop () Los métodos

At any point when the applet program starts running, the method will be handled. En
cualquier momento en que el programa del applet se pone en marcha, el método start () se
manejará. When a program first begins, the method is followed by the method. Cuando un
programa comienza el primer, el método init () es seguido por el método start (). After
that, in many instances there will never be a cause for the method to be handled again.
Después de eso, en muchos casos no habrá nunca una causa para el inicio () para
manejar de nuevo. In order for to be handled a second time or more, the applet has to stop
execution at some point. Con el fin de start (), para ser manipulados por segunda vez o
más, el applet tiene que detener la ejecución en algún momento.
The method is called when an applet stops execution. El método stop () es llamado
cuando el applet se detiene la ejecución. This event can occur when a user leaves the Web
page containing the applet and continues to another page. Este evento puede ocurrir cuando
un usuario abandona la página Web que contiene el applet y sigue a otra página. It also can
occur when the method is called directly in a program. También puede ocurrir cuando el
método stop () se llama directamente en un programa.

In the programs that you'll write as you're starting out with the Java language, and will
have the most use in animation. En los programas que voy a escribir como estás empezando
con el lenguaje Java, start () y stop () tendrá el mayor uso en la animación. You'll learn
more about this use during Hour 18, "Creating Animation." Usted aprenderá más acerca de
este uso durante la hora 18, "Creación de animaciones."

The destroy() Method El método destroy ()

The method is an opposite of sorts to the method. El método destroy () es una especie de
frente al método init (). It is handled just before an applet completely closes down and
completes running. Se maneja justo antes de un applet completamente cierra y completa
ejecución. This method is used in rare instances when something has been changed during a
program and should be restored to its original state. Este método se utiliza en casos raros
cuando algo ha cambiado en un programa y debe ser restaurado a su estado original. It's
another method that you'll use more often with animation than with other types of
programs. Es otro método que utilizará con más frecuencia con la animación que con otros
tipos de programas.

Putting an Applet on a Web Page Poner un applet en una página Web


Applets are placed on a Web page in the same way that anything unusual is put on a page:
HTML commands are used to describe the applet, and the Web browser loads it along with
the other parts of the page. Los applets se colocan en una página Web de la misma manera
que cualquier cosa inusual se pone en una página: los comandos HTML se utiliza para
describir el applet, y el explorador Web carga que junto con las otras partes de la página. If
you have used HTML to create a Web page, you know that it's a way to combine formatted
text, images, sound, and other elements together. Si ha utilizado HTML para crear una
página Web, usted sabe que es una manera de combinar texto con formato, imágenes,
sonido y otros elementos juntos. HTML uses special commands called tags that are
surrounded by < and > marks, including for the display of images, for the insertion of a
paragraph mark, and to center the text that follows until a tag is reached. HTML utiliza
comandos especiales llamadas etiquetas que están rodeadas por <y> las marcas, incluyendo
<IMG> para la visualización de imágenes, <P> para la inserción de una marca de párrafo, y
<CENTER> para centrar el texto que sigue hasta que un </ CENTRO etiquetas> que se
llegó.
The performance of some of these HTML tags can be affected by attributes that determine
how they function. El rendimiento de algunas de estas etiquetas HTML pueden ser
afectados por los atributos que determinan su funcionamiento. For example, is an attribute
of the tag, and it provides the name of the image file that should be displayed. Por ejemplo,
SRC es un atributo de la etiqueta <IMG>, y proporciona el nombre del archivo de imagen
que debe mostrarse. The following is an example of an tag: El siguiente es un ejemplo de
una etiqueta <IMG>:

<IMG SRC="Graduation.jpg"> <IMG SRC="Graduation.jpg">

You can place applets on a Web page by using an tag and several attributes. Usted puede
poner applets en una página Web mediante una etiqueta <APPLET> y varios atributos. The
following is an example of the HTML required to put an applet on a page: El siguiente es
un ejemplo del código HTML necesario para poner un applet en una página:

<APPLET CODE="StripYahtzee.class" CODEBASE="javadir"


HEIGHT=300 WIDTH=400> Sorry, no dice ... <APPLET
CODE="StripYahtzee.class" CODEBASE="javadir" HEIGHT=300
WIDTH=400> Lo sentimos, no dice ... this requires a Java-
enabled browser. esto requiere un navegador con Java.
</APPLET> </ APPLET>

The attribute identifies the name of the applet's class file. El atributo de código identifica
el nombre de la clase que se aplique el archivo. If more than one class file is being used
with an applet, should refer to the main class file that is a subclass of the class. Si más de
un archivo de clase se utiliza con un applet, CÓDIGO debe hacer referencia al archivo de
clase principal que es una subclase de la clase Applet.

If there is no attribute, all files associated with the applet should be in the same directory as
the Web page that loads the program. should contain a reference to the directory or
subdirectory where the applet and any related files can be found. Si no hay ningún atributo
CODEBASE, todos los archivos asociados con el applet debe estar en el mismo directorio que
la página Web que carga el programa. CODEBASE debe contener una referencia al directorio
o subdirectorio donde y de todo los archivos se puede encontrar el applet. In the preceding
example, indicates that the applet can be found in the subdirectory. En el ejemplo
anterior, CODEBASE indica que el applet StripYahtzee se puede encontrar en el
subdirectorio javadir.

The and attributes designate the exact size of the applet window on the Web page and
must be big enough to handle the things you are displaying in your applet. Los atributos
HEIGHT y WIDTH designar el tamaño exacto de la ventana del applet en la página web y
debe ser lo suficientemente grande como para manejar las cosas que están mostrando en el
applet.
In between the opening tag and the closing tag, you can provide an alternate of some kind
for Web users whose browser software cannot run Java programs. En medio de la etiqueta
<APPLET> la apertura y el cierre </ APPLET> etiquetas, puede proporcionar una alternativa
de algún tipo para los usuarios cuyo navegador web de software no se puede ejecutar
programas Java. In the preceding example, a line of text is displayed indicating that Java is
required to play the game. En el ejemplo anterior, una línea de texto se muestra que indica
que Java se requiere para jugar el juego.

Another attribute that you can use with applets is . Otro atributo que se puede utilizar con
los applets es ALIGN. It designates how the applet will be displayed in relation to the
surrounding material on the page, including text and graphics. Se designa como el applet se
muestra en relación con el material que rodea en la página, incluyendo textos y gráficos.
Values include , , and others. Los valores incluyen align = "left", ALIGN =
"derecha", y otros.

A Sample Applet Un applet de ejemplo


The first program that you wrote was a Java application that revealed a depressing fact
about the US financial condition--one minute's worth of the national debt. El primer
programa que escribí fue una aplicación Java que reveló un hecho deprimente sobre el
estado financiero de EE.UU. - vale la pena un minuto de la deuda nacional. If it isn't too
painful a prospect, you'll take a look at how applets are structured by writing the same
program as an applet. Si no es demasiado dolorosa perspectiva, se le eche un vistazo a
cómo están estructurados los applets por escrito el mismo programa como un applet.

Load your word processor and create a new file called . Cargue el procesador de texto y
crear un nuevo archivo llamado BigDebtApplet.java. Enter the text of Listing 13.1 into
the file and save it when you're done. Introduzca el texto del listado 13.1 en el archivo y
guardarlo cuando haya terminado.

Listing 13.1. Listado de 13.1. The full text of BigDebtApplet.java. El texto completo de
BigDebtApplet.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class BigDebtApplet extends java.applet.Applet
{ 3: public class BigDebtApplet extiende java.applet.Applet
{
4: int debt; 4: la deuda int;
5: 5:
6: public void init() { 6: public void init () {
7: debt = 59000000; 7: la deuda = 59000000;
8: debt = debt / 1440; 8: la deuda = Deuda / 1440;
9: } 9:}
10: 10:
11: public void paint(Graphics screen) { 11: public void
paint (pantalla de gráficos) {
12: screen.drawString("A minute's worth of debt is $" +
debt, 5, 50); 12: screen.drawString ("Un minuto de valor de
la deuda es de $" + de la deuda, 5, 50);
13: } 13:}
14:}

This applet does not need to use the , , or methods, so they are not included in the
program. Este applet no es necesario utilizar el start (), stop (), o destruir () los
métodos, por lo que no están incluidos en el programa. Compile the program with the
compiler tool. Compilar el programa con la herramienta del compilador javac.

Using the drawString() Method Uso de la drawString () Método

The method is one of the things you can use in a method to display information. El
drawString () es una de las cosas que usted puede utilizar en un método paint () para
mostrar la información. It is similar in function to statement, which cannot be used in an
applet. Es una función similar a System.out.println () declaración, que no se puede
utilizar en un applet. The method is part of the class, so you must use it in the method or
another method that has the object that was sent to the method. El drawString () es
parte de la clase Graphics, por lo que debe utilizar en el método paint () u otro método
que tiene el objeto Graphics que se envió a la pintura () método.

The following three arguments are sent to : Los siguientes tres argumentos son enviados a
drawString ():

 The text to display, which can be several different strings and variables strung together
with the operator El texto que se muestra, lo que puede haber varias cadenas diferentes y
variables unidas por el operador +
 The x position (in an (x,y) coordinate system) where the string should be displayed La
posición x (en una (x, y) el sistema de coordenadas) cuando debería ser la cadena que se
muestra
 The y position where the string should be displayed La posición y que debe ser la cadena
que se muestra

The (x,y) coordinate system in an applet is used with several methods. La (x, y) el sistema
de coordenadas en un applet se utiliza con varios métodos. It begins with the (0,0) point in
the upper-left corner of the applet window. Se inicia con el punto (0,0) en la esquina
superior izquierda de la ventana del applet. Figure 13.1 shows how the (x,y) coordinate
system works in conjunction with the statement on Line 12 of . La figura 13.1 muestra
cómo la (x, y) coordinar los trabajos del sistema en relación con la declaración de la Línea
12 del BigDebtApplet.java.

Figura 13.1. Drawing a string to an (x,y) position. Dibujo de una cadena a un x, y) la


posición (.

Testing the BigDebtApplet Program Prueba de la BigDebtApplet Programa

Although you have compiled the program into a class file, you cannot run it using the
interpreter. A pesar de que haya compilado el programa BigDebtApplet en un archivo de
clase, no se puede ejecutar utilizando el intérprete Java. If you do, you'll get an error
message such as the following: Si lo hace, obtendrá un mensaje de error como los
siguientes:

In class BigDebtApplet: void main(String argv[]) is not


defined En la clase de BigDebtApplet: void main (String
argv []) no está definido

The error occurs because the interpreter runs Java applications beginning with the first
statement of the block. El error se produce porque el intérprete de Java se ejecuta
aplicaciones Java a partir de la primera declaración de la main () del bloque. To run an
applet, you need to create a Web page that loads the applet. Para ejecutar un applet, es
necesario crear una página Web que carga el applet. To create a Web page, open up a new
file on your word processor and call it . Para crear una página Web, abra un nuevo archivo
en el procesador de textos y lo llaman BigDebtApplet.html. Enter Listing 13.2 and then
save the file. Introduzca Listado 13.2 y guarde el archivo.

Listing 13.2. Listado de 13.2. The full text of BigDebtApplet.html. El texto completo de
BigDebtApplet.html.

1: <html> 1: <html>
2: <head> 2: <head>
3: <title>The Big Debt Applet</title> 3: <title> La Gran
Deuda applet </ title>
4: </head> 4: </ head>
5: <body bgcolor="#000000" text="#FF00FF"> 5:
bgcolor="#000000" <body text="#FF00FF">
6: <center> 6: <center>
7: This a Java applet:<br> 7: Este applet de Java a: <br>
8: <applet code="BigDebtApplet.class" height=150
width=300> width=300> height=150: 8 <applet
code="BigDebtApplet.class"
9: You need a Java-enabled browser to see this. 9: Se
necesita un navegador compatible con Java para ver esto.
10: </applet> 10: </ applet>
11: </body> 11: </ body>
12: </ html>

Normally, you can test the Java applets that you write using the tool that comes with the
Java Developer's Kit. Normalmente, usted puede probar los applets de Java que se escribe
con la herramienta appletviewer que viene con Java Developer Kit. You can see the
output of the applet by typing the following: Usted puede ver la salida del applet
BigDebtApplet escribiendo lo siguiente:

appletviewer BigDebtApplet.html appletviewer


BigDebtApplet.html

However, only runs the applets that are included in a Web page and does not handle any of
the other elements such as text and images. Sin embargo, sólo appletviewer ejecuta los
applets que se incluyen en una página Web y no controla ninguno de los otros elementos,
como texto e imágenes. To see the file, load it into a browser that can handle Java
programs, such as the current versions of Microsoft Internet Explorer and Netscape
Navigator. Para ver el archivo BigDebtApplet.html, cargarlo en un navegador que pueda
manejar los programas Java, como las versiones actuales de Microsoft Internet Explorer y
Netscape Navigator. Figure 13.2 shows a screen capture of loaded into Internet Explorer.
La figura 13.2 muestra una captura de pantalla de BigDebtApplet.html cargado en
Internet Explorer.

Figura 13.2. The program on a Web page displayed by Microsoft Internet Explorer. El
programa BigDebtApplet en una página Web que se muestra en Microsoft Internet
Explorer.

Caution: At the time of this writing, the current versions of Netscape Navigator and Microsoft
Internet Explorer do not support any new feature introduced with version 1.1 of the Java
language. Atención: En el momento de escribir esto, las versiones actuales de Netscape Navigator
y Microsoft Internet Explorer no son compatibles con cualquier nueva característica introducida
con la versión 1.1 del lenguaje Java. This hour's applet works, but many others in later hours do
not. Las obras de este subprograma hora, pero muchos otros en las horas posteriores no. Use the
tool to run applets unless you know your browser software fully supports Java 1.1. Utilice la
herramienta appletviewer para ejecutar applets a menos que sepa su software de navegador
totalmente compatible con Java 1.1.

Workshop: Enhancing the BigDebtApplet Project Taller: Mejora el Proyecto


BigDebtApplet
As a short exercise to close out the hour, you'll enhance the program by making it
accumulate the debt over time, displaying how much the national debt grows each second.
Como un breve ejercicio para cerrar la hora, usted mejorar el programa BigDebtApplet por
lo que se acumulan la deuda a través del tiempo, mostrando la cantidad de la deuda
nacional crece cada segundo.

Open up a new file with your word processor and call it . Abra un archivo nuevo con su
procesador de textos y lo llaman Ouch.java. Enter Listing 13.3 and save the file when
you're done. Introduzca Listado 13.3 y guardar el archivo cuando haya terminado.

Listing 13.3. Listado de 13.3. The full text of Ouch.java. El texto completo de Ouch.java.

1: import java.awt.*; 1: import java.awt .*;


2: import java.util.*; 2: importar java.util .*;
3: 3:
4: public class Ouch extends java.applet.Applet { 4:
public class Ay extiende java.applet.Applet {
5: int debt = 683; 5: La deuda int = 683;
6: int totalTime = 1; 6: totalTime int = 1;
7: 7:
8: public void paint(Graphics screen) { 8: public void
paint (pantalla de gráficos) {
9: screen.drawString(totalTime + " second's worth of debt
is $" 9: screen.drawString (totalTime + "segundo valor de
la deuda es de $"
10: + (debt * totalTime), 5, 30); 10: + (deuda *
totalTime), 5, 30);
11: for (int i = 0; i < 5000000; i++); 11: for (int i = 0;
i <5000000; i + +);
12: totalTime++; 12: totalTime + +;
13: repaint(); 13: repaint ();
14: } 14:}
15:}
This file uses an empty loop in Line 11 to approximate the passage of a second's time. Este
archivo utiliza un vacío para el bucle de la línea 11 a la aproximación de la aprobación de
la segunda de una hora. Whether it actually pauses for a second depends on your processor
speed and anything else that's currently running on your computer. Si realmente hace una
pausa de un segundo depende de la velocidad del procesador y todo lo que actualmente se
ejecutan en el equipo. The call to in Line 13 at the end of the method causes the method
to be called again, starting over at the beginning of the method on Line 9. La llamada a
repaint () en la línea 13 al final del método paint () hace que la pintura () para llamar
de nuevo, empezar de nuevo a principios del método de la línea 9.

To try out the program, you need to compile it with the compiler tool and create a Web
page that runs the applet. Para probar el programa, es necesario compilarlo con la
herramienta del compilador javac y crear una página Web que se ejecuta el applet. Create
a new file on your word processor and enter Listing 13.4 into the file. Crear un nuevo
archivo en el procesador de texto y escriba Listado de 13,4 en el archivo. Save it when
you're done. Guardar cuando hayas terminado.

Listing 13.4. Listado de 13.4. The full text of Ouch.html. El texto completo de Ouch.html.

1: <applet code="Ouch.class" height=300 width=300> 1:


<applet code="Ouch.class" height=300 width=300>
2: </ applet>

This Web page only contains the HTML tags that are required to add an applet to a page.
Esta página web sólo contiene las etiquetas HTML que están obligados a añadir un applet a
una página. Load this Web page into the tool by typing the following at a command line:
Carga esta página web en la herramienta appletviewer, escriba lo siguiente en una línea
de comandos:

appletviewer Ouch.html appletviewer Ouch.html

You will see an applet that begins with the calculation of a second's worth of debt. Usted
verá un applet que comienza con el cálculo del valor de un segundo de la deuda. At a
regular interval, another second's debt will be added. En un intervalo regular, la deuda ni un
segundo se añadirá. The following is an example of the text that is displayed as the applet
runs: El siguiente es un ejemplo del texto que se muestra como se ejecuta el applet:

13 second's worth of debt is $8879 13 segundos es el valor


de la deuda es $ 8879
Summary Resumen
This hour was the first of several that will focus on the development of applets. Esta hora
fue el primero de varios que se centrará en el desarrollo de applets. You got a chance to
become acquainted with the and methods, which you will be using frequently when you're
developing applets. Usted tuvo la oportunidad de familiarizarse con el init () y paint ()
métodos, que va a utilizar con frecuencia cuando se está desarrollando applets.

Writing applets is a good way for beginners to develop their skills as Java programmers for
the following reasons: Escribir applets es una buena manera para los principiantes a
desarrollar sus habilidades como programadores de Java por las siguientes razones:

 Applets are usually smaller in scope, making their creation a less daunting task. Los applets
son generalmente más pequeños en su alcance, por lo que su creación una tarea menos
desalentadora.
 You can find thousands of sample applets on the World Wide Web, including many with
the source file available to learn from. Usted puede encontrar miles de applets de ejemplo
en la World Wide Web, muchos de ellos con el archivo de código fuente disponible para
aprender.
 You can make applets available to a global audience at low to no cost through the Web,
exposing your work to more people who can offer comments and suggestions. Usted
puede hacer applets disponibles para una audiencia global a bajo o ningún costo a través
de la Web, exponiendo su trabajo a más personas que pueden ofrecer comentarios y
sugerencias.

There's a "code war" of sorts afoot among the hundreds of Java programmers who are
putting their work on the Web, and many new applets announced on sites like demonstrate
new things that can be done with the language. Hay un "código de guerra" de clases en pie
entre los cientos de programadores de Java que están poniendo su trabajo en la Web, y
muchos nuevos applets anunció en sitios como http://www.jars.com demostrar nuevas
cosas que se pueden hacer con la idioma.

Q&A Q & A
Q Can arguments be sent to applets, as they can to applications? Q ¿argumentos se
enviará a los applets, ya que pueden a las aplicaciones?

A You can't use arguments, but parameters serve a similar function to arguments in applet
programming. A Usted no puede utilizar argumentos, pero los parámetros de una función
similar a los argumentos en la programación del applet. You can use the tag with its and
attributes to send parameters to Java programs. Usted puede utilizar la etiqueta <PARAM>
con su nombre y valor los atributos para enviar los parámetros a los programas de Java.
It's described fully in Hour 15, "Sending Parameters to Applets." Es descrito plenamente en
la hora 15, "El envío de los parámetros de applets".

Q Is there a reason why the CODEBASE attribute should be used in an <APPLET> tag? Q
¿Hay una razón por la cual debe ser el atributo CODEBASE utilizados en una etiqueta
<APPLET>?

A If all Java programs are grouped into their own subdirectory, as indicated by , this
structure might improve the way a Web site is organized, but there's no other reason why
using is better than omitting it. A Si todos los programas de Java se agrupan en su propio
subdirectorio, según lo indicado por CODEBASE, esta estructura podría mejorar la forma
organizada es un sitio Web, pero no hay otra razón por la CODEBASE usando es mejor que
la omisión de la misma. The choice is a matter of personal preference. La elección es una
cuestión de preferencia personal.

Q What happens if the height and width specified for an applet don't leave enough room
for the information that is displayed in the paint() method? Q ¿Qué pasa si la altura y el
ancho especificado para un applet no dejar suficiente espacio para la información que se
muestra en el método paint ()?

A The information will be drawn off-screen beyond the edges of the applet window and
won't be visible at any point while the applet runs. Una información de la que se extrae de
pantalla más allá de los bordes de la ventana del applet y no será visible en cualquier
momento mientras se ejecuta el applet. Choosing the right dimensions for an applet is
largely a matter of trial-and-error until you find the right size for both the and attributes
of the tag. Selección de las dimensiones adecuadas para un applet es en gran medida una
cuestión de prueba y error hasta encontrar el tamaño adecuado para ambos y los
atributos ALTURA ANCHO de la etiqueta <APPLET>. Fortunately, you can change the Web
page's HTML without having to recompile the Java program. Afortunadamente, usted
puede cambiar HTML de la página Web sin tener que recompilar el programa Java.

Quiz Quiz
The following questions test your knowledge of applets. Las siguientes preguntas prueba
tus conocimientos de los subprogramas.

Questions Preguntas

1. What type of argument is used with the method? 1. ¿Qué tipo de argumento se utiliza
con el método paint ()?

(a) A object (A) Un objeto gráfico


(b) A Boolean variable (B) Una variable booleana
(c) None (C) Ninguna

2. Which method is handled right before an applet finishes running? 2. ¿Qué método se
maneja justo antes de un applet termina de ejecutarse?

(a) (A) disminución de ()


(b) (B) destruir ()
(c) (C) desaparición ()
3. Why can't all variables needed in an applet be created inside the method? 3. ¿Por qué
no todas las variables necesarias en un applet se crea dentro del método init ()?

(a) The scope of the variables would be limited to the method only. (A) El ámbito de
aplicación de las variables se limitaría a la única.
(b) Federal legislation prohibits it. (B) la legislación federal lo prohíbe.
(c) They can be created there without any problems. (C) Se pueden crear allí sin ningún
problema.

Answers Respuestas

1. a. 1. A. The object keeps track of the behavior and attributes needed to display things
on-screen in the applet window. El objeto Graphics mantiene un seguimiento del
comportamiento y los atributos necesarios para mostrar cosas en pantalla en la ventana
del applet.

2. b. 2. B.

3. a. 3. A. Variables that are used in more than one method of a class should be created
right after the class statement but before any methods begin. Las variables que se utilizan
en más de un método de una clase se debe crear inmediatamente después de la
declaración de clase, pero antes de iniciar cualquier método.

Activities Actividades
You can apply your applet programming knowledge with the following activity: Usted
puede aplicar sus conocimientos de programación applet con la siguiente actividad:

 Create an applet that displays the values of an array in the applet window and adds one to
some of the values each time the applet is repainted. Crear un applet que muestra los
valores de una matriz en la ventana del applet y agrega uno a algunos de los valores cada
vez que se redibuja el applet. Drag other windows atop the running version of this
program to force it to require repainting. Arrastre otras ventanas encima de la versión de
funcionamiento de este programa para obligarlo a requerir volver a pintar. This exercise
demonstrates how the method is called for behind the scenes. Este ejercicio muestra
cómo el método paint () se llama por detrás de las escenas.

 14 horas
o Creación de un applet de rosca
 A-Link Applet Rotatorio
 La clase Declaración
 Configuración de variables
 A partir de init ()
 La captura de errores al configurar las direcciones URL
 Manejo de las actualizaciones de pantalla en el método paint ()
 A partir del hilo
 La ejecución del hilo
 Parar el Thread
 Manejo de clics de ratón
 Taller: Enlaces Rotatorio
 Listado de 14.1. El texto completo de Revolve.java.
 Listado de 14.2. El texto completo de Revolve.html.
 Figura 14.1.
 Figura 14.2.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 14 14 horas

Creating a Threaded Applet Creación de un applet de


rosca

A computer term that is used often to describe the hectic pace of daily life is multitasking.
Es un término informático que se utiliza a menudo para describir el ritmo agitado de la vida
cotidiana es multitarea. (Another term is used more often around here, but the editors asked
that it be omitted.) Multitasking means to do more than one thing at once--such as surfing
the Web at your desk while participating in a conference call and using the Buttmaster
exercise device to achieve more shapely shanks. (Otro término que se utiliza más a menudo
por aquí, pero los editores pidió que se omite.) Multitarea significa hacer más de una cosa a
la vez - como navegar por la web en su escritorio mientras participaba en una conferencia
telefónica y el uso de la Buttmaster dispositivo de ejercicio para lograr vástagos más bien
formadas. The term comes from the world of operating systems, where a multitasking
computer is one that can handle more than one program at a time. El término proviene del
mundo de sistemas operativos, donde un equipo multitarea es aquel que puede manejar más
de un programa a la vez.

One of the most sophisticated features of the Java language is the ability to write programs
that can multitask. Una de las características más sofisticadas del lenguaje Java es la
capacidad de escribir programas que pueden realizar múltiples tareas. Under Java, each of
the simultaneous tasks the computer handles is called a thread and the overall process is
called multithreading. En Java, cada una de las tareas al mismo tiempo el equipo se encarga
se llama un hilo y el proceso general se llama multithreading. Threading is useful in
animation and many other programs. Threading es útil en la animación y muchos otros
programas. This hour covers the subject of programming a threaded applet. Esta hora cubre
el tema de la programación de un applet de rosca.

The following topics will be covered: Los siguientes temas serán cubiertos:

 Using an interface with a program Usando una interfaz con un programa


 Creating threads Creación de hilos
 Starting and stopping threads Inicio y detención de las discusiones
 Pausing a thread Pausa de un hilo
 Loading a Web page from an applet program Carga de una página Web desde un
programa del applet
 Catching errors La captura de errores
 Displaying an applet with other Web page elements Viendo un applet con otros elementos
de la página Web

A Revolving-Link Applet A-Link Applet Rotatorio


To provide more information on how applets are programmed, this hour is an extended
workshop describing the design of a threaded applet. Para más información sobre cómo se
programan applets, esta hora es un taller ampliado que describe el diseño de un applet de
rosca. The program you'll be writing will rotate through a list of Web site titles and the
addresses used to visit them. El programa estará escrito girará a través de una lista de los
títulos del sitio Web y las direcciones utilizadas para su visita. The following six Web sites
will be listed: Los siguientes seis sitios web se enumeran:

 The JavaSoft Web site at El sitio Web de JavaSoft en http://java.sun.com


 The Gamelan Java directory at El gamelán de Java directamente en
http://www.gamelan.com
 The JavaWorld Web magazine at El JavaWorld web de la revista en
http://www.javaworld.com
 This book's Web site at sitio web del libro en este http://www.prefect.com/java24
 The Sams.net Publishing Developers' Solution Center at El Sams.net publicación de los
desarrolladores de soluciones Centro de http://www.mcp.com/sams
 The Java Applet Ratings Service at El applet de Java Calificaciones de Servicio al
http://www.jars.com

The title of each page and the Web address will be displayed in a continuous cycle. El título
de cada página y la dirección Web se mostrará en un ciclo continuo. Users will be able to
visit the currently displayed site by clicking anywhere on the applet with the mouse. Los
usuarios podrán visitar el sitio que se muestra al hacer clic en cualquier parte del applet con
el ratón. This program operates over a period of time; information on each Web site must
be shown long enough to be read, and the next site then will be shown. Este programa
opera durante un período de tiempo, información sobre cada sitio web debe mostrar el
tiempo suficiente para ser leído, y el próximo sitio a continuación, se mostrará. Because of
this time element, threads are the best way to control the program. Debido a este elemento
de tiempo, las discusiones son la mejor manera de controlar el programa.
Instead of entering this program into your word processor first and learning about it
afterward, you'll get a chance to enter the full text of the applet at the end of the hour. En
lugar de introducir este programa en su primer procesador de texto y aprender sobre ello
después, usted tendrá la oportunidad de entrar en el texto completo del applet Revolución
en la final de la hora. Before then, each section of the program will be described. Antes de
eso, cada sección del programa se describe.

The class Declaration La clase Declaración

The first thing you need to do in this applet is to use to make some classes available. Lo
primero que hay que hacer en este applet es utilizar la importación para hacer algunas
clases disponibles. The class, which is part of the group of classes, comes with methods to
start a thread, stop a thread, and pause a thread. La clase Thread, que forma parte del
grupo de las clases java.lang, viene con los métodos para iniciar un hilo, detener un hilo,
y la pausa de un hilo. All three of these methods will be useful in the applet. Los tres de
estos métodos serán útiles en el subprograma de Revolución.

The group of classes is needed because you'll be using one of them, , to display text on-
screen. El grupo java.awt de las clases es necesaria debido a que va a utilizar uno de ellos,
gráficos, para mostrar texto en pantalla. The group will be used when you work with the
Web addresses, and the group is needed when you tell the browser to load a new page. El
grupo de java.net se utiliza cuando se trabaja con las direcciones web, y el grupo
java.applet se necesita cuando usted le dice al navegador a cargar una nueva página.
Finally, the group is needed to respond to mouse clicks so that a user can visit one of the
addresses shown. Por último, el grupo java.awt.event es necesario para responder a los
clics del ratón de manera que un usuario puede visitar una de las direcciones indicadas.

Use the following statements: Utilice las declaraciones de importación siguientes:

import java.applet.*; importación java.applet .*;


import java.awt.*; import java.awt .*;
import java.awt.event.*; importación java.awt.event .*;
import java.net.*; importación java.net .*;

You might be wondering why the group of classes does not need to be imported. Usted
podría preguntarse por qué el grupo java.lang de clases no tiene por qué ser importados.
It automatically is available to all Java programs that you write and contains a lot of the
classes you will use most often. Automáticamente está disponible para todos los programas
de Java que se escribe y contiene una gran cantidad de las clases que se utiliza con más
frecuencia. The , , and classes are three examples of classes that belong to . El, Integer y
Matemáticas clases de cadenas son tres ejemplos de clases que pertenecen a java.lang.

After you have used to make some classes available, you're ready to begin the applet with
the following statement: Después de haber utilizado la importación para hacer algunas
clases disponibles, usted está listo para iniciar el applet con la siguiente declaración:

public class Revolve extends Applet public class


Revolución se extiende Applet
implements Runnable, ActionListener { implementa
Runnable, ActionListener {

This statement creates the class as a subclass of the class. Esta sentencia crea la clase de
revolución como una subclase de la clase Applet. It also uses a new statement called .
También utiliza una nueva declaración llama implementa.

The statement enables this class to inherit some extra methods beyond those that were
inherited from the class. La declaración permite que implementa esta clase de heredar
algunos métodos adicionales más allá de lo que fueron heredados de la clase Applet. The
and classes are called interfaces. El Ejecutable y clases ActionListener se llaman
interfaces. An interface is a special type of class that is only useful in conjunction with the
statement. Una interfaz es un tipo especial de clase que sólo es útil en relación con los
implementos comunicado. An interface extends the capabilities of a class. Una interfaz
amplía las capacidades de una clase. In this case, provides the behavior an applet needs in
order to become a thread. En este caso, Runnable proporciona el comportamiento de un
applet necesita para convertirse en un hilo. By implementing the class, you will be able to
use a method in this applet to make a thread begin running. Mediante la implementación de
la clase Runnable, usted será capaz de utilizar un método run () en este applet para hacer
un hilo comenzarán a publicarse. The interface enables the applet to respond to actions the
user takes with the mouse. La interfaz ActionListener permite al applet para responder a
las acciones que el usuario tiene con el ratón. Implementing it enables the method to be
called when a mouse button is clicked. Su aplicación permite a los actionPerformed ()
para ser llamado cuando un botón del ratón se hace clic.

Setting Up Variables Configuración de variables

The first thing to do in the class is to create the variables and objects needed throughout the
program. Lo primero que debe hacer en la clase de revolución es crear las variables y los
objetos necesarios en todo el programa. Create two arrays with six elements--an array of
objects called and an array of objects called : Cree dos conjuntos con seis elementos - una
matriz de objetos String denominada pageTitle y una serie de objetos llamados
pageLink URL:

String[] pageTitle = new String[6]; String [pageTitle] =


new String [6];
URL[] pageLink = new URL[6]; URL] pageLink [URL = new [6];

The array will store the titles of the six Web sites that will be displayed. La matriz
pageTitle almacenará los títulos de los seis sitios web que se mostrará. The class of
objects stores the value of a Web site address. has all the behavior and attributes that are
needed to keep track of a Web address and use it to load the page with a Web browser. La
clase de dirección de las tiendas de objetos de valor de una dirección del sitio Web. URL
tiene todo el comportamiento y los atributos que se necesitan para hacer un seguimiento de
una dirección Web y utilizarlo para cargar la página con un navegador Web. Both of these
arrays are set up without any values at this point, so you'll have to provide them later.
Ambos conjuntos se instalan sin ningún valor en este momento, por lo que tendrás que dar
más adelante.

The last two things to be created are an integer variable called and a object called : Las
dos últimas cosas que se cree son una variable entera llamada actual y un objeto Thread
llamado corredor:

int current = 0; int actual = 0;


Thread runner; Hilo corredor;

The variable will be used to keep track of which site is being displayed so that you can
cycle through the sites. La variable actual se utilizará para realizar un seguimiento de qué
sitio se muestra, para que pueda recorrer los sitios. The object represents the only thread
this program runs. El corredor objeto Thread representa el único hilo de este programa se
ejecuta. You will call methods of the object when you start, stop, and pause the operation
of the applet. Se llamará a los métodos del objeto corredor al iniciar, detener y pausar el
funcionamiento del applet.

Starting with init() A partir de init ()


The method of an applet automatically is handled when the applet first starts to run. El
método init () de un applet se maneja de forma automática cuando el primer applet
comienza a correr. In this example, this method is used to assign values to the two arrays
created for this applet, and . En este ejemplo, este método se utiliza para asignar valores a
las dos matrices creadas para este subprograma, pageTitle y pageLink. It also is used to
create a clickable button that will appear on the applet. También se utiliza para crear un
botón interactivo que aparece en el applet. The method consists of the following statements:
El método consta de las siguientes afirmaciones:

public void init() { Color background = new Color(255, 255,


204); setBackground(background); pageTitle[0] = "JavaSoft";
pageLink[0] = getURL("http://java.sun.com"); pageTitle[1] =
"Gamelan"; pageLink[1] = getURL("http://www.gamelan.com");
pageTitle[2] = "JavaWorld"; pageLink[2] =
getURL("http://www.javaworld.com"); pageTitle[3] = "Java
1.1 Programming in 24 Hours"; pageLink[3] =
getURL("http://www.prefect.com/java24"); pageTitle[4] =
"Sams.net Developers' Resource Center"; pageLink[4] =
getURL("http://www.mcp.com/sams"); pageTitle[5] = "Java
Applet Rating Service"; pageLink[5] =
getURL("http://www.jars.com"); Button goButton = new
Button("Go"); goButton.addActionListener(this);
add(goButton); } public void init () {background color =
color nuevo (255, 255, 204); setBackground (fondo);
pageTitle [0] = "JavaSoft"; pageLink [0] getURL
("http://java.sun.com = "); pageTitle [1] =" Gamelan ";
pageLink [1] = getURL (" http://www.gamelan.com ");
pageTitle [2] =" JavaWorld "; pageLink [2] = getURL (" http
: / / www.javaworld.com "); pageTitle [3] =" Java 1.1 de
programación en 24 horas "; pageLink [3] = getURL ("
http://www.prefect.com/java24 "); pageTitle [4 ] = "Los
desarrolladores de Recursos para Sams.net Centro"; pageLink
[4] = getURL ("http://www.mcp.com/sams"); pageTitle [5] =
"Java Applet Calificación del Servicio"; pageLink [5] =
getURL ("http://www.jars.com"); goButton botón = new Button
("Go"); goButton.addActionListener (este), añadir
(goButton);}

The first two statements of this method set up a background color for the applet. Las dos
primeras declaraciones de este método de establecer un color de fondo del applet. You'll
learn how to do this during Hour 16, "Using Fonts and Color in Applets." Usted aprenderá
a hacer esto durante la hora 16, "Uso de Fuentes y color en applets".

Strings are assigned to the six elements of the array, which stores the title of each Web
page. Las cadenas son asignados a los seis elementos de la matriz pageTitle, que
almacena el título de cada página Web. The elements of the array are assigned a value
returned by the method, which you will be creating for this program. Los elementos de la
matriz pageLink se les asigna un valor devuelto por la función getURL (), el cual va a
crear para este programa.

The last three statements of the method are used to create a button that will appear on-
screen when the applet runs. Las tres últimas declaraciones del método init () se utilizan
para crear un botón que aparecerá en pantalla cuando se ejecuta el applet. The button has
the name and is labeled with the text . El botón tiene el goButton nombre y se etiqueta
con el texto Volver. The statement makes it possible for the program to respond when the
user clicks the button. El addActionListener (este), la declaración hace posible que el
programa para responder cuando el usuario hace clic en el botón. The statement adds the
button to the applet's display area. El complemento () declaración agrega el botón de
visualización de la zona del applet. Creating components like buttons and using them in
programs will be explained in detail during Hour 19, "Building a Simple User Interface,"
and Hour 20, "Responding to User Events." Creación de componentes como los botones y
su uso en los programas serán explicados en detalle durante 19 horas, "La construcción de
una interfaz de usuario sencilla," Horas y 20, "Responder a eventos de usuario."

Catching Errors as You Set Up URLs La captura de errores al configurar las direcciones
URL
When you set up a object, you must make sure that the text used to set up the address is in
a valid format. and are valid, but something such as would not be because of the missing
marks. Cuando se configura un objeto URL, deberá asegurarse de que el texto que se utiliza
para establecer la dirección está en un formato válido. http://www.javasoft.com y
http://www.gamelan.com son válidos, pero algo como http:www.javasoft.com no sería
a causa de la falta / / marcas.

A special - statement is used to catch errors inside the program instead of letting them
cause it to stop running, as many errors do. Un especial de tratar - sentencia catch se
utiliza para detectar errores dentro del programa en lugar de dejarlos hacer que deje de
correr, como hacen muchos errores. The statement lets your program try to do something
that might cause an error. La instrucción try le permite a su programa de tratar de hacer
algo que pueda causar un error. If an error does occur, the statement is used to catch the
error before it brings the program to a crashing halt. Si se produce un error, la sentencia
catch se utiliza para detectar el error antes de que trae el programa a un alto estrellarse.

If you're having trouble with the concept of and statements, think of what it would be like
to be one of Superman's best pals. Si tienes problemas con el concepto de tratar de
cazar los comandos, piense en lo que sería como para ser uno de los mejores amigos de
Superman. Jimmy Olsen and Lois Lane can try all kinds of dangerous stunts without
worrying as much about the consequences if they make an error. Jimmy Olsen y Lois Lane
puede tratar todo tipo de acrobacias peligrosas sin tener que preocuparse tanto por las
consecuencias si se comete un error. No narrow ledge or runaway locomotive is too risky
an endeavor for them to attempt to navigate. N estrecha cornisa o una locomotora fuera de
control es demasiado arriesgado para ellos un esfuerzo para tratar de navegar. If they try
and fail, Superman will be there to catch them. Si intentan y fracasan, Superman estará allí
para su captura. No matter what you in a Java program, you can create a statement that
will catch errors. No importa lo que intente en un programa Java, puede crear una
instrucción catch que captura los errores. The method takes a string of text as an
argument. El () método getURL toma una cadena de texto como argumento. The string is
checked to see whether it's a valid Web address, and if it is, the method returns that valid
address. La cadena se comprueba para ver si es una dirección Web válida, y si lo es, el
método devuelve esa dirección válida. If it's erroneous, the method sends back a value. Si
es errónea, el método devuelve un valor nulo. The following is the method: El siguiente
es el () método getURL:

URL getURL(String urlText) { URL getURL (urlText String) {


URL pageURL = null; URL = null pageURL;
try { pageURL = new URL(getDocumentBase(), urlText); }
try {pageURL = nueva dirección URL (getDocumentBase (),
urlText);}
catch (MalformedURLException m) { } captura (m
MalformedURLException) {}
return pageURL; volver pageURL;
} }

The first line of this method includes three things, in this order: La primera línea de este
método incluye tres cosas, en este orden:

 The type of object or variable that is returned by the method--a object in this case. El tipo
de objeto o variable que es devuelta por el método - un objeto URL en este caso. If this is ,
no information is returned by the method. Si este es nulo, no hay información devuelta
por el método.
 The name of the method-- . El nombre del método - getURL.
 The argument or arguments, if any, that this method takes--only one in this example, a
variable called . El argumento o argumentos, en su caso, que este método tiene - una sola
en este ejemplo, una variable de cadena llamada urlText.

The statement is followed by and marks. La instrucción try va seguido de {y} marcas.
The program handles any statements between these marks, and if they generate any
exception or error conditions, these will be sent to the statement. El programa maneja las
declaraciones entre estas marcas, y si se genera ningún error o condiciones de excepción,
estos serán enviados a la declaración de capturas.

The statement also has and marks as part of the statement. La declaración de capturas
también ha {y} marcas como parte de la declaración. If is set up to catch an error from the
block statement, anything between the and marks will be handled. Si la captura se
configura para atrapar un error del bloque try, nada entre los {y} marcas serán tratados. In
this example, if a error occurs during the block of statements, any statements between the
and marks after will be handled. En este ejemplo, si un error MalformedURLException se
produce durante el intento de bloque de declaraciones, las declaraciones entre el {y}
marcas después de la captura se manejarán. Because there are no statements between and
in this method, ignores any errors that occur. Porque no hay instrucciones entre {y} en
este método, la captura pasa por alto los errores que se producen
MalformedURLException.

If the variable sent to the method is a valid Web address, it will be sent back as a valid
object. Si la variable de cadena envía al método es una dirección Web válida, será enviado
de vuelta como un objeto URL válida. If not, is returned. Si no, se devuelve null. Because
you were assigning values to six different objects in the array, the method makes this
process easier to do. Debido a que estás asignando valores a los seis objetos URL diferente
de la matriz pageURL, la función getURL () método hace que este proceso sea más fácil de
hacer.

Handling Screen Updates in the Paint() Method Manejo de las actualizaciones de


pantalla en el método paint ()
The method of any applet is handled when the screen needs to be updated. El método paint
() de cualquier subprograma se maneja cuando la pantalla debe ser actualizada. This
situation can be caused by the Web browser or operating system outside of the applet if
they obscure part of an applet window or change its dimensions in some way. Esta
situación puede ser causada por el navegador web o el sistema operativo fuera del applet si
parte oscura de una ventana del applet o cambia sus dimensiones, de alguna manera. The
method also can be manually called within an applet when the screen needs to be updated.
El método paint () también puede ser llamado de forma manual dentro de un applet cuando
la pantalla debe ser actualizada.

If you put a statement in an applet, it forces the method to be handled. Si usted pone un
repaint (); declaración en un applet, que obliga al método paint (), para ser
manipulados. This statement is a way you can tell the program that you have done
something that requires a screen update. Esta declaración es una manera que usted puede
decirle al programa que usted ha hecho algo que requiere una actualización de pantalla. For
example, if you are writing an animation program and you move an image from one place
to another, you need to use so that the image is shown in its new location. Por ejemplo, si
usted está escribiendo un programa de animación y mover una imagen de un lugar a otro,
usted necesita utilizar repaint (), de modo que la imagen se muestra en su nueva
ubicación.

The applet has a short method: El applet Revolución tiene un corto de pintar ()
método:

public void paint(Graphics screen) { public void paint


(pantalla de gráficos) {
screen.drawString(pageTitle[current], 5, 60);
screen.drawString (pageTitle [actual], 5, 60);
screen.drawString("" + pageLink[current], 5, 80);
screen.drawString ("" + pageLink [actual], 5, 80);
} }

The two statements inside the method display lines of text on the screen at the (x,y)
positions of (5, 60) and (5, 80). Los dos estados dentro de las líneas método de
visualización de texto en la pantalla en la (x, y) las posiciones de (5, 60) y (5, 80). The first
line that is displayed is an element of the array. La primera línea que se muestra es un
elemento de la matriz pageTitle. The second line that is displayed is the address of the
object, which is stored in the array. La segunda línea que se muestra es la dirección URL del
objeto, que se almacena en la matriz pageLink. The variable is used to determine which
elements of these arrays to display. La variable actual se utiliza para determinar qué
elementos de estas matrices para mostrar.

Starting the Thread A partir del hilo


One of the objects created for this program is a object called . Uno de los objetos creados
para este programa es un objeto Thread llamado corredor. In order for a thread to get
started, a place is needed where the thread is given a value and told to begin running. Para
que un hilo para empezar, se necesita un lugar donde el hilo se le da un valor y dijo que
comenzará a ejecutarse. In this applet, the thread will start whenever the method is
handled and stop whenever is handled. En este applet, el hilo corredor se iniciará cada
vez que el método start () se trata y parada cuando stop () se maneja.

The method of an applet is handled at two different times: Right after the method and
every time the program is restarted after being stopped. El método start () de un applet se
maneja en dos momentos diferentes: Derecho después de que el método init () y cada
vez que se reinicia el programa después de ser detenido. An applet is stopped any time a
user switches from the applet page to another Web page. Un applet se detiene cada vez que
un usuario cambia desde la página del applet a otra página Web. It starts again when a user
returns to the original page. Se comienza de nuevo cuando un usuario vuelve a la página
original. The following is the method of the applet: El siguiente es el método start () del
applet Revolución:

public void start() { inicio public void () {


if (runner == null) { if (corredor == null) {
runner = new Thread(this); corredor = new Thread
(this);
runner.start(); runner.start ();
} }
} }

This method does only one thing: If the thread is not already started, it creates a new
thread and starts it. Este método no sólo una cosa: Si el hilo corredor no se ha iniciado, se
crea un hilo nuevo corredor y la inicia. The object equals when it has not been started
yet, so you can test for this condition with the statement. El objetivo finalista es igual a
nula cuando no se ha iniciado todavía, así que usted puede probar esta condición con la
sentencia if.

The statement creates a new object with one argument--the statement. El corredor
declaración = new Thread (this); crea un nuevo objeto Thread con un argumento - la
declaración de esta. Using makes the applet itself the program that will run in the thread.
El uso de este applet hace el mismo programa que se ejecutará en el subproceso de
corredor.

The statement causes the thread to begin running. El runner.start (); declaración hace
que el hilo para empezar a ejecutar. When a thread begins, the method of that thread is
handled. Cuando un hilo comienza, el método run () de que el hilo se maneja. Because the
thread is the applet itself, the method of the applet is handled. Debido a que el hilo
corredor es el propio applet, el método run () del applet se maneja.

Running the Thread La ejecución del hilo

The method is where the main work of a thread takes place. El método run () es donde el
trabajo principal de un hilo se lleva a cabo. It is comparable to the block statement of a
Java application. Es comparable a la) bloque de instrucciones (principal de una
aplicación Java. In the applet, the following represents the method: En el subprograma de
Revolución, a continuación se presenta el método run ():

public void run() { public void run () {


while (true) { while (true) {
repaint(); repaint ();
current++; curso + +;
if (current > 5) if (actual> 5)
current = 0; actual = 0;
try { Thread.sleep(10000); } try {Thread.Sleep
(10000);}
catch (InterruptedException e) { } catch
(InterruptedException e) {}
} }
} }

All of the statements in this method are part of a loop that has the Boolean value as its
condition. Todas las declaraciones contenidas en este método son parte de un bucle while
que tiene el valor true como su condición. Because a loop will continue looping as long as
its condition equals , will cause the loop to continue indefinitely. Debido a que un bucle
while continuará bucle siempre y cuando su condición es igual a true, mientras que
(verdad) hará que el bucle para continuar indefinidamente. The only way the thread will
stop is for the method to be automatically called when the Web browser shuts down or the
page containing the applet is replaced with another page. La única manera que el hilo se
detiene es que el método stop () se llama automáticamente cuando el navegador web se
cierra o la página que contiene el applet se sustituye con otra página.

The method first uses the statement to cause the method to be handled. El método run ()
primero usa el repaint (); declaración para hacer que el método paint (), para ser
manipulados. Next, the value of the variable increases by one, and if exceeds , it is set to
again. A continuación, el valor de la variable aumenta actual por uno, y si la corriente
es superior a 5, se establece en 0. The variable is used in the method to determine which
Web site information to display. La variable actual se utiliza en el método paint () para
determinar qué información del sitio Web para mostrar. Changing causes a different site to
be displayed the next time is handled. El cambio hace que la corriente de un sitio
diferente al aparezca la pintura próxima vez () se maneja.

This method includes another - statement that handles an error that might occur. Este
método incluye otra oportunidad - Declaración de catch que controla un error que puede
ocurrir. The statement causes a thread to pause for 10,000 milliseconds. El Thread.Sleep
(10000); instrucción provoca un hilo para hacer una pausa para 10.000 milisegundos. This
statement causes the thread to wait long enough for users to read the name of the Web site
and its address. Esta declaración hace que el subproceso que esperar el tiempo suficiente
para que los usuarios leer el nombre del sitio web y su dirección. The statement takes care
of any errors that might occur while the statement is being handled. La declaración de las
capturas se hace cargo de cualquier error que pueda ocurrir InterruptedException
mientras que el Thread.Sleep () es que se manejan. These errors would occur if
something interrupted the thread while it was trying to . Estos errores se producen si hay
algo que interrumpe el hilo mientras se estaba tratando de dormir ().

Stopping the Thread Parar el Thread


The method is handled any time the applet is stopped because the applet's page is exited,
and it is the best place to stop the running thread. El método stop () se maneja cada vez que
se detuvo el applet porque la página del applet se sale, y es el mejor sitio para detener el
hilo conductor. The method for the applet contains the following statements: El método
stop () del applet Revolución contiene las siguientes declaraciones:

public void stop() { public void stop () {


if (runner != null) { if (finalista! = null) {
runner.stop(); runner.stop ();
runner = null; corredor = null;
} }
} }

The statement tests to see whether the object is equal to . La declaración de si las
pruebas para ver si el objeto corredor es igual a nulo. If it is, there isn't an active thread
that needs to be stopped. Si es así, no hay un hilo activo que debe ser detenido. Otherwise,
the statement uses the method of the object to stop that thread and sets equal to . De lo
contrario, la declaración utiliza el método stop () del objeto favorito para dejar que el
hilo y establece corredor igual a nulo.

Handling Mouse Clicks Manejo de clics de ratón


Anything the user does with a mouse or keyboard in an applet is called an event, and the
process of responding to events in a program is called event-handling. Cualquier cosa que
el usuario hace con el ratón o el teclado en un applet que se llama un evento, y el proceso
de responder a los eventos en un programa que se llama de control de eventos. You'll learn
all about events in Hour 20. Usted aprenderá todo sobre los eventos en la hora 20.

The last thing to take care of in the applet are mouse clicks. Lo último para atender en el
subprograma de revolución son clics del ratón. Whenever you click the Go button, the
Web browser should open the Web site that is listed. Cada vez que haga clic en el botón
Go, el navegador web se abrirá el sitio Web que aparece en la lista. This is done with a
method called . Esto se hace con un método llamado actionPerformed (). The method
is called whenever the button is clicked. El () método actionPerformed se llama cada vez
que se pulsa el botón.

The following is the method of the applet: El siguiente es el () método actionPerformed


del applet Revolución:

public void actionPerformed(ActionEvent evt) { public void


actionPerformed (ActionEvent evt) {
runner.stop(); runner.stop ();
AppletContext browser = getAppletContext(); navegador
AppletContext = getAppletContext ();
if (pageLink[current] != null) if (pageLink [actual]!
= null)
browser.showDocument(pageLink[current]);
browser.showDocument (pageLink [actual]);
} }

The first thing that happens in this method is that the thread is stopped. Lo primero que
sucede en este método es que el hilo corredor se detiene. The next two statements create a
new object called and check to see whether the currently displayed Web address is valid.
Las siguientes dos declaraciones crear un nuevo objeto llamado AppletContext
navegador y compruebe si la dirección Web que aparecen en la actualidad es válido. If it
is, the method of the class is used to display a new Web page in the user's browser. Si es
así, el método showDocument de la clase AppletContext se utiliza para mostrar una nueva
página web en el navegador del usuario.

Workshop: Revolving Links Taller: Enlaces Rotatorio


Now that all aspects of the applet have been described, you're ready to create the program
and test it out. Ahora que todos los aspectos del subprograma de Revolución se han
descrito, está listo para crear el programa y probarlo. Run your word processor and create a
new file called . Ejecutar el procesador de texto y crear un nuevo archivo llamado
Revolve.java. Enter the text of Listing 14.1 and save the file when you're done.
Introduzca el texto del listado 14.1 y guardar el archivo cuando haya terminado.

Listing 14.1. Listado de 14.1. The full text of Revolve.java. El texto completo de
Revolve.java.

1: import java.applet.*; 1: import java.applet .*;


2: import java.awt.*; 2: import java.awt .*;
3: import java.awt.event.*; 3: importación java.awt.event
.*;
4: import java.net.*; 4: importación java.net .*;
5: 5:
6: public class Revolve extends Applet 6: public class
Revolución se extiende Applet
7: implements Runnable, ActionListener { 7: implementa,
Ejecutable ActionListener {
8: 8:
9: String[] pageTitle = new String[6]; 9: String
[pageTitle] = new String [6];
10: URL[] pageLink = new URL[6]; 10: [] pageLink URL = new
URL [6];
11: int current = 0; 11: int actual = 0;
12: Thread runner; 12: Tema corredor;
13: 13:
14: public void init() { 14: public void init () {
15: Color background = new Color(255, 255, 204); 15: fondo
color = new Color (255, 255, 204);
16: setBackground(background); 16: setBackground (fondo);
17: pageTitle[0] = "JavaSoft"; 17: pageTitle [0] =
"JavaSoft";
18: pageLink[0] = getURL("http://java.sun.com"); 18:
pageLink [0] = getURL ("http://java.sun.com");
19: pageTitle[1] = "Gamelan"; 19: pageTitle [1] =
"Gamelan";
20: pageLink[1] = getURL("http://www.gamelan.com"); 20:
pageLink [1] = getURL ("http://www.gamelan.com");
21: pageTitle[2] = "JavaWorld"; 21: pageTitle [2] =
"JavaWorld";
22: pageLink[2] = getURL("http://www.javaworld.com"); 22:
pageLink [2] = getURL ("http://www.javaworld.com");
23: pageTitle[3] = "Java 1.1 Programming in 24 Hours"; 23:
pageTitle [3] = "Java 1.1 de programación en 24 horas";
24: pageLink[3] = getURL("http://www.prefect.com/java24");
24: pageLink [3] = getURL
("http://www.prefect.com/java24");
25: pageTitle[4] = "Sams.net Developers' Resource Center";
25: pageTitle [4] = "Sams.net desarrolladores Centro de
Recursos";
26: pageLink[4] = getURL("http://www.mcp.com/sams"); 26:
pageLink [4] = getURL ("http://www.mcp.com/sams");
27: pageTitle[5] = "Java Applet Rating Service"; 27:
pageTitle [5] = "Java Applet Calificación del Servicio";
28: pageLink[5] = getURL("http://www.jars.com"); 28:
pageLink [5] = getURL ("http://www.jars.com");
29: Button goButton = new Button("Go"); 29: goButton botón
= new Button ("Go");
30: goButton.addActionListener(this); 30:
goButton.addActionListener (este);
31: add(goButton); 31: agregar (goButton);
32: } 32:}
33: 33:
34: URL getURL(String urlText) { 34: URL getURL (urlText
String) {
35: URL pageURL = null; 35: URL = null pageURL;
36: try { pageURL = new URL(getDocumentBase(), urlText); }
36: try {pageURL = nueva dirección URL (getDocumentBase (),
urlText);}
37: catch (MalformedURLException m) { } 37: captura
(MalformedURLException m) {}
38: return pageURL; 38: volver pageURL;
39: } 39:}
40: 40:
41: public void paint(Graphics screen) { 41: public void
paint (pantalla de gráficos) {
42: screen.drawString(pageTitle[current], 5, 60); 42:
screen.drawString (pageTitle [actual], 5, 60);
43: screen.drawString("" + pageLink[current], 5, 80); 43:
screen.drawString ("" + pageLink [actual], 5, 80);
44: } 44:}
45: 45:
46: public void start() { 46: public void iniciar () {
47: if (runner == null) { 47: if (corredor == null) {
48: runner = new Thread(this); 48: corredor = new Thread
(this);
49: runner.start(); 49: runner.start ();
50: } 50:}
51: } 51:}
52: 52:
53: public void run() { 53: public void run () {
54: while (true) { 54: while (true) {
55: repaint(); 55: repaint ();
56: current++; 56: curso + +;
57: if (current > 5) 57: if (actual> 5)
58: current = 0; 58: actual = 0;
59: try { Thread.sleep(10000); } 59: try {Thread.Sleep
(10000);}
60: catch (InterruptedException e) { } 60: catch
(InterruptedException e) {}
61: } 61:}
62: } 62:}
63: 63:
64: public void stop() { 64: public void stop () {
65: if (runner != null) { 65: if (corredor = null!) {
66: runner.stop(); 66: runner.stop ();
67: runner = null; 67: corredor = null;
68: } 68:}
69: } 69:}
70: 70:
71: public void actionPerformed(ActionEvent evt) { 71:
public void actionPerformed (ActionEvent evt) {
72: runner.stop(); 72: runner.stop ();
73: AppletContext browser = getAppletContext(); 73:
navegador AppletContext getAppletContext = ();
74: if (pageLink[current] != null) 74: if (pageLink
[actual] nula! =)
75: browser.showDocument(pageLink[current]); 75:
browser.showDocument (pageLink [actual]);
76: } 76:}
77:}

After you compile this program with the compiler tool, you need to create a Web page to
put the applet on. Después de compilar este programa con la herramienta del compilador
javac, es necesario crear una página Web para poner el applet en. Create a new file with
your word processor and name it . Crear un nuevo archivo con su procesador de textos y el
nombre de Revolve.html. Enter Listing 14.2 and save the file. Introduzca listado 14.2 y
guarde el archivo. Note that some HTML tags have been included so that you can see the
applet in the way it might be presented on a real page. Tenga en cuenta que algunas
etiquetas de HTML se han incluido para que pueda ver el applet en la forma en que podría
ser presentado en una página real.
Listing 14.2. Listado de 14.2. The full text of Revolve.html. El texto completo de
Revolve.html.
1: <html> 2: <head> 3: <title>Homer's Home Page</title> 4:
</head> 5: <body bgcolor="#C4C4C4"> 6: <font face="Arial"
size=3> 7: <table> 8: <tr> 9: 10: <td bgcolor="#FFCCFF"
width=300 valign="TOP" align="CENTER"> 11: <h2>Homer's Home
Page</h2> 12: <p>Welcome to the cyberspace home of Homer!
1: <html> 2: <head> 3: Homer's Home <title> Page </ title>
4: </ head> 5: <body bgcolor="#C4C4C4"> 6: cara <font =
"Arial" size = 3> 7: <table> 8: <tr> 9: 10:
bgcolor="#FFCCFF" <td width=300 valign="top" ALIGN="LEFT">
11: <h2> Homer's Home Page </ h2> 12: <p> Bienvenido a la
página del ciberespacio de Homero! This page is under
construction. Esta página está en construcción. 13: </td>
14: 15: <td bgcolor="#FFFFCC" width=200 valign="TOP"
align="RIGHT"> 16: <i><b>Some of my favorite links:</b></i>
17: <applet code="Revolve.class" height=100 width=200> 18:
</applet> 19: <center> 20: <i>Click to visit</i> 21:
</center> 22: </td> 23: 24: </tr> 25: </table> 26: </font>
27: </body> 13: </ td> 14: 15: bgcolor="#FFFFCC" <td
width=200 valign="top" align="right"> 16: <b> <i> Algunos
de mis enlaces favoritos: </ b> </ i> 17:
code="Revolve.class" <applet height=100 width=200> 18: </
applet> 19: <center> 20: Haga clic en <i> para visitar </
i> 21: </ center > 22: </ td> 23: 24: </ tr> 25: </ table>
26: </ font> 27: </ body> 28: / html> <

When you're done, load this file into . Cuando haya terminado, cargar este archivo en
appletviewer. You can test the applet itself from this program, but you will not see the
surrounding HTML or be able to load a new Web page when the Go button is clicked.
Puede probar el propio applet de este programa, pero no podrá ver los alrededores de
HTML o ser capaz de cargar una nueva página Web cuando el botón Go se hace clic. These
features require the use of a Web browser that is equipped to handle Java 1.1 programs.
Estas características requieren el uso de un navegador Web que está equipado para manejar
los programas de Java 1.1. Figure 14.1 shows the output of the applet in the tool. La figura
14.1 muestra la salida del applet Revolución en la herramienta appletviewer.

Figura 14.1. A screen capture of the applet using . Una captura de pantalla del applet
con appletviewer Revolución.

So that you can see how this applet would look on a Web browser, Figure 14.2 shows a
modified version of using Netscape Navigator. Así que usted puede ver cómo este applet
se vería en un navegador Web, la figura 14.2 muestra una versión modificada de
Revolución con Netscape Navigator. This version uses no new features of Java 1.1, so it
can be run on browsers that can handle Java 1.0.2 programs. Esta versión no utiliza las
nuevas características de Java 1.1, por lo que se puede ejecutar en los navegadores que
puede manejar Java 1.0.2 programas.

Figura 14.2. A screen capture of a modified applet using Netscape Navigator. Una
captura de pantalla de un applet Revolución modificado usando Netscape Navigator.

If you'd like to run this modified version using a Web browser, you can find it on this
book's CD-ROM in the directory. Si desea ejecutar esta versión modificada mediante un
navegador Web, usted lo puede encontrar en el libro de este CD-ROM en el directorio
Win95nt4/Book/Source/Hour14. Load the Web page into a Java-enabled browser.
Cargue el OldRevolve.html página Web en un navegador compatible con Java.

Summary Resumen
Now that you have programmed applets and threads during the past two hours, you should
be getting a better idea of the behind-the-scenes work that takes place in an applet. Ahora
que usted ha programado applets y las discusiones durante las últimas dos horas, que
debería estar recibiendo una mejor idea de la labor detrás de las escenas que tiene lugar en
un applet. Many of the methods in these programs often are called automatically, such as .
Muchos de los métodos de estos programas a menudo se les llama de forma automática,
como la pintura ().

With or without threads, writing applets requires an understanding of the methods that
might be included in an applet and how they function. Con o sin hilos, escribir applets
requiere una comprensión de los métodos que podrían incluirse en un applet y cómo
funcionan. In the next several hours, you'll get more chances to see which methods are
called automatically and how to use them in your own programs. En las próximas horas,
tendrás más oportunidades de ver qué métodos son llamados automáticamente y cómo
utilizarlas en sus propios programas.

Even if you learned nothing else from this hour, you now have a new '90s term to describe
your frenzied lifestyle. Incluso si has aprendido nada de esta hora, ahora tiene un 90 nuevo
término para describir su estilo de vida frenético. Use it in a few sentences to see if it grabs
you: Se usa en unas pocas frases para ver si te agarra:

 "Boy, I was really multithreading yesterday after Mom was indicted for mail fraud."
"Muchacho, yo estaba realmente multithreading ayer después de la mamá fue acusado de
fraude por correo."
 "I multithreaded all through lunch, and it gave me gas." "Yo multiproceso durante todo el
almuerzo, y me dio de gas."
 "Not tonight, dear, I'm multithreading." "Esta noche no, querida, estoy multithreading".

Q&A Q & A
Q Why isn't java.applet.Applet needed in the class statement of the Revolve applet? Q
¿Por qué no se java.applet.Applet necesaria la declaración de clase del applet
Revolución?

A It isn't needed because of the statement that makes all of the classes available to the
program. A No es necesaria debido a la declaración de importación que hace que todas
las clases java.applet disponibles para el programa. The only purpose of is to make it
easier to refer to classes in a program. El único propósito de la importación es para
hacer más fácil para hacer referencia a las clases en un programa. If you don't use it, you
have to use full class references such as instead of simply . Si no lo utiliza, usted tiene que
utilizar las referencias de clase completa como java.applet.Applet en lugar de
simplemente applet. You could write all of your Java programs without using , though it
would make the source files more difficult to understand. Se puede escribir todos los
programas de Java sin necesidad de utilizar de importación, a pesar de que haría que
la fuente de los archivos más difícil de entender.

Q If the Revolve applet only has one thread, what's the point of using threads at all? Q Si
el applet de revolución tiene un solo hilo, ¿cuál es el punto de recurrir a las discusiones
en absoluto?

A Multithreading has benefits even it's really just single-threading. Un Multithreading


tiene beneficios aún no deja de ser una sola rosca. The reason is that you can start, stop,
and pause a thread from within a program; you don't have the same kind of control
without threads. La razón es que se puede iniciar, detener y pausar un hilo desde un
programa, usted no tiene el mismo tipo de control sin hilos. Also, by making an applet a
thread, even for a single-thread project, you make it easier to implement additional
threads as needed later on. Además, haciendo un applet de un hilo, incluso para un solo
proyecto-hilo, que sea más fácil aplicar las discusiones adicionales si es necesario más
adelante.

Q Are there any reasons not to leave a pair of empty brackets after a catch statement,
which causes errors to be disregarded? Q ¿Hay razones para no dejar un par de
paréntesis vacíos después de una declaración de capturas, lo que provoca errores al no
tenerse en cuenta?

A It depends on the type of error or exception that is being caught. A Depende del tipo de
error o excepción que se está atrapado. In the applet, you know with both statements
what the cause of an exception would be. En el subprograma de revolución, usted
sabe con ambas declaraciones de capturas, lo que la causa de una excepción sería.
Because of this knowledge, you can handle the error. Debido a este conocimiento, usted
puede controlar el error. In the method, the would only be caused if the URL sent to the
method is invalid. En la () método getURL, el MalformedURLException sólo se
produciría si la URL enviada al método no es válido.

Quiz Quiz
Set aside your threads (in the Java sense, not the nudity sense), and answer the following
questions about multithreading in Java. Dejar de lado sus discusiones (en el sentido de Java,
no el sentido de la desnudez), y contestar las siguientes preguntas sobre el multithreading
en Java.

Questions Preguntas
1. What class must be implemented for an applet to use threads? 1. ¿Qué clase debe ser
aplicado para un applet para utilizar hilos?

(a) (A) Ejecutable


(b) (B) Tema
(c) (C) Applet

2. When a class has been set up as a thread, what method will be handled when the
thread begins running? 2. Cuando se ha creado una clase como un hilo, ¿qué método será
tratada cuando el hilo comienza a funcionar?

(a) (A) de partida ()


(b) (B) ejecutar ()
(c) (C) init ()

3. You're admiring the work of another programmer who has created an applet that
handles four simultaneous tasks. 3. Usted es de admirar el trabajo de otro programador
que ha creado un applet que se encarga de cuatro tareas simultáneas. What should you
tell him? ¿Qué hay que decirle?

(a) "That's not half as exciting as the Eleanor Mondale screen saver I downloaded off the
Web." (A) "Eso no es un medio tan emocionante como el Mondale protector de pantalla
de Eleanor he descargado de la Web."
(b) "You're the wind beneath my wings." (B) "Tú eres el viento bajo mis alas."
(c) "Nice threads!" (C) "las discusiones de Niza!"

Answers Respuestas

1. a. must be used with the statement. is used inside a multithreaded program, but it is
not needed in the class statement that begins a program. 1. A. Ejecutable debe ser
utilizado con los implementos comunicado. Hilo se utiliza dentro de un programa de
multiproceso, pero no es necesario en la declaración de clase que se inicia un programa.
2. b. 2. B. The statement is handled when the thread begins. El run () sentencia se
gestiona cuando el hilo se inicia.
3. c. 3. C. This compliment could be confusing if the programmer is well-dressed, but let's
be honest--what are the chances of that? Este complemento puede ser confuso si el
programador está bien vestida, pero seamos honestos - ¿Cuáles son las posibilidades de
que?
Activities Actividades
If this long workshop hasn't left you feeling threadbare, expand your skills with the
following activities: Si este taller larga no te ha dejado sentir raída, ampliar sus
conocimientos con las siguientes actividades:

 If you are comfortable with HTML, create your own home page that includes the applet
and six of your own favorite Web sites. Si te sientes cómodo con HTML, crear su propia
página que incluye el subprograma de revolución y seis de sus propios sitios Web
favoritos. Use the applet along with other graphics and text on the page. Utilice el applet,
junto con otros gráficos y texto en la página.
 Rewrite the applet from the previous hour to use threads and actually pause one second
for each second that the national debt is increasing. Vuelva a escribir el applet ¡Ay de la
hora anterior al uso de las discusiones y, de hecho una pausa cada vez un segundo por
cada segundo que la deuda nacional es.

 15 horas
o El envío de parámetros a subprogramas
o
 El envío de los parámetros de una página Web
 Recepción de parámetros en el applet
 Taller: Manejo de parámetros en un applet

 Listado de 15.1. El texto completo de ShowWeight.java.
 Listado de 15.2. El texto completo de ShowWeight.html.
 Figura 15.1.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 15 15 horas

Sending Parameters to Applets El envío de parámetros a


subprogramas

Now that you have had some experience writing computer programs, you might be feeling
one of the strongest emotions of the programmer: compiler angst. Ahora que usted ha
tenido alguna experiencia escribiendo programas de ordenador, es posible que se sienta una
de las emociones más fuertes de la programación: la angustia del compilador. Even though
it takes no more than 15 seconds to compile most programs, that time can seem
interminable when you're debugging a program. A pesar de que no toma más de 15
segundos para compilar la mayoría de los programas, que el tiempo puede parecer
interminable cuando se está depurando un programa. Write, Save, Compile, Aargh--an
error! Escribir, Guardar, compilar, Aargh - un error! Write, Save, Compile, Aargh! Escribir,
Guardar, compilar, Aargh! Write, Save, Compile, Aargh!... Escribir, Guardar, compilar,
Aargh! ... As this vicious cycle repeats itself, it's easy to become world-weary as a program
is compiled and recompiled. En este círculo vicioso se repite, es fácil llegar a ser cansado
del mundo como un programa se compila y se vuelve a compilar.

One of the driving forces behind parameter use in Java applets is the fear and loathing of
compilation. Uno de los impulsores de utilizar el parámetro de applets de Java es el miedo
y el odio de la compilación. Parameters enable you to change elements of an applet without
editing or recompiling anything. Los parámetros le permiten cambiar los elementos de un
applet sin necesidad de editar o recompilar nada. They also make the program more useful.
También hacen el programa más útil.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 ending parameters to Java applets S termina parámetros para los applets de Java
 Receiving parameters in an applet program parámetros de recepción en un programa del
applet
 Checking for nonexistent parameters Comprobación de parámetros inexistentes
 Converting parameters from one type to another La conversión de los parámetros de un
tipo a otro
 Writing a program that uses parameters Escribir un programa que utiliza parámetros

Sending Parameters from a Web Page El envío de los parámetros de una página Web
Parameters are stored as part of the Web page that contains an applet. Los parámetros se
almacenan como parte de la página Web que contiene un applet. They are created using the
HTML tag and its two attributes: and . Ellos se crean utilizando el <PARAM> etiquetas
HTML y sus dos atributos: nombre y valor. You can have more than one tag with an
applet, but all of them must be between the opening tag and the closing tag. Usted puede
tener más de un <PARAM> etiqueta con un applet, pero todos ellos deben estar entre las
etiquetas <APPLET> la apertura y el cierre </ APPLET> etiquetas. The following is an tag
that includes several parameters: La siguiente es una etiqueta <APPLET> que incluye varios
parámetros:

<APPLET CODE="ScrollingHeadline.class" HEIGHT=50


WIDTH=400> CODE="ScrollingHeadline.class" <APPLET HEIGHT=50
WIDTH=400>
<PARAM NAME="Headline1" VALUE="Dewey defeats Truman">
<PARAM NAME="Headline1" VALUE="Dewey derrotas Truman">
<PARAM NAME="Headline2" VALUE="Stix nix hix pix"> <PARAM
NAME="Headline2" VALUE="Stix hix nix pix">
<PARAM NAME="Headline3" VALUE="Man bites dog"> <PARAM
NAME="Headline3" VALUE="Man picaduras dog">
</APPLET> </ APPLET>

This example could be used to send news headlines to an applet that scrolls them across the
screen. Este ejemplo podría ser utilizado para enviar los titulares de noticias a un applet que
los desplaza por la pantalla. Because news changes all the time, the only way to create a
program of this kind is with parameters. Debido a los cambios de noticias todo el tiempo, la
única manera de crear un programa de este tipo con los parámetros. No other solution
would work; just imagine how long it would take to recompile a Java program every time a
Dallas Cowboy ran afoul of the law. No hay otra solución que el trabajo, sólo imaginar
cuánto tiempo haría falta para volver a compilar un programa Java cada vez que un vaquero
de Dallas se vio arrastrada por la ley.

You use the attribute to give the parameter a name. Se utiliza el atributo NAME para dar
el parámetro de un nombre. This attribute is comparable to giving a variable a name. Este
atributo es comparable a dar una variable de un nombre. The attribute gives the named
parameter a value. El atributo VALUE da el parámetro denominado un valor.

Receiving Parameters in the Applet Recepción de parámetros en el applet


You have to do something in your Java program to retrieve the parameters on the Web page
or they will be ignored. Tienes que hacer algo en el programa Java para recuperar los
parámetros en la página Web o que será ignorado. The method of the class retrieves a
parameter from a tag on a Web page. El método getParameter () de la clase Applet
recupera un parámetro de una etiqueta <PARAM> en una página Web. The parameter name,
which is specified with the attribute on the page, is used as an argument to . El nombre del
parámetro que se especifica con el atributo NAME de la página, se utiliza como
argumento para getParameter (). The following is an example of in action: El siguiente
es un ejemplo de getParameter () en acción:

String display1 = getParameter("Headline1"); String


Display1 = getParameter ("Headline1");

The method returns all parameters as strings, so you have to convert them to other types as
needed. El método getParameter () devuelve todos los parámetros como cadenas, así que
tienes que convertirlos a otros tipos, según sea necesario. If you want to use a parameter as
an integer, you could use statements such as the following: Si desea utilizar un parámetro
como un entero, se puede utilizar frases como las siguientes:
int speed; int velocidad;
String speedParam = getParameter("SPEED"); speedParam
String = getParameter ("velocidad");
if (speedParam != null) if (speedParam! = null)
speed = Integer.parseInt(speedParam); velocidad =
Integer.parseInt (speedParam);

This example sets the variable by using the string. Este ejemplo establece la variable de la
velocidad mediante el uso de la cadena speedParam. You have to test for strings before
setting because the method cannot work with a string. Usted tiene que probar para
cadenas nulas antes de velocidad porque el parseInt () no puede trabajar con una
cadena nula. When you try to retrieve a parameter with that was not included on a Web
page with the tag, it will be sent as , which is the value of an empty string. Al intentar
recuperar un parámetro con getParameter () que no fue incluido en una página Web con
la etiqueta <PARAM>, será enviado como nulo, que es el valor de una cadena vacía.

Workshop: Handling Parameters in an Applet Taller: Manejo de parámetros en un


applet
This hour's workshop project has little practical value, except perhaps as a taunting device.
Este proyecto hora de taller poco valor práctico, excepto tal vez como un dispositivo de
burlas. The applet takes a person's weight and displays it under several different units. El
applet ShowWeight lleva el peso de una persona y lo muestra en varias unidades diferentes.
The applet takes two parameters: a weight in pounds and the name of the person who
weighs that amount. El applet tiene dos parámetros: un peso en libras y el nombre de la
persona que pesa esa cantidad. The weight is used to figure out the person's weight in
ounces, kilograms, and metric tons, and all of these are displayed. El peso se utiliza para
calcular el peso de la persona en onzas, kilogramos y toneladas métricas, y todos estos que
aparecen son.

Create a new file with your word processor and give it the name . Crear un nuevo archivo
con su procesador de texto y darle el nombre ShowWeight.java. Enter Listing 15.1 into
the file. Introduzca listado 15.1 en el archivo. Then save and compile the file. A
continuación, guarde y compile el archivo.

Listing 15.1. Listado de 15.1. The full text of ShowWeight.java. El texto completo de
ShowWeight.java.
1: import java.awt.*; 2: 3: public class ShowWeight extends
java.applet.Applet { 4: float lbs = (float)0; 5: float ozs;
6: float kgs; 7: float metricTons; 8: String name =
"somebody"; 9: 10: public void init() { 11: String lbsValue
= getParameter("weight"); 12: if (lbsValue != null) { 13:
Float lbsTemp = Float.valueOf(lbsValue); 14: lbs =
lbsTemp.floatValue(); 15: } 16: String personValue =
getParameter("person"); 17: if (personValue != null) 18:
name = personValue; 19: 20: ozs = (float)(lbs * 16); 21:
kgs = (float)(lbs / 2.204623); 22: metricTons = (float)(lbs
/ 2204.623); 23: } 24: 25: public void paint(Graphics
screen) { 26: screen.drawString("Studying the weight of " +
name, 5, 30); 27: screen.drawString("In pounds: " + lbs,
55, 50); 28: screen.drawString("In ounces: " + ozs, 55,
70); 29: screen.drawString("In kilograms: " + kgs, 55, 90);
30: screen.drawString("In metric tons: " + metricTons, 55,
110); 31: } 32: 1: import java.awt .*; 2: 3: public class
ShowWeight extiende java.applet.Applet {4: libra = float
(flotador) 0; 5 onzas flotador; 6: kg flotan; 7: metrictons
flotador; 8: String nombre = "alguien"; 9:: 11 públicos: 10
sin efecto init () {String lbsValue = getParameter
("peso"); 12: if (! lbsValue = null) {13: lbsTemp flotador
= Float.valueOf (lbsValue) ; 14 libras = lbsTemp.floatValue
(); 15:} 16: personValue String = getParameter ("persona");
17:) si personValue (! = null 18: nombre = personValue; 19:
20: onzas = (float) (* libras 16); 21: kg = (float) (libras
/ 2,204623); 22: metrictons = (float) (libras / 2204.623);
23:} 24: 25: public void paint (pantalla de gráficos) {26:
pantalla . drawString ("Estudiar el peso de" + nombre, 5,
30); 27: screen.drawString ("En libras:" + libras, 55, 50);
28: screen.drawString ("En onzas:" + onzas, 55, 70); 29:
screen.drawString ("En kilogramos:" + kgs, 55, 90); 30:
screen.drawString ("En toneladas métricas:" + metrictons,
55, 110); 31:} 32: 33 :}

The method is where the two parameters are loaded into the applet. El método init () es
donde los dos parámetros se cargan en el applet. Because they come from the Web page as
strings, they must be converted into the form you need: a floating-point number for the
variable and a string for . Porque vienen de la página Web en forma de cadenas, que deben
convertirse en la forma que necesita: un número de punto flotante para la variable de
libras y una cadena para el nombre. Converting a string to a floating-point number
requires two steps: converting the string to a object and then converting that object to a
variable of the type . Convertir una cadena a un número de punto flotante de dos etapas: la
conversión de la cadena a un objeto flotante y luego convertir ese objeto a una variable
del tipo float.

As you learned with strings, objects and variables are treated differently in Java programs,
and there are different things you can do with them. Como ha aprendido con cadenas,
objetos y las variables son tratadas de manera diferente en los programas de Java, y hay
cosas diferentes que puedes hacer con ellos. The reason there is a object and a variable
type is so you can use a floating-point number as either an object or a variable. La razón no
es un objeto flotante y un tipo variable de tipo float es así que usted puede utilizar un
número de punto flotante, ya sea como un objeto o una variable. The object class also has
useful methods such as and that you can use to convert floating-point numbers into
different types of variables. La clase de objeto flotante también tiene métodos útiles,
como valueOf () y floatValue () que puede utilizar para convertir los puntos de
números en coma flotante en diferentes tipos de variables.

Lines 20-22 are used to convert the variable into different units of measure. Líneas 20 a 22
se utilizan para convertir la variable de libras en las diferentes unidades de medida. Each
of these statements has in front of the conversion equation. Cada uno de estos estados tiene
(float) delante de la ecuación de conversión. This is used to convert the result of the
equation into a floating-point number. Esto se utiliza para convertir el resultado de la
ecuación en un número de punto flotante. You can use this structure to convert variables of
one type to another. Usted puede utilizar esta estructura para convertir variables de un tipo
a otro. Put a variable type in parentheses in front of an equation that produces a result, and
it will convert the result to that type. Ponga un tipo variable entre paréntesis frente a una
ecuación que produce un resultado, y se convertirá el resultado de ese tipo.

The method of the applet uses the method of the class to display a line of text on-screen.
El método paint () del applet utiliza el drawString () de la clase Graphics para mostrar
una línea de texto en pantalla. The method has three arguments: the text to display and the
x and y positions where the text should be shown. El método paint () tiene tres
argumentos: el texto a mostrar y la posición x e y que debe ser el texto que se muestra.

Before you can test the applet, you need to create a Web page that contains the applet.
Antes de probar el applet ShowWeight, es necesario crear una página Web que contiene el
applet. Open up a new file on your word processor and name it . Abra un archivo nuevo en
su procesador de textos y el nombre de ShowWeight.html. Enter Listing 15.2 and save it
when you're done. Introduzca Listado 15.2 y guardarlo cuando haya terminado.

Listing 15.2. Listado de 15.2. The full text of ShowWeight.html. El texto completo de
ShowWeight.html.

1: <applet code="ShowWeight.class" height=170 width=200>


1: <applet code="ShowWeight.class" height=170 width=200>
2: <param name="person" value="Konishiki"> 2:
name="person" <param value="Konishiki">
3: <param name="weight" value=605> 3: name="weight" <param
value=605>
4: </ applet>

Use the tool to see the applet. Utilice la herramienta appletviewer para ver el applet
ShowWeight. This demonstration uses Konishiki as its example because the American-born
sumo wrestling champion weighs in at more than 605 pounds, making him the largest of the
bikini-wearing behemoths. Esta demostración utiliza Konishiki como su ejemplo, porque el
sumo nacidos en Estados Unidos el campeón de lucha pesa más de 605 libras,
convirtiéndose en el mayor de los gigantes en bikini. You can substitute anyone whose
weight is either exemplary or well-known. Puede sustituir cualquier persona cuyo peso es
ya sea ejemplar o notoriamente conocida. Figure 15.1 shows an example of output from the
applet. Figura 15.1 muestra un ejemplo de salida del applet. As you can see, Konishiki's
workout regimen doesn't include a lot of fat-free SnackWell's Devil's Food Cakes. Como
puede ver, Konishiki régimen de ejercicios no incluye una gran cantidad de Diablo Pasteles
sin grasa SnackWell de la Alimentación.

Figura 15.1. The output of the applet. La salida del applet ShowWeight.

To make the applet display a different name along with a different value for the parameter,
all you have to change is the file. Para hacer la pantalla applet un nombre diferente, junto
con un valor diferente para el "peso" de parámetros, todo lo que tiene que cambiar es el
archivo ShowWeight.html. The applet itself will continue to work correctly. El propio
applet seguir funcionando correctamente.

Summary Resumen
If you visit a site such as Gamelan on the World Wide Web ( ), you'll see links to
numerous applets that have been made available for public use, including some that offer
the source file of the program. Si usted visita un sitio como Gamelan en la World Wide
Web ( http://www.gamelan.com ), puedes encontrar enlaces a numerosos applets que se
han hecho disponibles para uso público, incluyendo algunas que ofrecen el archivo de
origen de el programa. These applets often use parameters, especially for animation or
scrolling text programs. Estos applets a menudo se utilizan parámetros, especialmente para
los programas de animación de texto o el desplazamiento. During this hour you covered all
aspects of parameter use in your applets. Durante esta hora que abarcó todos los aspectos
del uso de parámetros en los applets. Parameters can greatly improve the usefulness and
performance of applets. Parámetros puede mejorar la utilidad y el rendimiento de los
applets.

Even if you're the paragon of programming patience and you can wait out the slowest
compiler, you'll be using parameters in your Java applets. Incluso si usted es el paradigma
de la paciencia de programación y se puede esperar a que el compilador más lento, que va a
utilizar los parámetros de los applets de Java. Like arguments for Java applications,
parameters are a useful way to make one program perform in a variety of ways. Como
argumentos para aplicaciones Java, los parámetros son un medio útil para realizar un
programa en una variedad de maneras.
Q&A Q & A
Q Why can't parameters be used with Java applications? Q ¿Por qué no puede ser
utilizado con los parámetros de las aplicaciones Java?

A Parameters must be stored in some sort of document, such as a Web page. Un


parámetros deben ser almacenados en algún tipo de documento, como una página Web.
With a Java application that runs from the command line, there's nowhere to put them.
Con una aplicación Java que se ejecuta desde la línea de comandos, no hay donde
ponerlos. However, you can specify arguments on the command line when you run the
program, and these are brought in as strings also. Sin embargo, puede especificar
argumentos en la línea de comandos cuando se ejecuta el programa, y estas son
presentadas en forma de cadenas también. Handling arguments in applications has many
similarities to handling parameters in applets. Tratamiento de los argumentos en las
aplicaciones tiene muchas similitudes con los parámetros de manejo en los applets.

Q Does the name of a parameter on a Web page have to be capitalized exactly as it is


shown as an argument to the getParameter() method? Q ¿El nombre de un parámetro
en una página Web tiene que estar en mayúsculas tal y como se muestra como un
argumento al método getParameter ()?

A Like all HTML tags and attributes, the and attributes of the tag do not have to be
capitalized a specific way to work. A igual que todas las etiquetas HTML y atributos, el
nombre y valor los atributos de la etiqueta <PARAM> no tiene que estar en mayúsculas
de una determinada manera de trabajar. The text and and all refer to the same
parameter. El texto de "Speed" y "velocidad" y "velocidad" se refieren al mismo
parámetro.

Quiz Quiz
Test your knowledge of parameters with the following questions. Pon a prueba tu
conocimiento de los parámetros con las siguientes preguntas.

Questions Preguntas

1. What's the name of the HTML tag that is used to send a parameter to a Java program?
1. ¿Cuál es el nombre de la etiqueta HTML que se utiliza para enviar un parámetro a un
programa Java?

(a) (A) <APPLET>


(b) (B) <variable>
(c) (C) <PARAM>

2. When the method is used to load a parameter value into a program, what type of
information is loaded? 2. Cuando el método getParameter () se utiliza para cargar un
valor de parámetro en un programa, ¿qué tipo de información que se carga?

(a) a variable (A) una cadena variable


(b) a different type depending on the parameter (B) un tipo diferente en función del
parámetro
(c) an array of characters (C) una matriz de caracteres

3. If you try to load a parameter that is not included on the Web page that contains the
applet, what will do? 3. Si intenta cargar un parámetro que no está incluido en la página
Web que contiene el applet, lo que getParameter () hacer?

(a) crash the program with an error (A) hacer que el programa con un error
(b) return the empty string as a value (B) la devolución de la nula cadena vacía como un
valor
(c) nothing (C) nada

Answers Respuestas

1. c. is the tag to send a parameter, and is the tag to load the applet itself. 1. C. <PARAM>
es la etiqueta para enviar un parámetro, y <APPLET> es la etiqueta de la carga del propio
applet.

2. a. 2. A. All parameters are received by an applet as variables. Todos los parámetros son
recibidos por un applet como variables de cadena. They have to be converted to
another type of variable or object if you want to use them differently. Ellos tienen que ser
convertidos a otro tipo de variable u objeto, si desea utilizarlos de manera diferente.

3. b. 3. B. The method must return some kind of value. El método getParameter ()


debe devolver algún tipo de valor. The value is used to signify the lack of a parameter that
matches the argument of . El valor nulo se utiliza para significar la falta de un parámetro
que coincide con el argumento de getParameter ().

Activities Actividades
If you're not overstuffed from the weighty subject of parameters, the following activities
are suggested: Si no está atiborrado de los sujetos de peso de los parámetros, las actividades
se sugieren las siguientes:

 Create an applet version of the application from Hour 8, "Repeating an Action with
Loops," that takes the line to display over and over again as a parameter. Crear una
versión applet de la solicitud de repetición de 8 horas, "Repetición de una acción con
Loops", que tiene la línea para ver una y otra vez como un parámetro.
 Add a parameter to the applet that specifies the ideal weight of the person. Agregar un
parámetro para el applet ShowWeight que especifica el peso ideal de la persona. Display
how many weeks of dieting it would take them to reach it, given five pounds of weight loss
per week. Mostrar el número de semanas de dieta que les llevaría a alcanzar, teniendo en
cuenta cinco libras de pérdida de peso por semana.
 16 horas
o Utilizar fuentes y color en Applets
 Uso de la clase de fuente
 Listado de 16.1. El texto completo de Fonts.java.
 Listado de 16.2. El texto completo de Fonts.html.
 Figura 16.1.
 Uso de la clase Color
 Otras formas de elegir los colores
 Taller: Visualización de un mensaje de peligro
 Listado de 16.3. El texto completo de Danger.java.
 Listado de 16.4. El texto completo de Danger.html.
 Figura 16.2.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 16 16 horas

Using Fonts and Color in Applets Utilizar fuentes y color


en Applets

A famous catchphrase from the television show Saturday Night Live during the 1980s was,
"It's not how you feel, but how you look...and darling, you look MAH-ve-lous." Una
famosa frase de la serie de televisión Saturday Night Live "durante la década de 1980 fue:"
No es cómo te sientes, pero ¿cómo te ves ... y querida, te ves MAH-ve-Lous ". The quote
epitomized the philosophy of Fernando, comedian Billy Crystal's eternally tan and
impeccably groomed celebrity. La frase resume la filosofía de Fernando, el comediante
Billy Crystal celebridades eternamente bronceado y peinado impecable. Regardless of what
was going on in his life, as long as his hair was styled properly and he was dressed for the
occasion, everything was copacetic. Independientemente de lo que estaba pasando en su
vida, siempre y cuando su pelo era de estilo correctamente y estaba vestido para la ocasión,
todo estaba Copacetic. After all, though Fernando hadn't been in a hit movie since Won
Ton Ton, the Dog Who Saved Hollywood, he still looked good. Después de todo, aunque
Fernando no había estado en una película de éxito desde Won Ton Ton, el perro que salvó a
Hollywood, que aún se veía bien. Correction: He looked MAH-ve-lous. Corrección: Miró
MAH-ve-Lous.

If you're interested in making your Java applets look MAH-ve-lous, you should know about
the and classes. Si usted está interesado en hacer su applets de Java buscar MAH-ve-Lous,
usted debe saber sobre el color y las clases de fuentes. No self-respecting applet would
be seen in public without them. No applet que se precie sería visto en público sin ellos.
With these classes, you can present text in several different fonts and sizes and change the
colors of text, graphics, and other elements. Con estas clases, usted puede presentar el texto
en varios diferentes tipos de letra y tamaños y cambiar los colores de texto, gráficos y otros
elementos.

One of the principles of object-oriented programming is to make an object work for itself,
and the and objects follow this rule. Uno de los principios de la programación orientada a
objeto es hacer un objeto de trabajo por sí mismo, y el color y los objetos de fuente sigue
esta regla. They store all the information that's needed to display a font or change a color,
and they can handle other related tasks that are required. Que almacenan toda la
información que se necesita para mostrar una fuente o cambiar un color, y pueden manejar
otras tareas relacionadas que se requieren. The following topics will be covered during this
hour: Entre los temas que se tratarán durante esta hora:

 Using fonts in your applets Uso de fuentes en los applets


 Setting a font's style and size Programación del estilo de una fuente y el tamaño
 Choosing a font Selección de una fuente
 Displaying colors in applets Viendo los colores de los applets
 Using the color constants Uso de las constantes de colores
 Setting up the background color Configuración del color de fondo
 Using RGB values to choose colors Utilizando los valores RGB para elegir los colores
 Using HSB values to choose colors El uso de valores HSB para elegir colores
 Creating special text effects using colors Creación de efectos especiales de texto con
colores

Using the Font Class Uso de la clase de fuente


There are three things you need to know about a font in order to display it: Hay tres cosas
que usted necesita saber acerca de una fuente con el fin de mostrarla:

 The typeface of the font: Helvetica, Courier, Dialog, Times Roman, or others El tipo de letra
de la fuente: Helvetica, Courier, de diálogo, Times Roman, u otros
 The style of the font: bold, italic, or plain El estilo de la fuente: negrita, cursiva, o simple
 The size of the font, in points El tamaño de la fuente, en los puntos

Before you can display text in a certain typeface, style, and point size, you need to create a
object that holds this information. Antes de poder mostrar el texto en un tipo de letra
determinada, estilo y tamaño de punto, es necesario crear un objeto Font que contiene esta
información. The following statement creates a 12-point Times Roman italic object: La
siguiente instrucción crea un niño de 12 puntos Times cursiva romana Fuente objeto:

Font currentFont = new Font("TimesRoman", Font.ITALIC,


12); currentFont fuente = new Font ("TimesRoman",
Font.ITALIC, 12);

The typeface that you can select may vary depending on the system you're using. El tipo de
letra que usted puede elegir varían dependiendo del sistema que está utilizando. The current
release of the Java Developer's Kit for Windows 95 includes Helvetica, Courier, Dialog,
Dialog Input, and Times Roman. La versión actual del Kit de Desarrollo Java para
Windows 95 incluye Helvetica, Courier, diálogo, diálogo de entrada, y la época romana.

You choose the style of the font by using one or more constant variables. Usted elige el
estilo de la fuente mediante el uso de una o más variables constantes. Specifying the style
as makes it nonbold and nonitalic, makes it bold, and makes it italic. Especificar el estilo
como Font.PLAIN hace nonbold y nonitalic, Font.Bold hace audaces, y Font.ITALIC
hace cursiva. To combine bold and italic, use , as in the following code: Para combinar
negrita y cursiva, el uso Font.Bold + Font.ITALIC, como en el siguiente código:

Font headlineFont = new Font("Courier",


Font.BOLD+Font.ITALIC, 72); headlineFont fuente = new Font
("Correo", Font.Bold + Font.ITALIC, 72);

The last argument specifies the point size of the font. El último argumento especifica el
tamaño de punto de la fuente. To see a simple example of using fonts in an applet, open
your word processor and create a new file called . Para ver un ejemplo sencillo del uso de
fuentes en un applet, abra su procesador de textos y crear un nuevo archivo llamado
Fonts.java. Enter the text of Listing 16.1 and save the file. Introduzca el texto del listado
16.1 y guardar el archivo.

Listing 16.1. Listado de 16.1. The full text of Fonts.java. El texto completo de Fonts.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Fonts extends java.applet.Applet { 3:
Fuentes de clase pública se extiende java.applet.Applet {
4: 4:
5: public void paint(Graphics screen) { 5: public void
paint (pantalla de gráficos) {
6: Font currentFont = new Font("TimesRoman", Font.PLAIN,
20); 6: currentFont nuevo Font Fuente = ("TimesRoman",
Font.PLAIN, 20);
7: screen.setFont(currentFont); 7: screen.setFont
(currentFont);
8: screen.drawString("If I've said it once, I've said it
a thousand 9: times, darling,", 5, 50); 8:
screen.drawString ("Si lo he dicho una vez, lo he dicho mil
nueve: los tiempos, querida-, 5, 50);
10: currentFont = new Font("TimesRoman", Font.ITALIC, 40);
10: currentFont = new Font ("TimesRoman", Font.ITALIC, 40);
11: screen.setFont(currentFont); 11: screen.setFont
(currentFont);
12: screen.drawString("you look MAH-VE-LOUS", 5, 80); 12:
screen.drawString ("te ves MAH-VE-LOUS", 5, 80);
13: } 13:}
14:}

After you compile the file with the compiler tool, you need to create a Web page that
contains the applet. Después de compilar el archivo con la herramienta del compilador
javac, es necesario crear una página Web que contiene el applet. Create a new file in your
word processor called and enter the text of Listing 16.2. Crear un nuevo archivo en el
procesador de textos llamado Fonts.html y escriba el texto del listado 16.2.

Listing 16.2. Listado de 16.2. The full text of Fonts.html. El texto completo de
Fonts.html.

1: <applet code="Fonts.class" height=125 width=450> 1:


<applet code="Fonts.class" height=125 width=450>
2: </ applet>

Save this file and then load this page into the tool by using the following command:
Guardar este archivo y luego cargar esta página en la herramienta appletviewer utilizando
el siguiente comando:

appletviewer Fonts.html appletviewer Fonts.html

The output should resemble Figure 16.1. La salida debe ser similar a la figura 16.1.

Figura 16.1. The output of the applet. La salida del applet Fuentes.
Using the Color Class Uso de la clase Color
The simplest way to use a color in a Java program is to use one of the constant variables
from the class. La forma más sencilla de usar un color en un programa Java es utilizar una
de las variables constantes de la clase Color. You can use the following constants: , , , ,
, , , , , , , , and . Puede utilizar las siguientes constantes: negro, azul, cian,
darkGray, gris, verde, gris_claro, magenta, naranja, rosa, rojo, blanco y
amarillo.

In an applet, you can set the background color of the applet window using these constants.
En un applet, puede configurar el color de fondo de la ventana del applet con estas
constantes. The following is an example: El siguiente es un ejemplo:

setBackground(Color.orange); setBackground (Color.orange);

When you want to display text of a certain color or draw other graphics in different colors,
you have to use a method that sets up the current color. Cuando se desea mostrar texto de
un determinado color o dibujar otros gráficos en colores diferentes, usted tiene que utilizar
un método que establece el color actual. You can do this from within the method of an
applet by using a method, as in the following: Usted puede hacer esto desde dentro del
método paint () de un applet usando un setColor () método, como en el siguiente:

public void paint(Graphics screen) { public void paint


(pantalla de gráficos) {
screen.setColor(Color.orange); screen.setColor
(Color.orange);
screen.drawString("Go, Buccaneers!", 5, 50);
screen.drawString ("Vaya, Bucaneros!", 5, 50);
} }

Unlike the method, which is inherited directly from the class, the method must be used on
an object that can handle a color change. A diferencia de la setBackground () método,
que se hereda directamente de la clase Applet, el setColor () el método debe ser
utilizado en un objeto que puede manejar un cambio de color. The preceding example
shows the method of the object being used to change the current color of the applet
window. El ejemplo anterior muestra la setColor () de la pantalla del objeto que se
utiliza para cambiar el color actual de la ventana del applet.

Other Ways to Choose Colors Otras formas de elegir los colores


To use a color not included in the 13 constant variables, you must specify the color's RGB
or HSB values. Para utilizar un color no incluido en las 13 variables constantes, se debe
especificar RGB del color o los valores HSB. RGB, which stands for Red Green Blue,
defines a color by the amount of red, green, and blue that is present in the color. RGB, que
significa rojo verde azul, un color se define por la cantidad de rojo, verde y azul que está en
el color. Each value ranges from 0, which means there is none of that color, to 255, which
means the maximum amount of that color is present. Cada valor va de 0, lo que significa
que no es de ese color, a 255, lo que significa la cantidad máxima de que el color está
presente. Most graphics editing and drawing programs will identify a color's RGB values.
La mayoría de los programas de edición de gráficos y dibujo identificará los valores de
color RGB.

If you know a color's RGB values, you can use it to create a object. Si usted sabe de color
RGB de los valores a, se puede utilizar para crear un objeto Color. For example, an RGB
value for dark red is 235 red, 50 green, and 50 blue, and an RGB value for light orange is
230 red, 220 green, and 0 blue. Por ejemplo, un valor RGB de color rojo oscuro es de 235
rojo, 50 verde y azul de 50 años, y un valor RGB para el color naranja es de 230 rojo, verde
220, y azul 0. The following is an example of an applet that displays dark red text on a light
orange background: El siguiente es un ejemplo de un applet que muestra el texto de color
rojo oscuro sobre un fondo naranja claro:

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

public class GoBucs extends java.applet.Applet { public


class GoBucs extiende java.applet.Applet {

public void init() { public void init () {


Color lightOrange = new Color(230, 220, 0);
lightOrange color = new Color (230, 220, 0);
setBackground(lightOrange); setBackground
(lightOrange);
} }

public void paint(Graphics screen) { public void paint


(pantalla de gráficos) {
Color darkRed = new Color(235, 50, 50); Color =
DarkRed nuevo Color (235, 50, 50);
screen.setColor(darkRed); screen.setColor
(DarkRed);
screen.drawString("Go, Buccaneers!", 5, 50);
screen.drawString ("Vaya, Bucaneros!", 5, 50);
} }
} }
Dark red on a light orange background isn't much more attractive on a Java applet than it is
on the National Football League's Tampa Bay Buccaneers. Rojo oscuro sobre un fondo
naranja la luz no es mucho más atractivo en un applet de Java que está en Tampa la Liga
Nacional de Fútbol Bay Buccaneers. Using RGB values enables you to select from more
than 16.5 million possible combinations, although most computer monitors can only offer a
close approximation for most of them. El uso de valores RGB le permite elegir entre más
de 16,5 millones de combinaciones posibles, aunque la mayoría de los monitores de
ordenador sólo puede ofrecer una buena aproximación para la mayoría de ellos. For
guidance on whether light-light-light-semidark-midnight-blue goes well with medium-
light-semidark-baby-green, purchase a copy of the upcoming Teach Yourself Color Sense
While Waiting in Line at This Bookstore from Sams.net Publishing. Para obtener
orientación acerca de si la luz-la luz-la luz-semidark de la medianoche-azul va bien con
medios-ligeros-semidark-bebé-verde, comprar una copia de la próxima sentido Teach
Yourself color mientras espera en fila en esta librería de Sams.net publicación .

Another way to select a color in a Java program is the HSB system, which stands for Hue
Saturation Brightness. Otra forma de seleccionar un color en un programa Java es el
sistema HSB, que significa Tono Saturación Brillo. Each of these is a floating-point
number that ranges from 0.0 to 1.0. Cada uno de estos es un número de punto flotante que
va desde 0.0 a 1.0. The HSB system isn't as commonly supported in graphics software, so
you won't be using it as often in your programs as you use RGB values. El sistema HSB no
es tan común el apoyo en el software de gráficos, por lo que no va a utilizar tan a menudo
en los programas que se utilizan valores RGB. However, one thing HSB values are
convenient for is changing a color's brightness without changing anything else about the
color. Sin embargo, una cosa son los valores HSB es conveniente para cambiar el brillo de
un color sin cambiar nada más sobre el color. You'll see an example of this use and an
example of using HSB values to choose a color in this hour's workshop. Usted verá un
ejemplo de este uso y un ejemplo del uso de los valores HSB para elegir un color en el
taller de esta hora.

Workshop: Displaying a Danger Message Taller: Visualización de un mensaje de peligro


You can use Java applets to present news headlines and other information in different ways.
Puede utilizar los applets de Java para presentar los titulares de noticias y otra información
de diferentes maneras. One special effect you might see on a Web page is text that fades to
black. Uno de los efectos especiales que usted puede ver en una página Web es el texto que
se desvanece a negro. You also might see the reverse--text that brightens from black to
white. También puede ver el reverso - texto que ilumina de blanco a negro. This hour's
workshop uses the and classes to create text that cycles in brightness from dark to bright.
hora de taller de este utiliza el color y las clases de fuente para crear un texto que los
ciclos en el brillo de oscuro a brillante. The text looks like an alert about impending danger,
so the applet will be called . El texto se ve como una alerta sobre el peligro inminente, por
lo que el applet se llama Peligro.

To make the applet more useful, the text of the warning will be set from a parameter on a
Web page. Para hacer que el applet más útil, el texto de la advertencia que se establecerá a
partir de un parámetro en una página Web. The text that will be used in this example warns
of a "Core breach in Sector 12," but you can substitute other threatening text of similar
length. El texto que se utilizará en este ejemplo, advierte de una "violación de la base en el
Sector 12," pero se puede sustituir otro tipo de texto amenazantes de similar longitud.

If you're at a secure place in your life right now and can't think of anything suitably
menacing, feel free to choose one of the following: Si estás en un lugar seguro en su vida
ahora y no puedo pensar en nada convenientemente amenazadora, no dude en elegir uno de
los siguientes:

 "Mother-in-law wants to visit" "Madre-en-ley quiere visitar"


 "Boss approaching" "Boss se acerca"
 "Dallas Cowboys scheduled to play here" "Dallas Cowboys programado para jugar aquí"
 "We have no bananas today" "No tenemos los plátanos de hoy"
 "No hamburger--cheeseburger" "No hamburguesa - hamburguesa con queso"

Create a new file in your word processor called . Crear un nuevo archivo en el procesador
de textos llamado Danger.java. Each section of the applet will be described as you enter
it. Cada sección del applet se describirá como usted entrar en él. Begin with the following
statements: Comienza con las siguientes afirmaciones:

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

public class Danger extends java.applet.Applet { public


class peligro se extiende java.applet.Applet {
String text = "No text has been specified"; String
texto = "No hay texto ha sido determinada";
float hue = (float) 0.5; flotador color = (float) 0.5;
float saturation = (float) 0.8; flotador saturación =
(float) 0.8;
float brightness = (float) 0.0; flotador brillo =
(float) 0.0;
Font textFont = new Font("Dialog", Font.BOLD, 20);
textFont fuente = new Font ("Dialog", Font.Bold, 20);
int textX; int textX;
The program begins like most applets that you will create. El programa se inicia como la
mayoría de los applets que va a crear. The classes, such as , , and , are made available for
use in this program with the statement. Las clases java.awt, como Fuente, Color y
FontMetrics, se ponen a disposición para su uso en este programa con la declaración de
importación. The statement defines as a subclass of the class, as all applets must be. La
declaración de clase define peligro como una subclase de la clase Applet, como todos
los subprogramas debe ser.

The next several lines define variables and objects that will be used during the program.
Las líneas próximos definir las variables y los objetos que se utilizarán durante el
programa. The string variable is created with a default value, and it will be used to store
the text that should be displayed on-screen. El texto variable de cadena se crea con un
valor predeterminado, y se utilizará para almacenar el texto que debe mostrarse en pantalla.
Three floating-point variables are used to store values for a color using its Hue Saturation
Brightness (HSB) ratings. Tres variables de punto flotante se utilizan para almacenar
valores de un color con su tono saturación de brillo (HSB) valoraciones. The portion of
each line converts the value that follows it into a floating-point number. El flotador)
parte (de cada línea convierte el valor que le sigue en un número de punto flotante. This
conversion must be done because the , , and variables must be of type . Esta conversión
se debe hacer, porque el matiz, saturación y brillo de las variables deben ser de tipo
float.

The text of the applet will be displayed in 20-point Dialog bold. El texto del applet
aparezca en negrita en el diálogo de 20 puntos. In order to do this, you need to create a
object to store that font's values. Con el fin de hacer esto, necesita crear un objeto Font
para almacenar fuentes de valores que. The object called is created for this purpose. El
llamado textFont objeto Font está creado para este propósito. Finally, the integer variable
will be used when you're centering text from left-to-right on the screen. Por último, la
variable de entero textX se utiliza cuando se está centrando el texto de izquierda a derecha
en la pantalla.

After inserting a blank line, continue entering the program by entering the method of the
applet: Después de insertar una línea en blanco, siga introduciendo el programa de peligro
por entrar en el método init () del applet:

public void init() { public void init () {


setBackground(Color.black); setBackground
(Color.Black);
String paramName = getParameter("TEXT"); paramName
String = getParameter ("TEXT");
if (paramName != null) if (paramName! = null)
text = paramName; text = paramName;
FontMetrics fm = getFontMetrics(textFont); FontMetrics
fm = getFontMetrics (textFont);
textX = size().width / 2 - fm.stringWidth(text) / 2;
textX = size () 2. ancho / 2 - fm.stringWidth (texto) /;
} }

The method is handled once when the applet is first run, and then it is never handled again.
El método init () se maneja una vez cuando el applet se ejecuta por primera vez, y
entonces nunca se maneja de nuevo. It's a good place to set up some things that weren't set
up when variables and objects were created. Es un buen lugar para configurar algunas cosas
que no se crearon cuando las variables y los objetos fueron creados. The first thing that
happens in this method is the background of the applet is set to black by using the method
inherited by from the class. Lo primero que sucede en este método es el fondo del applet
se establece en negro mediante el setBackground () método heredado por Peligro de la
clase Applet.

Next, the parameter called is retrieved from the Web page that contains this applet. A
continuación, el parámetro llamado TEXT es encontrado en la página Web que contiene este
applet. If no parameter is found, the default text stored in will be displayed. Si no tiene un
parámetro que se encuentran, el texto predeterminado almacenado en el texto se mostrará.
Otherwise, the text specified by the parameter will be stored in . De lo contrario, el texto
especificado por el parámetro se almacenará en el texto.

The class measures how wide a line of text will appear when it is displayed. La clase
FontMetrics medidas de la anchura de una línea de texto aparece cuando se muestra.
Using the method of and the applet's method, you can center text on-screen. Uso de la
stringWidth () de FontMetrics y el tamaño de la applet () método, se puede centrar el
texto en pantalla. The variable stores the horizontal position where the text should be
displayed. La variable almacena textX la posición horizontal donde debe ser el texto que se
muestra.

Now continue by entering the method of your class, which is called whenever the display
on-screen needs to be updated. Ahora hay que continuar introduciendo el método paint ()
de la clase, que se llama cada vez que la visualización en pantalla debe ser actualizada.
Leave a blank line after the method and enter the following: Deja una línea en blanco
después de que el método init () y escriba lo siguiente:

public void paint(Graphics screen) { public void paint


(pantalla de gráficos) {
Color textColor = Color.getHSBColor(hue, saturation,
brightness); Color = textColor Color.getHSBColor (tono,
saturación, brillo);
screen.setColor(textColor); screen.setColor
(textColor);
screen.setFont(textFont); screen.setFont (textFont);
screen.drawString(text, textX, 30); screen.drawString
(texto, textX, 30);
pause(250000); pausa (250.000);
brightness += 0.05; brillo + = 0,05;
if (brightness > 1) { si (brillo> 1) {
brightness = (float) 0.0; brillo = (float) 0.0;
pause(250000); pausa (250.000);
} }
repaint(); repaint ();

} }

The method takes a object called as an argument. El método paint () toma un objeto
Graphics llamada pantalla como un argumento. This object holds all the information
needed to display something on-screen, and it has several methods you'll use. Este objeto
contiene toda la información necesaria para mostrar algo en pantalla, y tiene varios métodos
que vamos a usar.

The object called is created using the HSB variables to select the color. El objeto de
color llamado textColor se crea utilizando las variables HSB para seleccionar el color.
The object then becomes the current display color using the method of . El objeto
textColor se convierte en el color de la pantalla actual mediante el setColor () de la
pantalla.

Using the method of , the variable is displayed at the (x,y) position of and 30. Uso de la
drawString () de la pantalla, el texto de la variable se muestra en la x, y) la
posición (de textX y 30. The color of the text is the current display color. El color del texto
es el color de la pantalla actual. After the text has been displayed, a method is called with
an argument of 250,000. Después de que el texto se ha mostrado, una pausa () se llama al
método con un argumento de 250.000. You'll see what this method does when you add it to
your program. Usted verá lo que este método no hace cuando se agrega a su programa.
In order for the text to change in brightness, you have to change the value of the variable.
Para que el texto a los cambios en el brillo, lo que tienes que cambiar el valor de la variable
de brillo. The program increases the variable .05 (a 5 percent change), and if the variable
has reached the maximum brightness of 1.0, it is reset to 0.0. El programa aumenta la
variable de 0,05 (una variación del 5 por ciento), y si la variable ha alcanzado el máximo
brillo de 1.0, se pone a 0.0. Whenever must be reset to 0.0, the program calls the method.
Cada vez que el brillo se debe ajustar a 0.0, el programa llama al método pause ().

The last thing that takes place in the method is the statement. Lo último que se lleva a
cabo en el método paint () es el repaint (); comunicado. You use this statement any
time you need to redraw the screen because something has changed. Puede utilizar esta
declaración en cualquier momento que usted necesita para volver a dibujar la pantalla
porque algo ha cambiado. Because the variable has changed, you know there's a need to
redisplay the text at the new brightness. Dado que la variable cambia el brillo, usted sabe
que hay una necesidad de volver a mostrar el texto en el brillo de nuevo. The statement
causes the method to begin again. El repaint () declaración hace que el método paint ()
para comenzar de nuevo.

The method handles most of the work that takes place during the applet. El método paint
() maneja la mayor parte del trabajo que se lleva a cabo durante el applet de peligro. All
you have left to add are two short methods called and . Todo lo que han dejado de añadir
dos métodos corto llamado update () y pausa (). Enter a blank line at the end of your
program, and then continue with the following statements: Introduzca una línea en blanco
al final de su programa, y luego continuar con las siguientes afirmaciones:

public void update(Graphics screen) { public void


actualizar (pantalla de gráficos) {
paint(screen); pintura (pantalla);
} }

void pause(int duration) { anular la pausa (duración int)


{
for (int pause = 0; pause < duration; pause++); for
(int pausa = 0; <duración de la pausa, una pausa + +);
} }

} }

The method is one of the methods that normally works behind the scenes as an applet runs.
El método update () es uno de los métodos que normalmente funciona en segundo plano
como un applet se ejecuta. It is handled any time the screen needs to be repainted or the
statement is used. Se maneja todo momento la pantalla tiene que ser pintado o repintado
de la () se utiliza. The method clears the screen and calls on to do its work. El método
update () borra la pantalla y hace un llamamiento a paint () para realizar su trabajo.
However, clearing the screen when you're changing graphics or text often causes things to
flicker badly in a Java program. Sin embargo, borrar la pantalla cuando se está cambiando
de gráficos o de texto a menudo hace que las cosas parpadeo mal en un programa Java. In
this code, you're overriding the method so it does not clear the screen at all, which will
improve the quality of your applet's display. En este código, que está reemplazando el
método update () por lo que no se borra la pantalla en absoluto, lo que mejorará la calidad
de su pantalla applet. You'll learn more about this procedure during Hour 18, "Creating
Animation." Usted aprenderá más acerca de este procedimiento durante la hora 18,
"Creación de animaciones."

The last thing in your applet is the method, which takes an argument called . Lo último en
el applet es el método pause (), que toma un argumento duración llamado. The method
runs an empty loop ranging from 0 to the value of . El método se ejecuta un bucle vacío
para que van desde 0 hasta el valor de duración. This loop causes the program to pause.
Este ciclo hace que el programa para hacer una pausa. The higher the value of , the longer
the pause. Cuanto mayor sea el valor de duración, más larga es la pausa. When you are
displaying changing graphics or text, you might need pauses of some kind to prevent things
from changing too quickly. Cuando usted está cambiando la presentación de gráficos o de
texto, es posible que necesite una pausa de algún tipo para evitar que las cosas cambien
demasiado rápido. This method is one way to create these pauses. Esta pausa () es una
manera de crear estas pausas.

Save the file, which should resemble Listing 16.3. Guarde el archivo Danger.java, que
debe ser similar de venta 16.3. The only difference might be in the way you have indented
methods and other statements. La única diferencia podría estar en la forma en que han
sangrado métodos y otras declaraciones. That does not have to be changed in order for the
program to run, but indentation and other spacing can make a program easier to understand.
Eso no tiene que ser cambiado para que el programa se ejecute, pero el sangrado y el
espaciamiento de otros puede hacer un programa más fácil de entender.

Listing 16.3. Listado de 16.3. The full text of Danger.java. El texto completo de
Danger.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Danger extends java.applet.Applet { 3
público de clases peligro extiende java.applet.Applet {
4: String text = "No text has been specified"; 4: String
texto = "No hay texto ha sido determinada";
5: float hue = (float) 0.5; 5: flotador color = (float)
0.5;
6: float saturation = (float) 0.8; 6: la saturación del
flotador = (float) 0.8;
7: float brightness = (float) 0.0; 7: el brillo del
flotador = (float) 0.0;
8: Font textFont = new Font("Dialog", Font.BOLD, 20); 8:
textFont nuevo Font Fuente = ("diálogo", Font.Bold, 20);
9: int textX; 9: int textX;
10: 10:
11: public void init() { 11: public void init () {
12: setBackground(Color.black); 12: setBackground
(Color.Black);
13: String paramName = getParameter("TEXT"); 13: paramName
String = getParameter ("TEXT");
14: if (paramName != null) 14: if (paramName = null!)
15: text = paramName; 15: text = paramName;
16: FontMetrics fm = getFontMetrics(textFont); 16:
FontMetrics fm = getFontMetrics (textFont);
17: textX = size().width / 2 - fm.stringWidth(text) / 2;
17: textX = size ();. Ancho / 2 - fm.stringWidth (texto) /
2
18: } 18:}
19: 19:
20: public void paint(Graphics screen) { 20: public void
paint (pantalla de gráficos) {
21: Color textColor = Color.getHSBColor(hue, saturation,
brightness); 21: color = textColor Color.getHSBColor (tono,
saturación, brillo);
22: screen.setColor(textColor); 22: screen.setColor
(textColor);
23: screen.setFont(textFont); 23: screen.setFont
(textFont);
24: screen.drawString(text, textX, 30); 24:
screen.drawString (texto, textX, 30);
25: pause(250000); 25: pausa (250.000);
26: brightness += 0.05; 26: brillo + = 0,05;
27: if (brightness > 1) { 27: if (brillo> 1) {
28: brightness = (float) 0.0; 28: brillo = (float) 0.0;
29: pause(250000); 29: pausa (250.000);
30: } 30:}
31: repaint(); 31: repaint ();
32: } 32:}
33: 33:
34: public void update(Graphics screen) { 34: public void
actualizar (pantalla de gráficos) {
35: paint(screen); 35: pintura (pantalla);
36: } 36:}
37: 37:
38: void pause(int duration) { 38: pausa void (int tiempo)
{
39: for (int pause = 0; pause < duration; pause++); 39:
for (int pausa = 0; <duración de la pausa, una pausa + +);
40: } 40:}
41: 41:
42:}

After compiling the file with the compiler tool, you need to create a Web page that
contains the applet. Después de compilar el archivo con la herramienta del compilador
javac, es necesario crear una página Web que contiene el applet Peligro. Create a new
file with your word processor called , and enter the text of Listing 16.4 into the file. Crear
un nuevo archivo con su procesador de textos llamado Danger.html, y escriba el texto del
listado 16.4 en el archivo.

Listing 16.4. Listado de 16.4. The full text of Danger.html. El texto completo de
Danger.html.
1: <applet code="Danger.class" height=60 width=400> 2:
<param name="TEXT" value="Core breach in Sector 12"> 1:
code="Danger.class" <applet height=60 width=400> 2:
name="TEXT" <param violación value="Core en el sector 12">
3: </ applet>

You can change the value in Line 2 to any other menacing sounding text, as long as it is
similar in size to . Puede cambiar el valor de la línea 2 a cualquier otro texto que suena
amenazante, mientras que es similar en tamaño a la violación central en el sector
12. Use the tool to view the Web page with the following command: Utilice la
herramienta appletviewer para ver la página web con el siguiente comando:

appletviewer Danger.html appletviewer Danger.html

Figure 16.2 shows the output of the applet. Figura 16.2 muestra la salida del applet
Peligro.

Figura 16.2. A screen capture of the applet as it runs with the tool. Una captura de
pantalla del applet peligro ya que se ejecuta con la herramienta appletviewer.

Summary Resumen
Now that you can use and objects in your programs to change the color scheme, you can
no longer feign ignorance when it comes to designing an attractive applet. Ahora que se
puede utilizar de fuente y color de los objetos en sus programas para cambiar el
esquema de color, ya no se puede fingir ignorancia cuando se trata de diseñar un applet
atractivo. By using fonts and color instead of sticking to the familiar black text on a light
gray background, you can draw more attention to elements of your programs and make
them more compelling for users. Mediante el uso de fuentes y el color en lugar de apegarse
al texto negro familiar en un fondo gris claro, usted puede llamar más la atención a los
elementos de sus programas y hacerlos más atractivos para los usuarios. You also, of
course, can write programs that look MAH-ve-lous. También, por supuesto, puede escribir
programas que se ven MAH-ve-Lous. It's what Fernando would want you to do. Es lo que
Fernando se quiere que hagas.

Q&A Q & A
Q Is there a limit to the point size that can be used for text? Q ¿Hay un límite en el
tamaño de punto que se puede utilizar para el texto?

A The limiting factor is the height and width of your applet window or the part of an
applet the text is supposed to be displayed in. Point sizes typically range from 9-point text
for small lines that are readable to 48-point text for large headlines. Un factor limitante es
el de la altura y la anchura de la ventana del applet o la parte de un applet el texto que se
supone que se muestren in tamaños punto suelen oscilar entre el texto del punto 9 para
pequeñas líneas que se pueden leer a punto de texto 48 para grandes titulares. Choosing
the right size depends on the font typeface as well as the size, so it's largely a matter of
trial and error. Elegir el tamaño adecuado depende del tipo de letra, así como el tamaño,
por lo que es en gran medida una cuestión de prueba y error.

Q What happens if a color defined in a Java program can't be displayed on the monitor
of someone displaying the program? Q ¿Qué pasa si un color definido en un programa
Java no se puede visualizar en el monitor de una persona que muestra el programa? For
example, if my monitor is set to display only 256 colors, what will occur if I choose one
of the 16.5 million colors that isn't in those 256? Por ejemplo, si el monitor está
configurado para mostrar sólo 256 colores, lo que ocurrirá si elijo uno de los 16,5
millones de colores que no está en los 256?

A When a monitor can't display a color selected with a or method, it shows the closest
existing color as a substitute. Un Cuando un monitor no puede mostrar un color
seleccionado con un setColor () o setBackground () método, se muestra el color
más cercano existente como un sustituto. An example of this kind of substitution is the
applet, which runs differently depending on the number of colors that can be shown as
the text cycles from black to light blue to white. Un ejemplo de este tipo de sustitución es
el applet de peligro, que corre de forma diferente en función del número de colores
que se pueden mostrar como los ciclos de texto desde el negro a la luz azul a blanco.

Quiz Quiz
Test whether your font and color skills are MAH-ve-lous by answering the following
questions. habilidades de prueba si su fuente y el color son MAH-ve-Lous contestando las
siguientes preguntas.

Questions Preguntas

1. Which one of the following is not a constant used to select a color? 1. ¿Cuál de las
siguientes no es una constante que utiliza para seleccionar un color?

(a) (A) Color.cyan


(b) (B) Color.teal
(c) (C) Color.magenta

2. When you change the color of something and redraw it on an applet window, what
must you do to make it visible? 2. Cuando se cambia el color de algo y volver a dibujarlo en
una ventana del applet, lo que tiene que hacer para que sea visible?

(a) Use the method. (A) Utilice el drawColor () método.


(b) Use the statement. (B) Utilice el repaint () declaración.
(c) Do nothing. (C) No hacer nada.

3. What do the initials HSB stand for? 3. ¿Qué significan las siglas HSB representan?

(a) Hue Saturation Brightness (A) Brillo Saturación Matiz


(b) Hue Shadows Balance (B) Balance de Tono Sombras
(c) Lucy in the Sky with Diamonds (C) Lucy en el cielo con diamantes

Answers Respuestas

1. b. 1. B.

2. b. 2. B. The call to causes the method to be manually called. La llamada a repaint ()


hace que el método paint () de forma manual llamado.

3. a. 3. A. If c were the right answer, you could use colors that would only be visible years
later during flashbacks. Si c fueron la respuesta correcta, puede usar los colores que sólo
serían visibles años más tarde, durante flashbacks.

Activities Actividades
To further explore the spectrum of possibilities when using fonts and color in your
programs, do the following activities: Para explorar el espectro de posibilidades al utilizar
fuentes y el color en sus programas, realizar las siguientes actividades:

 Remove the method from the applet to see what effect it has on the quality of the
display. Retire el método update () del applet Peligro para ver qué efecto tiene sobre
la calidad de la pantalla.
 Add a way to specify the background of the applet by sending parameters for the RGB
values of the desired background color. Agregar una forma de especificar el fondo del
applet peligro mediante el envío de parámetros para los valores RGB del color de fondo
deseado.

 17 horas
o Trabajar con gráficos
 Utilización de gráficos en un applet
 Dibujar líneas y formas
 Figura 17.1.
 Dibujar líneas
 Dibujo de rectángulos
 Dibujo de óvalos y círculos
 Dibujo de Polígonos
 Crear Javaman
 Listado de 17.1. El texto completo de JavaMan.java.
 Listado de 17.2. El texto completo de JavaMan.html.
 Taller: Atención de dibujo para algo
 Listado de 17.3. El texto completo de Drawing.java.
 Listado de 17.4. El texto completo de Drawing.html.
 Figura 17.2.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 17 17 horas
Working with Graphics Trabajar con gráficos

During the previous hour you had a chance to experience the joy of text by displaying
strings in a variety of fonts and colors. Durante la hora anterior que tenía la oportunidad de
experimentar la alegría de texto que muestra las cadenas en una variedad de fuentes y
colores. Using these Java classes makes the programming language an enjoyable text aid,
but at some point you probably were expecting more. El uso de estas clases de Java hace
que el lenguaje de programación de una ayuda de texto agradable, pero en algún momento
es probable que se esperaba más. There's more to life than text, and this hour is evidence of
that. Hay más en la vida de texto, y esta hora es prueba de ello. You'll get a chance to draw
shapes of different colors in a program--everything from rectangles to ovals to lines. Usted
tendrá la oportunidad de dibujar formas de diferentes colores en un programa - desde
rectángulos para óvalos a las líneas.

The following subjects will be covered: Los siguientes temas serán cubiertos:

 The drawing methods of the class Los métodos de dibujo de la clase Graphics

 Drawing lines Dibujo de líneas


 Drawing rectangles, rounded rectangles, and 3-D rectangles Dibujo de rectángulos,
rectángulos redondeados, rectángulos y 3-D
 Drawing polygons Dibujo de polígonos
 Drawing ovals Dibujar óvalos
 Drawing with different colors Dibujo con colores diferentes
 Drawing filled and unfilled shapes Dibujo de formas llenas y sin relleno

Using Graphics in an Applet Utilización de gráficos en un applet


This isn't meant as a knock to those of us who enjoy displaying arrays, incrementing
variables, or using a constructor method, but let's face it--many subjects in a programming
language such as Java tend to be dry. Esto no pretende ser un golpe para aquellos de
nosotros que disfrutan de las matrices que muestra, incrementando las variables, o usando
un método constructor, pero seamos sinceros - muchos temas en un lenguaje de
programación como Java tienden a ser secos. It's hard to impress your non-programming
acquaintances with the way your - loop determines which method to use in a mathematical
application. Es difícil de impresionar a su programación conocidos no con el modo en que
hacer - bucle while determina el método a utilizar en una aplicación matemática. Dates
don't get nearly as excited as you do when a - block statement handles a variety of
different circumstances correctly. Las fechas no tienen casi tan entusiasmado como cuando
un interruptor - bloque de sentencias asas de una variedad de circunstancias diferentes
correctamente. Nobody ever attracted a mate because they use the conditional operator
(using conditioner, on the other hand...). Nadie atrajo a un compañero debido a que utilizan
el operador condicional (con acondicionador, por otra parte ...). Graphics programming is
the exception to this general rule. programación de gráficos es la excepción a esta regla
general. When you write a program that does something interesting with graphics, it's a
way to have fun with a programming language and impress relatives, friends, strangers, and
prospective employers. Cuando se escribe un programa que hace algo interesante con
gráficos, es una manera de divertirse con un lenguaje de programación e impresionar a
familiares, amigos, extraños, y los posibles empleadores.

Drawing things such as lines and polygons is as easy in a Java applet as displaying text.
Dibujo cosas tales como líneas y polígonos es tan fácil en un applet de Java como mostrar
el texto. You use a method of the class inside the method of the program. Se utiliza un
método de la clase de gráficos dentro del método paint () del programa. The class stores
information required to display something on-screen. La clase Graphics almacena la
información necesaria para mostrar algo en pantalla. The most common use of the class is
to create an object that represents the applet window. El uso más común de la clase es crear
un objeto que representa la ventana del applet. This object is often called , and its methods
are used to draw text with a command such as the following: Este objeto Graphics se
llama a menudo la pantalla, y sus métodos se utilizan para dibujar texto con un
comando como el siguiente:

screen.drawString("Draw, pardner!", 15, 40);


screen.drawString ("Empate, compañero!", 15, 40);

This statement causes the text to be displayed at the (x,y) coordinates of (15,40). Esta
declaración hace que el texto Dibujar, compañero! Se muestren en la (x, y) las
coordenadas de (15,40).

All of the shape- and line-drawing methods work using the same (x,y) coordinate system as
text. Todos los métodos de forma-y el dibujo de línea de trabajo utilizando la misma (x, y)
el sistema de coordenadas en forma de texto. The (0,0) coordinate is at the upper-left corner
of the applet window. El (0,0) de coordenadas está en la esquina superior izquierda de la
ventana del applet. x values go up as you head to the right, and y values go up as you head
downward. x valores suben a medida que la cabeza hacia la derecha, y los valores y subir a
medida que la cabeza hacia abajo. You can determine the maximum (x,y) value that you
can use in an applet with the following statements: Puede determinar el máximo (x, y) el
valor que se puede utilizar en un applet con las siguientes afirmaciones:

int maxXValue = size().width; maxXValue int = size () de


ancho.;
int maxYValue = size().height; maxYValue int = size () de
altura.;
Drawing Lines and Shapes Dibujar líneas y formas
Figure 17.1 shows JavaMan, an illustration composed of all the different things you'll be
learning to draw during this hour: La figura 17.1 muestra Javaman, una ilustración
compuesta de todas las cosas que usted aprenderá a elaborar durante esta hora:

 Lines: JavaMan's arm and fingers are lines. Líneas: Javaman brazo y los dedos son líneas.
 Rounded rectangles: The border of the illustration is a rectangle with rounded corners.
Rectángulos redondeados: La frontera de la ilustración es un rectángulo con esquinas
redondeadas.
 Rectangles: JavaMan's torso is composed of a filled gray rectangle covered with 100
unfilled rectangles. Rectángulos: torso Javaman se compone de un rectángulo relleno gris
cubierto con 100 rectángulos vacíos. His mouth is another rectangle. Su boca es otro
rectángulo.
 Ovals: JavaMan's eyes are ovals. Óvalos: Javaman ojos son óvalos.
 Polygons: JavaMan's hat is a polygon. n polígonos: el sombrero Javaman es un polígono.

Figura 17.1. JavaMan, a figure composed of Java polygons and lines. Javaman, una figura
compuesta de polígonos y las líneas de Java.

With the exception of lines, all of the shapes you can draw can be filled or unfilled. Con la
excepción de las líneas, todas las formas que puede dibujar puede ser con o sin relleno. A
filled shape is drawn with the current color completely filling the space taken up by the
shape. Una forma llena se dibuja con el color actual llenando completamente el espacio
ocupado por la forma. Unfilled shapes just draw a border with the current color. formas
vacías sólo establecer una frontera con el color actual. The rounded rectangle around Figure
17.1 is an example of an unfilled shape. El rectángulo redondeado alrededor de la figura
17.1 es un ejemplo de una forma sin relleno. Only the border of the rectangle is drawn. Sólo
el borde del rectángulo se dibuja. JavaMan's hat is a filled shape because the entire hat is
filled in with the same color. Javaman sombrero es una forma rellena el sombrero porque
todo se llena con el mismo color.

Before you create an applet to draw JavaMan, each of the drawing methods will be
described. Antes de crear un applet para dibujar Javaman, cada uno de los métodos de
dibujo se describe. The object will be used as the object throughout this section, and it's
the object used as an argument to the method of an applet. El objeto de la pantalla se
utiliza como objeto Graphics de toda esta sección, y es el objeto que se utiliza como
argumento para la pintura () de un applet.

Drawing Lines Dibujar líneas

To draw a line, a statement such as the following is used: Para dibujar una línea, una
declaración como la siguiente se utiliza:

screen.drawLine(200,110,170,115); screen.drawLine
(200110170115);
This statement draws a line beginning at the (x,y) coordinate of (200,110) and ending at
(170,115). Esta declaración establece una línea que comienza en las coordenadas (x, y)
coordenadas de (200.110) y termina en (170,115). All lines in Java are one pixel in width,
so you have to draw several lines side by side if you want to draw a thick line. Todas las
líneas en Java son un píxel de ancho, así que tienes que dibujar varias líneas lado a lado, si
desea dibujar una línea gruesa.

Drawing Rectangles Dibujo de rectángulos

Rectangles can be filled or unfilled, and they can have rounded corners or square ones.
Rectángulos pueden ser con o sin relleno, y que pueden tener las aristas redondeadas o los
cuadrados. The following statement draws an unfilled rectangle with square corners: La
declaración siguiente se dibuja un rectángulo sin relleno con esquinas cuadradas:

screen.drawRect(245,65,20,10); screen.drawRect
(245,65,20,10);

This statement draws a rectangle with its upper-left corner at the (x,y) coordinate of
(245,65). Esta declaración se dibuja un rectángulo con la esquina superior izquierda en (x,
y) coordenadas de (245,65). The width of the rectangle is 20 and the height is 10. La
anchura del rectángulo es 20 y la altura es de 10. These dimensions are expressed in pixels,
the same unit of measure used for coordinates. Estas dimensiones se expresan en píxeles, la
misma unidad de medida utilizada para las coordenadas.

If you want to make the rectangle filled in, use the method instead of . Si usted desea
hacer el rectángulo relleno, utilice el método fillRect () en lugar de drawRect (). The
arguments are the same: Los argumentos son los mismos:

screen.fillRect(245,65,20,10); screen.fillRect
(245,65,20,10);

You can draw rectangles with rounded corners instead of square ones by using the and
methods. Puede dibujar rectángulos con esquinas redondeadas en lugar de los cuadrados
mediante el drawRoundRect () y fillRoundRect () métodos. As you might expect, you
use the to draw an unfilled rectangle, and you use the method to draw a filled rectangle.
Como es de esperar, se utiliza el drawRoundRect () para dibujar un rectángulo sin relleno,
y se utiliza el fillRoundRect () para dibujar un rectángulo relleno. These methods have
two extra arguments at the end that specify the distance from the corner to begin making it
round. Estos métodos tienen dos argumentos adicionales a fin de que especificar la
distancia desde la esquina para empezar a hacer que todo el año. The following statement
draws an unfilled, rounded rectangle: La declaración siguiente se dibuja un rectángulo sin
relleno, redondeado:

screen.drawRoundRect(10,10,size().width-20, size().height-
20, 15, 15); screen.drawRoundRect (10,10, size (),. ancho-
20, calibre (15). altura 20, 15);

This rectangle has its upper-left corner at the (10,10) coordinate. Este rectángulo tiene su
esquina superior izquierda en el (10,10) de coordenadas. The last two arguments to specify
that the corner should begin rounding 15 pixels away from the corner at (10,10). Los dos
últimos argumentos para drawRoundRect () especifica que la esquina debe comenzar
redondeo 15 píxeles de distancia desde la esquina al (10,10). As with other rectangle
methods, the third and fourth arguments specify how wide and tall the rectangle should be.
Al igual que con otros métodos de rectángulo, los argumentos tercero y cuarto especificar
la anchura y altura del rectángulo debe ser. In this case, and are used so that the rectangle
can use the size of the applet window as a way to determine how large the rectangle should
be. En este caso, el tamaño (). Anchura y tamaño (). Altura se utilizan para que el
rectángulo se puede utilizar el tamaño de la ventana del applet como una forma de
determinar el tamaño del rectángulo debe ser.

Drawing Ovals and Circles Dibujo de óvalos y círculos

To draw ovals and circles, use the and methods. Para dibujar círculos y óvalos, utiliza el
drawOval () y fillOval () métodos. You can draw a circle by specifying the same
width and height values, as in the following: Puede dibujar un círculo especificando la
misma anchura y los valores de altura, como en el siguiente:

screen.fillOval(245,45,5,5); screen.fillOval (245,45,5,5);

This statement draws an oval at (245,45) with a height and width of 5. Esta afirmación se
basa en un óvalo (245,45) con una altura y anchura de 5. Changing one of the height or
width coordinates to a different value would make the shape an oval instead of a circle. un
cambio de la altura o ancho de las coordenadas a un valor diferente sería la forma de un
óvalo en lugar de un círculo.

Drawing Polygons Dibujo de Polígonos

Polygons are the most complicated shape to draw because they have a varying number of
points. Los polígonos son la forma más complicada de elaborar debido a que tienen un
número variable de puntos. To set up the points, all of the x coordinates of the polygon are
put into an array of integers. Para configurar los puntos, todas las coordenadas x del
polígono se ponen en una matriz de enteros. All of the y coordinates are then put into
another array, in the same order. Todas las coordenadas y luego se puso en otra matriz, en
el mismo orden. The and methods are used with the arrays and the number of points as
arguments: El drawPolygon () y FillPolygon () se utiliza con las matrices y el número
de puntos como argumentos:

int[] xPoints = { 205, 305, 240 }; int [] = {xPoints 205,


305, 240};
int[] yPoints = { 43, 40, 15 }; int [] = {yPoints 43, 40,
15};
int points = 3; int = 3 puntos;
screen.fillPolygon(xPoints, yPoints, points);
screen.fillPolygon (xPoints, yPoints, puntos);

You can use the method to draw the entire polygon with the same color or use to only
draw the polygon's outline. Usted puede utilizar el FillPolygon () para dibujar el
polígono entero con el mismo color o drawPolygon () para dibujar sólo polígono
esquema. All polygons are completed automatically by making the last point join up with
the first point. Todos los polígonos se completan automáticamente al hacer el último punto
se unen con el primer punto. In this example, (240,15) will connect to (205,43). En este
ejemplo, (240,15) se conectará a (205,43).

Another way to draw polygons is to use a object to hold all of the point values, as in the
following: Otra forma de dibujar polígonos es utilizar un objeto Polígono de celebrar todos
los valores de punto, como en lo siguiente:

int[] yellowX = { 64, 126, 136, 74, 64 }; int [] =


{yellowX 64, 126, 136, 74, 64};
int[] yellowY = { 228, 176, 184, 240, 228 }; int [] =
{amarillento 228, 176, 184, 240, 228};
yellow = new Polygon(yellowX, yellowY, 5); amarillo =
nuevo polígono (yellowX, amarillento, 5);
screen.fillPolygon(xPositions, yPositions, points);
screen.fillPolygon (xPositions, yPositions, puntos);

Polygons do not have to meet in a point, however; you can use to draw partial polygons.
Los polígonos no tienen que reunirse en un punto, sin embargo, puede utilizar
drawPolyline () para dibujar polígonos parcial. This is done by specifying two integer
arrays containing all of the points and the number of points, as in the following: Esto se
hace mediante la especificación de dos matrices de enteros que contiene todos los puntos y
el número de puntos, como en lo siguiente:
int[] xPoints = { 205, 305, 240 }; int [] = {xPoints 205,
305, 240};
int[] yPoints = { 43, 40, 15 }; int [] = {yPoints 43, 40,
15};
int points = 3; int = 3 puntos;
screen.drawPolyline(xPoints, yPoints, points);
screen.drawPolyline (xPoints, yPoints, puntos);

Unlike and , this method does not connect the first and last lines. A diferencia de
drawPolygon () y FillPolygon (), este método no se conecta el pasado y las primeras
líneas.

Creating JavaMan Crear Javaman

To put all of these shapes together, load your word processor and create a new file called .
Para poner todas estas formas en conjunto, la carga de su procesador de textos y crear un
nuevo archivo llamado JavaMan.java. Enter Listing 17.1 into the file and save it when
you're done. Introduzca Listado 17,1 en el archivo y guardarlo cuando haya terminado.

Listing 17.1. Listado de 17.1. The full text of JavaMan.java. El texto completo de
JavaMan.java.
1: import java.awt.*; 2: 3: public class JavaMan extends
java.applet.Applet { 4: 5: public void init() { 6:
setBackground(Color.yellow); 7: } 8: 9: public void
paint(Graphics screen) { 10: 11:
screen.setColor(Color.black); 12:
screen.drawRoundRect(10,10,size().width-20, 13:
size().height-20,15,15); 14: 15:
screen.setColor(Color.gray); 16:
screen.fillRect(200,90,100,100); 17: 18:
screen.setColor(Color.blue); 19: for (int x = 200; x < 300;
x += 5) 20: for (int y = 90; y < 190; y += 5) 21:
screen.drawRect(x,y,5,5); 22: 23:
screen.setColor(Color.black); 24:
screen.drawLine(200,110,170,115); 25:
screen.drawLine(170,115,160,90); 26:
screen.drawLine(160,90,150,94); 27:
screen.drawLine(160,90,153,85); 28:
screen.drawLine(160,90,158,83); 29:
screen.drawLine(160,90,163,84); 30: 31:
screen.setColor(Color.white); 32:
screen.fillOval(220,30,60,60); 33: 34:
screen.setColor(Color.green); 35:
screen.fillOval(245,45,5,5); 36:
screen.fillOval(255,45,5,5); 37: 38:
screen.setColor(Color.black); 39:
screen.fillRect(245,65,15,15); 40: 41:
screen.setColor(Color.magenta); 42: int[] xPoints = { 205,
305, 240, 205 }; 43: int[] yPoints = { 43, 40, 15, 43 };
44: int points = 4; 45: screen.fillPolygon(xPoints,
yPoints, points); 46: } 4 1: import java.awt .*; 2: 3:
public class Javaman extiende java.applet.Applet {4: 5:
public void init () {6: setBackground (Color.yellow); 7:}
8: 9: pública anular la pintura (pantalla de gráficos) {10:
11: screen.setColor (Color.Black); 12: 10,10, size ().
screen.drawRoundRect ancho-20, 13: size (). (altura-20, 15,
15); 14: 15: screen.setColor (Color.gray); 16:
screen.fillRect (200,90,100,100); 17: 18: screen.setColor
(Color.blue); 19: for (int x = 200; x <300; x + = 5) 20:
for (int y = 90; y <190; y + = 5) 21: screen.drawRect (x,
y, 5,5); 22: 23: screen.setColor (color . negro); 24:
screen.drawLine (200110170115); 25: screen.drawLine
(170,115,160,90); 26: screen.drawLine (160,90,150,94); 27:
screen.drawLine (160,90,153,85); 28: screen.drawLine
(160,90,158,83); 29: screen.drawLine (160,90,163,84); 30:
31: screen.setColor (Color.white); 32: screen.fillOval
(220,30,60 , 60); 33: 34: screen.setColor (Color.green);
35: screen.fillOval (245,45,5,5); 36: screen.fillOval
(255,45,5,5); 37: 38 : screen.setColor (Color.Black); 39:
screen.fillRect (245,65,15,15); 40: 41: screen.setColor
(Color.magenta); 42: int [] = {xPoints 205, 305, 240, 205};
43: int [] = {yPoints 43, 40, 15, 43}; 44: int = 4 puntos;
45: screen.fillPolygon (xPoints, yPoints, puntos); 46:} 4
7:}

After compiling the program successfully, create a new file in your word processor called .
Después de compilar el programa con éxito, crear un nuevo archivo en el procesador de
textos llamado JavaMan.html. Enter Listing 17.2 into the file. Introduzca listado 17.2 en el
archivo.

Listing 17.2. Listado de 17.2. The full text of JavaMan.html. El texto completo de
JavaMan.html.

1: <applet code="JavaMan.class" height=220 width=340> 1:


<applet code="JavaMan.class" height=220 width=340>
2: </ applet>

When you use or a Java-capable Web browser to view this applet, you will discover why I
chose computer book writing as a profession over illustration. Cuando se utiliza
appletviewer o un navegador Web capaz de Java para ver este applet, usted descubrirá la
razón por la que escogió el libro equipo escritura como profesión a través de la ilustración.
If you're using , resize the window a few times to see how the rounded black border
changes. Si estás utilizando appletviewer, cambiar el tamaño de la ventana de un par de
veces para ver cómo el negro cambios borde redondeado.

Workshop: Drawing Attention to Something Taller: Atención de dibujo para algo


To draw this hour to a close, you'll create an applet that uses a polygon, several polylines, a
rounded rectangle, and three ovals. Para elaborar esta hora a su fin, va a crear un applet que
utiliza un polígono, varias polilíneas, un rectángulo redondeado, y tres óvalos. The finished
product ought to be a familiar face. El producto final debe ser una cara conocida.

Load your word processor and create a new file called . Cargue el procesador de texto y
crear un nuevo archivo llamado Drawing.java. Enter the full text of Listing 17.3, and then
save and compile the file when you're done. Introduzca el texto completo del listado 17.3, a
continuación, guarde y compile el archivo cuando haya terminado.

Listing 17.3. Listado de 17.3. The full text of Drawing.java. El texto completo de
Drawing.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Drawing extends java.applet.Applet { 3:
Dibujo clase pública se extiende java.applet.Applet {
4: Polygon hair; 4: Polígono de pelo;
5: 5:
6: public void init() { 6: public void init () {
7: int[] hairX = { 125, 131, 156, 217, 270, 314, 244,
233, 7: int [] = {hairX 125, 131, 156, 217, 270, 314, 244,
233,
8: 196, 162, 147, 153, 180, 189, 125 }; 8: 196, 162, 147,
153, 180, 189, 125};
9: int[] hairY = { 314, 122, 75, 57, 96, 287, 319, 118,
9: int [] = {peludas 314, 122, 75, 57, 96, 287, 319, 118,
10: 87, 92, 133, 203, 231, 258, 314 }; 10: 87, 92, 133,
203, 231, 258, 314};
11: hair = new Polygon(hairX, hairY, 15); 11: pelo = new
Polygon (hairX, peludo, 15);
12: 12:
13: setBackground(Color.lightGray); 13: setBackground
(Color.lightGray);
14: } 14:}
15: 15:
16: public void paint(Graphics screen) { 16: public void
paint (pantalla de gráficos) {
17: screen.setColor(Color.white); 17: screen.setColor
(Color.white);
18: screen.fillRoundRect(147,84,103,74,23,23); 18:
screen.fillRoundRect (147,84,103,74,23,23);
19: screen.fillOval(147,94,103,132); 19: screen.fillOval
(147,94,103,132);
20: 20:
21: screen.setColor(Color.black); 21: screen.setColor
(Color.Black);
22: screen.fillPolygon(hair); 22: screen.fillPolygon
(pelo);
23: 23:
24: int[] eyebrow1X = { 151, 168, 174, 171, 178, 193 };
24: int [] = {eyebrow1X 151, 168, 174, 171, 178, 193};
25: int[] eyebrow1Y = { 145, 140, 148, 184, 191, 188 };
25: int [] = {eyebrow1Y 145, 140, 148, 184, 191, 188};
26: screen.drawPolyline(eyebrow1X, eyebrow1Y, 6); 26:
screen.drawPolyline (eyebrow1X, eyebrow1Y, 6);
27: 27:
28: int[] eyebrow2X = { 188, 197, 213, 223 }; 28: int [] =
{eyebrow2X 188, 197, 213, 223};
29: int[] eyebrow2Y = { 146, 141, 142, 146 }; 29: int [] =
{eyebrow2Y 146, 141, 142, 146};
30: screen.drawPolyline(eyebrow2X, eyebrow2Y, 4); 30:
screen.drawPolyline (eyebrow2X, eyebrow2Y, 4);
31: 31:
32: int[] mouthX = { 166, 185, 200 }; 32: int [] = {mouthX
166, 185, 200};
33: int[] mouthY = { 199, 200, 197 }; 33: int [] =
{bocazas 199, 200, 197};
34: screen.drawPolyline(mouthX, mouthY, 3); 34:
screen.drawPolyline (mouthX, bocazas, 3);
35: 35:
36: screen.fillOval(161,148,10,3); 36: screen.fillOval
(161,148,10,3);
37: screen.fillOval(202,145,12,5); 37: screen.fillOval
(202,145,12,5);
38: } 38:}
39:}

The applet includes two methods, and , and a single object as the only variable. El applet
de dibujo incluye dos métodos, init () y paint (), y un objeto único polígono como
la única variable. The object is used to store all the information that's needed to draw a
polygon. El objeto Polígono se utiliza para almacenar toda la información que se necesita
para dibujar un polígono.

The polygon is drawn by setting up an array of integers with the x coordinates of each point
on the polygon. El polígono se dibuja mediante la creación de una matriz de enteros con las
coordenadas x de cada punto del polígono. Next, another array of integers is set up with the
y coordinates of each point. A continuación, otra serie de números enteros se configura con
las coordenadas de cada punto. When both of these are set up, the following statement is
used: Cuando ambos se establecen, la siguiente instrucción se utiliza:

hair = new Polygon(hairX, hairY, 15); pelo = new Polygon


(hairX, peludo, 15);

The first two arguments to the constructor method are the integer arrays-- and . Los dos
primeros argumentos del método constructor Polígono son las matrices de enteros - hairX
y peludo. The last argument is the number of points in the polygon. El último argumento
es el número de puntos en el polígono.

Once you have created a polygon in this manner, you can use the or methods of the class
to draw it. Una vez creado un polígono de esta manera, se puede utilizar el drawPolygon
() o FillPolygon () de la clase Graphics para dibujar. This action takes place in the
method of the applet because you need a object that indicates where the polygon should be
drawn. Esta acción se lleva a cabo en el método paint () del applet ya que necesita un
objeto gráfico que indica que el polígono debe ser elaborado. An object called is used:
Una llamada pantalla de objeto se utiliza:

screen.fillPolygon(hair); screen.fillPolygon (pelo);

The method draws a polygon that is filled in with the current color. El FillPolygon ()
dibuja un polígono que se rellena con el color actual. If you do not want the polygon to be
filled in, you can use the method with two integer arrays instead. Si no desea que el
polígono debe ser rellenado, puede utilizar el drawPolyline () con dos matrices de
enteros en su lugar.

You select colors with the method of the class. Puede seleccionar los colores con la
setColor () de la clase Graphics. Constants from the class such as and are used as
arguments to the method. Las constantes de la clase de color, como Color.Red
Color.green y se utilizan como argumentos a la setColor () método. The following
statement in the method sets the current color to black: La siguiente declaración en el
método paint () establece el color actual negro:

screen.setColor(Color.black); screen.setColor
(Color.Black);

In addition to the polygons, three ovals are drawn in the applet. Además de los polígonos,
tres óvalos se dibujan en el applet de dibujo. The following is one of the statements used
to draw an oval: El siguiente es uno de los estados se utiliza para dibujar un óvalo:

screen.fillOval(161,148,10,3); screen.fillOval
(161,148,10,3);

The first two parameters to the method are the (x,y) coordinates where the oval should be
drawn. Los dos primeros parámetros a la fillOval () método son los (x, y) las
coordenadas donde el óvalo deberían proceder. The last two parameters are the width and
height of the oval. Los dos últimos parámetros son el ancho y la altura del óvalo.

After you have compiled successfully, open a new file in your word processor to create a
the Web page to put the applet on. Después de haber compilado Drawing.java
correctamente, abra un nuevo archivo en el procesador de textos para crear una página Web
de poner el applet en. Create a new file called and enter Listing 17.4 into the file. Crear un
nuevo archivo llamado Drawing.html y entrar de venta 17.4 en el archivo.

Listing 17.4. Listado de 17.4. The full text of Drawing.html. El texto completo de
Drawing.html.
<applet code="Drawing.class" height=340 width=280>
code="Drawing.class" <applet height=340 width=280>

After saving the file, view the applet with the tool or a Web browser. </ Applet>
Después de guardar el archivo, ver el applet con la herramienta appletviewer o un
navegador Web. Figure 17.2 shows what the finished product should look like. Figura 17.2
muestra lo que el producto final debe ser similar.

Figura 17.2. The output of the applet. La salida del applet de dibujo.

If the long black hair, moony expression, and stoned smile aren't enough of a visual clue,
this applet attempts to draw the Mona Lisa using a few polygons and lines. Si el pelo largo
y negro, la expresión de lunares, y la sonrisa apedreado no son suficientes de una pista
visual, este applet intenta dibujar la Mona Lisa usando unos pocos polígonos y líneas.
Leonardo da Vinci didn't have the chance to use Java drawing commands when he created
the real Mona Lisa in 1503-1506, so he used paint instead. Leonardo da Vinci no tuvo la
oportunidad de usar los comandos de dibujo de Java cuando se creó la verdadera Mona Lisa
en 1503-1506, por lo que la pintura utilizada en su lugar. His results were pretty impressive
too, but it took him considerably longer than an hour to finish his version. Sus resultados
fueron bastante impresionante también, pero le tomó mucho más tiempo de una hora para
terminar su versión.
The Louvre, the home of the Mona Lisa, has an extensive Web site at the following
address: El Museo del Louvre, el hogar de la Mona Lisa, tiene un extenso sitio Web en la
siguiente dirección:

http://mistral.culture.fr/louvre/

A picture of the Mona Lisa is displayed under the title La Joconde (Monna Lisa) at the
following address: Un cuadro de la Mona Lisa se muestra bajo el título de La Gioconda
(Mona Lisa) a la siguiente dirección:

http://mistral.culture.fr/louvre/anglais/musee/collec/monna
.htm

Summary Resumen
Drawing something using the polygons and other shapes available with Java might seem
like more trouble than it's worth, especially when you can load image files such as files
and files, as you'll see in the next hour. Dibujo algo con los polígonos y otras formas
disponibles con Java podría parecer más trabajo de lo que vale, sobre todo cuando se puede
cargar archivos de imagen como archivos. GIF y archivos. JPG, como se verá en la
próxima hora. However, graphics depicted with polygons have two advantages over
graphics that are loaded from image files: Sin embargo, los gráficos representados con
polígonos tienen dos ventajas sobre los gráficos que se cargan desde los archivos de
imagen:

 Speed: Even a small graphic, such as an icon, would take longer to load and display than a
series of polygons. Velocidad: Hasta un pequeño gráfico, como un icono, tomaría más
tiempo para cargar y mostrar que una serie de polígonos.
 Scaling: You can change the size of an entire image that uses polygons simply by changing
the values to create it. Escala: Usted puede cambiar el tamaño de una imagen completa
que utiliza polígonos simplemente cambiando los valores para crearlo. For example, you
could add a function to the class that doubles the values for every (x,y) point in the arrays
before you display anything, and it would result in an image twice as large. Por ejemplo,
usted podría agregar una función a la clase de dibujo que duplica los valores para cada
(x, y) el punto en los órdenes antes de mostrar cualquier cosa, y que daría lugar a una
imagen el doble de grande. Polygon images scale much more quickly than image files do
and produce better results. archivos Polígono escala de las imágenes mucho más
rápidamente que la imagen de hacer y producir mejores resultados.
There are many instances where it makes more sense to use graphics files in your programs,
but polygons can be a useful option. Hay muchos casos en los que tiene más sentido utilizar
los archivos de gráficos en sus programas, pero los polígonos puede ser una opción útil.

Q&A Q & A
Q Why does the JavaMan image flicker when I resize the applet window? Q ¿Por qué el
parpadeo de la imagen Javaman cuando cambiar el tamaño de la ventana del applet?

A The reason for this flicker is that the screen is automatically cleared each time the
screen must be repainted. Una razón de esto es que el parpadeo de la pantalla se borra
automáticamente cada vez que la pantalla debe ser repintada. This happens in a method
called that normally works behind the scenes. Esto sucede en un llamado método de
actualización () que normalmente funciona en segundo plano. You can override this
method in your programs to prevent the flickering problem, as you will see during the next
hour. Puede reemplazar este método en sus programas para prevenir el problema
vacilante, como se verá durante la hora siguiente.

Q Ovals and circles don't have corners. Q óvalos y círculos no tiene esquinas. What are
the (x,y) coordinates specified with the fillOval() and drawOval() method? ¿Cuáles son
los (x, y) las coordenadas especificadas en la fillOval () y drawOval () método?

A The (x,y) coordinates represent the smallest x value and smallest y value of the oval or
circle. A El (x, y) coordenadas representan el menor valor de x y el menor valor y del óvalo
o círculo. If you drew an invisible rectangle around it, the upper-left corner of the
rectangle would be the x and y coordinates used as arguments to the method. Si usted
dibujó un rectángulo invisible a su alrededor, la esquina superior izquierda del rectángulo
sería la coordenadas x e y usadas como argumentos al método.

Quiz Quiz
Test whether your Java graphics skills are taking shape by answering the following
questions. Comprobar si tus habilidades gráficas de Java están tomando forma,
respondiendo a las siguientes preguntas.

Questions Preguntas

1. What method is used to change the current color before you draw something in a
program? 1. ¿Qué método se utiliza para cambiar el color actual antes de dibujar algo en
un programa?

(a) (A) shiftColor ()


(b) (B) setColor ()
(c) Could you repeat the question? (C) ¿Podría repetir la pregunta?

2. If you want to use the height and width of an applet window to determine how big
something should be drawn, what can you use? 2. Si desea utilizar la altura y el ancho de
una ventana del applet para determinar qué tan grande que debe de ser elaborado, lo
puede usar?

(a) A ruler and a friend who's good at math (A) Una regla y un amigo que es bueno para las
matemáticas
(b) and (B) getHeight () y getwidth ()
(c) and (C) el volumen (). Altura y tamaño (). Ancho

3. What personal failing did this book's author admit to during this hour? 3. ¿Qué personal
no hizo el autor de este libro admitir que durante esta hora?

(a) poor grooming (A) preparación pobres


(b) poor drawing ability (B) la capacidad de dibujo pobres
(c) codependency (C) co-dependencia

Answers Respuestas

1. b. 1. B. You can use the method to set the background color of an applet, and you can
use the method of the class to select the current color. Usted puede utilizar el
setBackground () para establecer el color de fondo de un applet, y se puede utilizar el
setColor () de la clase Graphics para seleccionar el color actual.

2. c. 2. C.

3. b. 3. B. JavaMan represents one of the high points of my illustrative career. Javaman


representa uno de los puntos culminantes de mi carrera ilustrativos.

Activities Actividades
To draw upon your vast storehouse of graphical skills, do the following activities: Para
aprovechar el vasto almacén de conocimientos gráficos, realizar las siguientes actividades:

 Create a method that can multiply every integer in an array by some kind of common
factor. Crear un método que puede multiplicar todo entero en una matriz por algún tipo
de factor común. You can use this method in the applet to change the points in a polygon
to make it bigger or smaller before it is created. Usted puede utilizar este método en el
applet de dibujo para cambiar los puntos de un polígono para hacerlo más grande o más
pequeña antes de que se crea.
 Add parameters to the applet to control the colors used on the background, body, and
hat. Agregar parámetros al applet Javaman para controlar los colores utilizados en el
fondo, el cuerpo, y el sombrero.

 18 horas
o Creación de animaciones
 Creación de un applet logotipo animado
 Listado de 18.1. El texto completo de Animate.java.
 Prevención de Animación parpadeo
 Carga y visualización de imágenes
 Almacenamiento de un grupo de imágenes relacionadas
 Envío de parámetros para el applet
 Listado de 18.2. El texto completo de Animate.html.
 Figura 18.1.
 Taller: Siga la pelota que rebota
 Listado de 18.3. El texto completo de Bounce.java.
 Listado de 18.4. El texto completo de Bounce.html.
 Figura 18.2.
 Dibujo de la imagen
 Llegando a su pantalla oculta
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 18 18 horas

Creating Animation Creación de animaciones

Like the final voyage of the SS Minnow, the trip through the visual side of Java
programming is a three-hour tour. Al igual que el último viaje del SS Minnow, el viaje por
el lado visual de programación Java es un tour de tres horas. At this point, you have learned
how to use text, fonts, color, lines, and polygons in your Java applets. En este punto, que
han aprendido a utilizar el texto, fuentes, colores, líneas y polígonos en los applets de Java.
Any adversity you have experienced should have been minor, at least in comparison to the
castaways of Gilligan's Island. Cualquier adversidad que ha experimentado debería haber
sido menor, al menos en comparación con los náufragos de la Isla de Gilligan. At this point
in the tour, passengers were asking the Skipper if hurricane-force winds were a scheduled
part of the itinerary. En este punto de la gira, los pasajeros estaban pidiendo el comandante
si los vientos con fuerza de huracán fueron parte del itinerario programado.

This third hour shows how to display image files in the and formats in your applets and
some tricks to use when presenting these images in an animation. Esta tercera hora se
muestra cómo mostrar archivos de imagen en el GIF. Y. Formatos JPG en los applets y
algunos trucos para utilizar en la presentación de estas imágenes en una animación. The
following topics will be covered: Los siguientes temas serán cubiertos:

 Using objects to hold image files El uso de objetos de imagen que contiene los archivos
de imagen
 Putting a series of images into an array Poner una serie de imágenes en una matriz
 Cycling through an image array to produce animation Ciclismo a través de una serie de
imágenes para producir animación
 Using the method to reduce flickering problems Utilizando el método update () para
reducir el parpadeo problemas
 Using the command Uso de la drawImage () comando
 Drawing to an off-screen workspace Llegando a su área de trabajo fuera de la pantalla
 Why double-buffering improves animation results ¿Por qué el doble buffer mejora los
resultados de la animación
 Establishing rules for the movement of an image Se establecen normas para el
movimiento de una imagen

Creating an Animated Logo Applet Creación de un applet logotipo animado


Computer animation at its most basic consists of drawing an image at a specific place,
moving the location of the image, and telling the computer to redraw the image at its new
location. La animación por computadora en su forma más básica consiste en dibujar una
imagen en un lugar específico, moviendo la ubicación de la imagen, y decirle al equipo
para volver a dibujar la imagen en su nueva ubicación. Many animations on Web pages are
a series of image files, usually or files, that are displayed in the same place in a certain
order. Muchas animaciones en las páginas Web son una serie de archivos de imagen, por lo
general. GIF o archivos. JPG, que se muestran en el mismo lugar en un orden
determinado. You can do this to simulate motion or to create some other effect. Usted
puede hacer esto para simular el movimiento o para crear algún otro efecto.

The first program that you will be writing today uses a series of image files for an animated
logo. El primer programa que se va a escribir hoy en día utiliza una serie de archivos de
imagen de un logotipo animado. Several details about the animation will be customizable
with parameters, so you can replace any images of your own for those provided for this
example. Algunos detalles acerca de la animación se puede personalizar con los
parámetros, por lo que puede sustituir alguna de las imágenes de su propia para las
previstas para este ejemplo. Create a new file in your word processor called . Crear un
nuevo archivo en el procesador de textos llamado Animate.java. Enter Listing 18.1 into
the file, and remember to save the file when you're done entering the text. Introduzca
Listado 18,1 en el archivo, y no olvide guardar el archivo cuando haya terminado de
introducir el texto.

Listing 18.1. Listado de 18.1. The full text of Animate.java. El texto completo de
Animate.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Animate extends java.applet.Applet
implements Runnable { 3: Animar clase pública se extiende
java.applet.Applet implementa Runnable {
4: 4:
5: Image[] picture = new Image[6]; 5: Imagen [imagen] =
new Image [6];
6: int totalPictures = 0; 6: totalPictures int = 0;
7: int current = 0; 7: int actual = 0;
8: Thread runner; 8: Tema corredor;
9: int pause = 500; 9: pausa int = 500;
10: 10:
11: public void init() { 11: public void init () {
12: for (int i = 0; i < 6; i++) { 12: for (int i = 0; i
<6; i + +) {
13: String imageText = null; 13: imageText String = null;
14: imageText = getParameter("image"+i); 14: imageText =
getParameter ("imagen" + i);
15: if (imageText != null) { 15:) si imageText (! = Null {
16: totalPictures++; 16: totalPictures + +;
17: picture[i] = getImage(getCodeBase(), imageText); 17:
Foto [i] = getImage (getCodeBase (), imageText);
18: } else 18:} else
19: break; 19: descanso;
20: } 20:}
21: String pauseText = null; 21: pauseText String = null;
22: pauseText = getParameter("pause"); 22: pauseText =
getParameter ("pause");
23: if (pauseText != null) { 23: if (pauseText = null!) {
24: pause = Integer.parseInt(pauseText); 24: pausa =
Integer.parseInt (pauseText);
25: } 25:}
26: } 26:}
27: 27:
28: public void paint(Graphics screen) { 28: public void
paint (pantalla de gráficos) {
29: screen.drawImage(picture[current],0,0,this); 29:
screen.drawImage (foto [actual], 0,0, este);
30: } 30:}
31: 31:
32: public void start() { 32: public void iniciar () {
33: if (runner == null) { 33: if (corredor == null) {
34: runner = new Thread(this); 34: corredor = new Thread
(this);
35: runner.start(); 35: runner.start ();
36: } 36:}
37: } 37:}
38: 38:
39: public void run() { 39: public void run () {
40: while (true) { 40: while (true) {
41: repaint(); 41: repaint ();
42: current++; 42: curso + +;
43: if (current >= totalPictures) 43: if (actual> =
totalPictures)
44: current = 0; 44: actual = 0;
45: try { Thread.sleep(pause); } 45: try {Thread.Sleep
(pausa);}
46: catch (InterruptedException e) { } 46: catch
(InterruptedException e) {}
47: } 47:}
48: } 48:}
49: 49:
50: public void stop() { 50: public void stop () {
51: if (runner != null) { 51: if (corredor = null!) {
52: runner.stop(); 52: runner.stop ();
53: runner = null; 53: corredor = null;
54: } 54:}
55: } 55:}
56: 56:
57: public void update(Graphics screen) { 57: public void
actualizar (pantalla de gráficos) {
58: paint(screen); 58: pintura (pantalla);
59: } 59:}
60:}

This program uses the same threaded applet structure that you used during Hour 14,
"Creating a Threaded Applet." Este programa utiliza la misma estructura applet de rosca
que se utilizó durante la hora 14, "Creación de un applet de rosca." Threads are often used
during animation programming because they give you the ability to control the timing of
the animation. Los hilos se utilizan a menudo durante la programación de animación, ya
que le dan la capacidad de controlar el momento de la animación. The method is an
effective way to determine how long each image should be displayed before the next image
is shown. El Thread.Sleep () es una manera eficaz de determinar la duración de cada
imagen debe aparecer antes de la siguiente imagen se muestra.

The applet retrieves images as parameters on a Web page. El applet Animar recupera
imágenes como parámetros en una página Web. The parameters should have names starting
at and ending at the last image of the animation, such as in this hour's example. Los
parámetros deben tener nombres a partir de "image0" y termina en la última imagen de la
animación, como "image3" en esta hora de ejemplo. The maximum number of images that
can be displayed by this applet is 6, but you could raise this number by making changes to
Lines 5 and 12. El número máximo de imágenes que se pueden mostrar por este
subprograma es de 6, pero que podría aumentar este número al hacer cambios en las líneas
5 y 12.

The integer variable determines how many different images will be displayed in an
animation. La variable entero totalPicture determina cuántas imágenes diferentes se
mostrarán en una animación. If fewer than 6 image files have been specified by parameters,
the applet will determine this during the method when equals after Line 14. Si menos de
6 archivos de imagen se han especificado por los parámetros, el applet Animar lo
determinará durante el método init () es igual a cuando imageText nula después de la
línea 14.

The speed of the animation is specified by a parameter. La velocidad de la animación se


especifica mediante un parámetro de pausa. Because all parameters from a Web page are
received as strings, the method is needed to convert the text into an integer. Debido a que
todos los parámetros de una página web se reciben en forma de cadenas, el
Integer.parseInt () es necesaria para convertir el texto en un número entero. The
variable keeps track of the number of milliseconds to pause after displaying each image in
an animation. La variable de pausa no pierde de vista el número de milisegundos para
hacer una pausa después de mostrar cada imagen en una animación.

Preventing Flickering Animation Prevención de Animación parpadeo

As with most threaded programs, the method contains the main part of the program. Como
con la mayoría de los programas de rosca, el método run () contiene la parte principal del
programa. A statement in Line 40 causes Lines 41-46 to loop as long as the program is not
stopped by someone leaving the Web page. Hace un tiempo (true) Declaración en la
línea 40 hace que las líneas 41 a 46 para recorrer, siempre y cuando el programa no se
detiene a alguien por salir de la página web.

The first thing that happens in the method is a statement. Lo primero que sucede en el
método run () es un repintado (); comunicado. This statement causes the method and
method to be handled, in that order, so that the screen can be updated. Esta declaración
hace que el método update () y pintura () para ser manejado, en ese orden, de modo que
la pantalla se puede actualizar. Use any time you know something has changed and the
display needs to be changed to bring it up to date. Utilice pintar () en cualquier momento
que sabe que algo ha cambiado y las necesidades de la pantalla para ser modificado para
que fuera hasta la fecha. In this case, every time the loop goes around once, a different
image should be shown. En este caso, cada vez que el bucle Animar da la vuelta una vez,
una imagen diferente se debe mostrar.

The method contains only one statement, . El método update () contiene sólo una
declaración, la pintura (pantalla);. The reason to use this method is that it overrides
the behavior that normally performs. La razón para usar este método es que anula el
comportamiento que update () normalmente realiza. If you did not override in the
program, it would clear the screen before calling on the method. Si no reemplazar update
() en el programa de Animación, sería borrar la pantalla antes de llamar en el método
paint (). This action causes flickering animation problems that have been mentioned in
previous hours. Esta acción hace que el parpadeo problemas con la animación que se han
mencionado en las horas anteriores.

Loading and Displaying Images Carga y visualización de imágenes

The method is simple in this applet: It draws an image on-screen with the method. El
método paint () es simple en este applet: Se dibuja una imagen en pantalla con el método
drawImage (). The method displays a current object at the (x, y) position specified. El
método drawImage () muestra un objeto actual de la imagen en la x, y) la posición
(especificado. The following is another example of a statement: El siguiente es otro
ejemplo de una drawImage () declaración:

screen.drawImage(turtlePicture, 10, 25, this);


screen.drawImage (turtlePicture, 10, 25, este);

This statement displays the object called at the (x, y) coordinates of (10, 25). Esta
declaración muestra el objeto de la imagen en el llamado turtlePicture (, x) las
coordenadas de (10, 25). The statement sent as the fourth argument to enables the program
to use a class called . La declaración de esta enviado como el cuarto argumento a
drawImage () permite que el programa para usar una clase llamada ImageObserver. This
class tracks when an image is being loaded and when it is finished. Esta clase de pistas
cuando una imagen se está cargando y cuando esté terminado. The class contains behavior
that works behind the scenes to take care of this process, so all you have to do is specify as
an argument to and some other methods related to image display. La clase Applet contiene
el comportamiento que trabaja entre bastidores para hacerse cargo de este proceso, por lo
que todo lo que tienes que hacer es especificar esto como un argumento para drawImage
() y otros métodos relacionados con la visualización de la imagen. The rest is taken care of
for you. El resto es atendido por usted.

The preceding example assumed that an object called had been created and loaded with a
valid image. El ejemplo anterior asume que un objeto de imagen llamado turtlePicture
había sido creado y cargado con una imagen válida. The way to load an image in an applet
is to use the method. La forma de cargar una imagen en un applet es utilizar el getImage
() método. This method takes two arguments, the Web address or directory that contains
the image file and the file name of the image. Este método toma dos argumentos, la
dirección Web o directorio que contiene el archivo de imagen y el nombre del archivo de la
imagen.

The first argument is taken care of with the method, which is part of the class. El primer
argumento es atendido con la getCodeBase (), el cual forma parte de la clase Applet.
This method returns the location of the applet itself, so if you put your images in the same
directory as the applet's class file, you can use . Este método devuelve la ubicación del
mismo subprograma, así que si usted pone las imágenes en el mismo directorio que el
archivo de clase del applet, puede utilizar getCodeBase (). The second argument should
be a file or file to load. El segundo argumento debe ser un archivo. Archivo GIF o
archivo. JPG a la carga. The following statement loads the object with a file called : La
siguiente carga de la declaración del objeto turtlePicture con un archivo llamado
Mertle.gif:

Image turtlePicture = getImage(getCodeBase(),


"Mertle.gif"); Imagen turtlePicture = getImage (getCodeBase
(), "Mertle.gif");

Storing a Group of Related Images Almacenamiento de un grupo de imágenes


relacionadas

In the applet, images are loaded into an array of objects called . En el subprograma de
Anime, las imágenes se cargan en una matriz de objetos de imagen llamado fotos. The
array is set up to handle six elements in Line 5 of the program, so you can have objects
ranging from to . El arsenal de imágenes está configurado para manejar seis elementos en
la Línea 5 del programa, lo que puede tener objetos de imágenes que van desde la imagen
[0] a la imagen [5]. The following statement in the applet's method displays the current
image: La siguiente declaración en el applet de la pintura () método muestra la imagen
actual:

screen.drawImage(picture[current],0,0,this);
screen.drawImage (foto [actual], 0,0, este);

The variable is used in the applet to keep track of which image to display in the method.
La variable actual se utiliza en el applet para hacer un seguimiento de qué imagen se
mostrará en el método paint (). It has an initial value of 0, so the first image to be
displayed is the one stored in . Tiene un valor inicial de 0, por lo que la primera imagen
que se muestra es la almacenada en la imagen [0]. After each call to the statement in
Line 41 of the method, the variable is incremented by one in Line 42. Después de cada
llamada al pintar () en la línea 41 del método run (), la variable de corriente se
incrementa en uno en la línea 42.

The variable is an integer that keeps track of how many images should be displayed. La
variable totalPictures es un entero que hace un seguimiento de cuántas imágenes se
debe mostrar. It is set when images are loaded from parameters off the Web page. Se
establece cuando las imágenes se cargan desde los parámetros de la página web. When
equals , it is set back to 0. Cuando la corriente es igual a totalPictures, se establece
de nuevo a 0. As a result, cycles through each image of the animation, and then begins
again at the first image. Como resultado, los ciclos de corriente a través de cada imagen
de la animación, y luego comienza de nuevo en la primera imagen.

Sending Parameters to the Applet Envío de parámetros para el applet


Becaus the applet relies on parameters to specify the image files it should display, you
need to create a Web page containing these file names before you can test the program.
Becaus el applet Anime se basa en parámetros para especificar los archivos de imagen que
debe mostrar, es necesario crear una página Web que contiene los nombres de estos
archivos antes de que pueda probar el programa. After saving and compiling the file, open
up a new file in your word processor and call it . Después de guardar y compilar el archivo
Animate.java, abre un nuevo archivo en el procesador de textos y lo llaman
Animate.html. Enter Listing 18.2 into that file, and save it when you're done. Introduzca
listado 18.2 en ese archivo, y guardar cuando haya terminado.

Listing 18.2. Listado de 18.2. The full text of Animate.html. El texto completo de
Animate.html.
1: <applet code="Animate.class" width=230 height=166> 2:
<param name="image0" value="sams0.gif"> 3: <param
name="image1" value="sams1.gif"> 4: <param name="image2"
value="sams2.gif"> 5: <param name="image3"
value="sams3.gif"> 6: <param name="pause" value="400"> 1:
code="Animate.class" <applet width=230 height=166> 2:
name="image0" <param value="sams0.gif"> 3: param name <=
"imagen1" value = "sams1.gif "> 4: name="image2" <param
value="sams2.gif"> 5: name="image3" <param
value="sams3.gif"> 6: param name <=" pausa "value =" 400 "
> 7: </> applet

This file specifies four image files: , , , and . Este archivo especifica cuatro archivos de
imagen: sams0.gif, sams1.gif sams2.gif, y sams3.gif. These files are listed as the
values for the parameters through . Estos archivos se muestran como los valores de los
parámetros a través de image0 image3. You can find the files used in this example on this
book's CD-ROM in the directory . Usted puede encontrar los archivos que se usan en este
ejemplo en el libro de este CD-ROM en el directorio Win95nt4/Book/Source/Hour18.
They also can be downloaded from the book's official Web site at the following address:
También se puede descargar desde su página web oficial del libro en la siguiente dirección:

http://www.prefect.com/java24

Look for the link that's available on the main page of the site. Busque las 18 horas de
vínculos de gráficos que está disponible en la página principal del sitio. You also can
specify any of your own or files if desired. También puede especificar cualquiera de su
cuenta. GIF o archivos. JPG si lo desea. Whichever files you choose should be placed
in the same directory as the and files. Cualquiera que sea el archivo que usted elija debe
ser colocado en el mismo directorio y los archivos Animate.html Animate.class. With
the parameter, you can specify how long the program should pause after each image is
displayed. Con la "pausa" parámetro, puede especificar el tiempo que el programa debería
hacer una pausa después de cada imagen se muestra.

You might be wondering why the files and the parameters are given names that start
numbering with 0 instead of 1. Usted podría preguntarse por qué los archivos y los
parámetros se dan nombres que empiezan con la numeración 0 en lugar de 1. This is done
because the first element of an array in a Java program is numbered 0. Esto se hace porque
el primer elemento de una matriz en un programa de Java es el número 0. Putting an called
into makes it easier to know where these images are being stored. Poner una llamada
sams0.gif image0 en imágenes [0] hace que sea más fácil saber donde estas imágenes
se almacenan.

Once the files have been put in the right place, you're ready to try out the applet. Una vez
que los archivos se han puesto en el lugar correcto, estás listo para probar el applet Animar.
Type the following command to use the to view the page: Escriba el siguiente comando
para utilizar el appletviewer para ver la página:
appletviewer Animate.html appletviewer Animate.html

Figure 18.1 shows the four images of the animation that was provided for this book. La
figura 18.1 muestra las cuatro imágenes de la animación que se proporcionó para este libro.

Figura 18.1. Four shots of the applet as it runs. Cuatro disparos del applet Animar ya que
se ejecuta.

Although this is a simple animation program, hundreds of applets on the Web use similar
functionality to present a series of image files as an animation. Aunque se trata de un
programa de animación simple, cientos de applets en el uso de la Web una funcionalidad
similar a presentar una serie de archivos de imagen como una animación. Presenting a
sequence of image files through Java is similar to the animated files that are becoming
more commonplace on Web pages. La presentación de una secuencia de archivos de
imagen a través de Java es similar a la animación. GIF que son cada vez más habitual en
las páginas Web. Although Java applets are often slower to load than these files, applets
can provide more control of the animation and allow for more complicated effects. Aunque
los applets de Java son a menudo más lento de cargar que estos archivos. GIF, los
applets pueden proporcionar un mayor control de la animación y dejar para más efectos
complicados.

Workshop: Follow the Bouncing Ball Taller: Siga la pelota que rebota
This hour's workshop is an animation that definitely couldn't be replicated with an animated
file or any other non-programming alternative. hora de taller Esta es una animación que
definitivamente no puede ser replicado con un archivo. archivo GIF o sin experiencia en
programación alternativa. You'll write a program that bounces a tennis ball around the
screen in lazy arcs, caroming off the sides of the applet window. Te voy a escribir un
programa que rebota una pelota de tenis por la pantalla en arcos perezoso, caroming de los
lados de la ventana del applet. Though a few laws of physics will be broken along the way,
you'll learn one way to move an image file around the screen. Aunque algunas leyes de la
física se romperá en el camino, usted aprenderá una forma de mover un archivo de imagen
por la pantalla.

Create a new file in your word processor called , and enter the text of Listing 18.3 into it.
Crear un nuevo archivo en el procesador de textos llamado Bounce.java, y escriba el texto
del listado 18.3 en el mismo. Save and compile the file when you're done. Guarde y
compile el archivo cuando haya terminado.
Listing 18.3. Listado de 18.3. The full text of Bounce.java. El texto completo de
Bounce.java.
1: import java.awt.*; 2: 3: public class Bounce extends
java.applet.Applet implements Runnable { 4: 5: Image ball;
6: float current = (float) 0; 7: Thread runner; 8: int
xPosition = 10; 9: int xMove = 1; 10: int yPosition = -1;
11: int ballHeight = 102; 12: int ballWidth = 111; 13: int
height; 14: Image workspace; 15: Graphics offscreen; 16:
17: public void init() { 18: workspace =
createImage(size().width, size().height); 19: offscreen =
workspace.getGraphics(); 20: setBackground(Color.white);
21: ball = getImage(getCodeBase(), "tennis.jpg"); 22: } 23:
24: public void paint(Graphics screen) { 25: height =
size().height - ballHeight; 26: if (yPosition == -1) 27:
yPosition = height; 28: offscreen.setColor(Color.white);
29: offscreen.fillRect(0,0,size().width,size().height); 30:
offscreen.drawImage(ball, 31: (int) xPosition, 32: (int)
yPosition, 33: this); 34: screen.drawImage(workspace, 0, 0,
this); 35: } 36: 37: public void start() { 38: if (runner
== null) { 39: runner = new Thread(this); 40:
runner.start(); 41: } 42: } 43: 44: public void run() { 45:
while (true) { 46: repaint(); 47: current += (float) 0.1;
48: if (current > 3) 49: current = (float) 0; 50: xPosition
+= xMove; 51: if (xPosition > (size().width - 111)) 52:
xMove *= -1; 53: if (xPosition < 1) 54: xMove *= -1; 55:
double bounce = Math.sin(current) * height; 56: yPosition =
(int) (height - bounce); 57: try { Thread.sleep(200); } 58:
catch (InterruptedException e) { } 59: } 60: } 61: 62:
public void stop() { 63: if (runner != null) { 64:
runner.stop(); 65: runner = null; 66: } 67: } 68: 69:
public void update(Graphics screen) { 70: paint(screen);
71: } 1: import java.awt .*; 2: 3: Bounce clase pública se
extiende java.applet.Applet implementa Runnable {4: 5: bola
de la imagen; 6: float actual = (float) 0; 7: corredor
Hilo; 8: int xPosition = 10; 9: xMove int = 1; 10:
yPosition int = -1; 11: int ballHeight = 102; 12: ballWidth
int = 111; 13: int altura; 14: espacio de trabajo de la
imagen; 15: fuera de la pantalla de gráficos; 16: 17:
public void init () {18: espacio de trabajo = createImage
(). ancho), size ().; altura de 19 (tamaño: fuera de la
pantalla = workspace.getGraphics (); 20: setBackground
(Color.white); 21: pelota = getImage (getCodeBase (),
"tennis.jpg"); 22:} 23:: 25 públicos: 24 void (pintura
gráfica de la pantalla) {title = size ():. altura -
ballHeight; 26 si (yPosition == -1) 27: yPosition altura =
28;: offscreen.setColor (Color.white); 29:
offscreen.fillRect (, size (). 0,0 de ancho, el tamaño ()
de altura.); 30: offscreen.drawImage (bola, de 31 años:
(int) xPosition, 32: (int) yPosition, de 33 años: esto);
34: screen.drawImage (espacio de trabajo, 0, 0,); 35:} 36::
38 públicos: 37 sin efecto start () {if (corredor == null)
{39: corredor = new Thread (this); 40: runner.start ();
41:} 42:} 43:: 45 públicos: 44 void Run () {while (true)
{46: pintar ( ); 47: actual + = (float) 0,1; 48: if
(actual> 3) 49: actual = (float) 0; 50: xPosition + =
xMove; 51: if (> xPosition (size () 111. ancho - )) 52:
xMove *= -1; 53: if (xPosition <1) 54: xMove *= -1; 55:
rebote doble = Matemáticas.Sin (actual) * altura; 56:
yPosition = (int) (altura - rebote); 57: try {Thread.Sleep
(200);} 58: catch (InterruptedException e) {} 59:} 60:}
61:: 63 públicos: 62 sin efecto stop () {if (corredor {! =
null) 64: runner.stop (); 65: corredor = null; 66:} 67:}
68: 69: public void actualizar (pantalla de gráficos) {70:
pintura (pantalla); 71:} 72:}

Before you dive into the discussion of what's taking place in this applet, you should see
what it does. Antes de zambullirse en la discusión de lo que está sucediendo en este applet,
debería ver lo que hace. Create a new file in your word processor called and enter Listing
18.4 into it. Crear un nuevo archivo en el procesador de textos llamado Bounce.html e
introduzca listado 18.4 en el mismo.

Listing 18.4. Listado de 18.4. The full text of Bounce.html. El texto completo de
Bounce.html.

1: <applet code="Bounce.class" width=500 height=300> 1:


<applet code="Bounce.class" width=500 height=300>
2: </ applet>

After saving this file, you need to get a copy of the file and put it in the same directory as
and . Después de guardar este archivo, usted necesita para obtener una copia del archivo
tennis.jpg y lo puso en el mismo directorio que Bounce.class y Bounce.html. This file
is available from the same place as the Sams.net logo image files: the directory of the CD-
ROM and the book's Web site at . Este archivo está disponible en el mismo lugar que los
archivos de imagen logotipo Sams.net: el directorio Win95nt4/Source/Hour18 / del CD-
ROM y sitio web del libro en el http://www.prefect.com/java24 . Once you have
copied into the right place, use or a Java-enabled Web browser to display this program.
Una vez que haya copiado tennis.jpg en el lugar correcto, appletviewer uso de Java o
un navegador habilitado para web para mostrar este programa. Figure 18.2 shows the
applet running on Netscape Navigator. Figura 18.2 muestra el applet de rebote se ejecuta
en Netscape Navigator.

Figura 18.2. The applet running on a Web page loaded by Netscape Navigator. El applet
de rebote que se ejecutan en una página Web cargada por Netscape Navigator.
This applet displays a file of a tennis ball bouncing back and forth. Este applet muestra un
archivo JPG. De una pelota de tenis rebotando. It hits a point at the bottom edge of the
applet window and rebounds upward close to the top edge of the window. Se llega a un
punto en el borde inferior de la ventana del applet y rebota hacia arriba cerca del borde
superior de la ventana. When the ball hits the right or left edge of the window, it bounces in
the opposite direction. Cuando la pelota golpea el borde derecho o izquierdo de la ventana,
rebota en la dirección opuesta. If you're using to try the applet out, resize the window by
making the right and left edges smaller. Si estás utilizando appletviewer probar el applet,
cambiar el tamaño de la ventana, haciendo los bordes derecho e izquierdo más pequeño.
The applet can keep track of your actions. El applet de rebote puede realizar un
seguimiento de tus acciones.

The applet is a relatively simple example of how to animate an image file using Java. El
applet de rebote es un ejemplo relativamente simple de cómo animar un archivo de
imagen usando Java. It consists of the following steps: Se compone de los siguientes pasos:

 Draw the ball at its current location. Dibujar el balón en su ubicación actual.
 Move the ball according to the rules that have been established for how the ball should
move. Mover la pelota de acuerdo a las normas que se han establecido para la forma en
que el balón debe moverse.
 Check whether the rules need to be changed based on the ball's new location. Comprobar
si las normas deben modificarse sobre la base de la nueva ubicación de la pelota.
 Repeat. Repita.

Drawing the Image Dibujo de la imagen

The applet has the same basic structure as the applet. El applet de rebote tiene la misma
estructura básica como el applet Animar. It's a threaded program with , , and methods to
control the operation of the thread. Es un programa de roscado con start (), stop (), y
ejecutar () para controlar el funcionamiento de la rosca. There are also and methods to
display information on-screen. También hay update () y pintura () para mostrar
información en pantalla.

The object called is loaded with the image in the method. El objeto de la imagen
llamada bola se carga con la imagen tennis.jpg en el método init (). Several variables
are used in the applet to keep track of the ball's location and its current rate of movement:
Diversas variables se utilizan en el applet para hacer un seguimiento de la ubicación de la
pelota y su ritmo actual de movimiento:

 : This variable is the x coordinate where the ball should be drawn. xPosition: Esta
variable es la coordenada x donde la bola debe ser elaborado. This coordinate begins as
10. Esta coordinación se inicia el 10.
 : This variable is the amount that the ball should move along the x axis after every screen
update. xMove: Esta variable es la cantidad que el balón debe moverse a lo largo del eje x
después de cada actualización de pantalla. This amount starts out as 1, but it will change
to -1 when the ball hits the right edge of the applet window. Esta cantidad comienza como
una, pero cambia a -1 cuando la pelota golpea el borde derecho de la ventana del applet.
It changes back and forth from -1 to 1 every time it hits an edge, and this change is
handled by Lines 51-54. Cambia de ida y vuelta -1-1 cada vez que toca un borde, y este
cambio está a cargo de las líneas 51-54.
 : This variable is the y coordinate where the ball should be drawn. yPosition: Esta
variable es la coordenada y donde la bola debe ser elaborado. This coordinate is initially
set to -1, which is a signal to the method that the needs to be set up before the ball can
be drawn for the first time. Esta coordinación se establece inicialmente en -1, lo que es
una señal al método paint () que el yPosition debe ser creada antes de la bola se
puede extraer por primera vez. The value varies from a point near the bottom of the
applet window to the top edge. El valor yPosition varía de un punto cerca de la parte
inferior de la ventana del applet en el borde superior.
 : This floating-point number starts at 0 and increases by 0.1 each time the ball is redrawn.
actual: Este número de punto flotante comienza en 0 y aumenta en 0.1 cada vez que el
balón se vuelve a dibujar. When it reaches 3, it is set back to 0 again. Cuando se llega a 3,
se establece de nuevo a 0. The variable is used with a mathematical sine function to
determine how high the ball bounces. La variable actual se utiliza con una función
sinusoidal matemática para determinar qué tan alto el balón rebota. Sine waves are a
good way to approximate the movements of a bouncing ball, and the method enables a
sine value to be used in conjunction with animation. Las ondas del seno son una buena
manera de aproximar los movimientos de una pelota que rebota, y la Matemáticas.Sin
() método permite a un valor del seno que se utiliza junto con la animación. The tennis
ball is traveling half a sine wave each time it goes from the ground to the top of the
window and back. La pelota de tenis viaja media onda sinusoidal cada vez que va desde el
suelo hasta la parte superior de la ventana y la espalda.

The movement rules that you establish for an animation applet will vary depending on what
you're trying to show. Las normas de circulación que se establece para un applet de
animación variará dependiendo de lo que estamos tratando de mostrar. The applet uses the
method to create the slow arcs traveled by the ball. El applet de rebote utiliza el
Matemáticas.Sin () para crear los arcos lenta recorrida por la pelota.

Drawing to a Hidden Screen Llegando a su pantalla oculta

The method uses a technique called double-buffering to make the animation display more
smoothly. El método paint () utiliza una técnica llamada doble buffer para que la pantalla
de animación más fluida. Double-buffering is drawing everything off-screen to a storage
place that's the same size as the program's display area and copying it to the display only
when all drawing is done. Doble-buffering es dibujando todo fuera de la pantalla a un lugar
de almacenamiento que es del mismo tamaño que la zona de visualización del programa y
copiarlo en la pantalla sólo cuando todo el dibujo está hecho. The advantage to using
double-buffering is that it reduces flickering and other things that might be seen while the
method is drawing things on-screen. La ventaja de utilizar el doble buffer es que reduce el
parpadeo y otras cosas que podría ser visto mientras que el método paint () es dibujar cosas
en pantalla.
Because all drawing in an applet is done to a object that represents the applet window, you
have to create an additional object for the off-screen area. Debido a que todos los dibujos
en un applet se hace a un objeto gráfico que representa la ventana del applet, usted tiene
que crear un objeto Graphics adicionales para el área frente a la pantalla. You also must
create an object to hold everything that's being drawn to the hidden area. También debe
crear un objeto de imagen para celebrar todo lo que está siendo elaborado para el área
oculta. Lines 14-15 create an object called and a object called . Líneas 14-15 crear un
objeto de imagen llamado espacio de trabajo y un objeto Graphics llamada fuera de
la pantalla. These objects are set up in the method. Estos objetos se crean en el método
init (). Line 18 uses the method to set up as an empty image the size and width of the
applet window. La línea 18 utiliza el createImage () para crear espacio de trabajo
como una imagen vacía del tamaño y la anchura de la ventana del applet. Line 19 associates
the object with the image, using the method of the class. La línea 19 se asocia el objeto
fuera de la pantalla con la imagen de espacio de trabajo, utilizando el
getGraphics () de la clase Image.

The key to double-buffering is to draw everything to the off-screen area in the method. La
clave para el doble buffer es dibujar todo a la zona frente a la pantalla en el método paint
(). To do this, use the object for all display methods instead of the object. Para ello,
utilice el objeto fuera de la pantalla para todos los métodos de visualización en lugar
del objeto de la pantalla. Each of these methods will update the image with the things
that are being displayed. Cada uno de estos métodos se actualizará la imagen de espacio
de trabajo con las cosas que se están exhibiendo.

When all drawing has been done and you know the off-screen area looks the way the screen
should look, draw that entire off-screen image to the applet window by using a statement
such as the one on Line 34: Cuando todo el dibujo se ha hecho y que conoce el área fuera
de la pantalla se ve la forma en la pantalla debe mirar, dibujar la imagen entera fuera de la
pantalla a la ventana del applet mediante una instrucción como la de la línea 34:

screen.drawImage(workspace, 0, 0, this); screen.drawImage


(espacio de trabajo, 0, 0,);

Because is an object with the same dimensions as the applet window, you can use (0,0) as
its coordinates, and it will fill the display area. Debido a que área de trabajo es un
objeto de imagen con las mismas dimensiones que la ventana del applet, puede utilizar
(0,0) como sus coordenadas, y llenará el área de visualización.

When you are drawing only one image to the screen during each update, as you did in the
applet, there's no reason to use double-buffering. Cuando se le dibujo una sola imagen a la
pantalla en cada actualización, como lo hizo en el subprograma de Animación, no hay
razón para utilizar doble buffer. However, if the animation involves more than one thing to
draw, you will get better results by drawing to an off-screen area and then copying the
whole thing to the screen at one time. Sin embargo, si la animación consiste en más de una
cosa a dibujar, obtendrá mejores resultados llegando a un área fuera de la pantalla y luego
copiar todo el asunto a la pantalla a la vez.

The applet requires an off-screen area because it clears the screen right before drawing the
tennis ball during each update. El applet de rebote requiere un área frente a la pantalla, ya
que elimina el derecho de la pantalla antes de sacar la pelota de tenis en cada actualización.
The screen is cleared by drawing a filled white rectangle the size of the applet window. La
pantalla se borra por dibujar un rectángulo relleno blanco del tamaño de la ventana del
applet. This rectangle is needed to remove the image of the ball in its last position before
the new position is drawn. Este rectángulo es necesaria para eliminar la imagen de la bola
en su posición anterior a la nueva posición se dibuja.

Summary Resumen
Using the classes that come with the Java language, you can produce some interesting
animated graphics and games. Uso de las clases que vienen con el lenguaje Java, puede
producir algunos gráficos interesantes animados y juegos. A lot of graphics functionality is
built-in and can be used in short programs like those written during this hour. Una gran
cantidad de funcionalidad gráfica incorporada y puede ser utilizado en programas cortos
como los que escribió durante esta hora.

Because Java is an interpreted language, its programs run at speeds slower than compiled
languages such as C can achieve. Debido a que Java es un lenguaje interpretado, sus
programas se ejecutan a una velocidad más lenta que lenguajes compilados como C se
puede alcanzar. This makes it more of a challenge to produce animated graphics at
acceptable speeds. Esto hace más de un desafío de producir gráficos animados a una
velocidad aceptable. However, many applets on display on World Wide Web pages
showcase Java's graphics capabilities. Sin embargo, muchos applets en la exhibición en las
páginas World Wide Web mostrar las capacidades gráficas de Java.

What you have learned about graphics and animation should keep you from running adrift
if you venture into uncharted waters like Java game programming and other visually
inventive projects. Lo que hemos aprendido acerca de los gráficos y la animación que le
impiden correr a la deriva si se aventuran en aguas desconocidas, como la programación de
juegos Java y otros proyectos de inventiva visual. Java animation programming is quite a
challenge, but it could be worse. de programación Java animación es todo un reto, pero
podría ser peor. The Professor on Gilligan's Island had nothing to work with but coconuts
and palm fronds, and he produced a washing machine. El profesor en la Isla de Gilligan no
tenía nada para trabajar con mas coco y hojas de palmera, y produjo una lavadora.
Q&A Q & A
Q Does a threaded animation program have to use Thread.sleep() to pause, or can you
omit it to produce the fastest possible animation? Q ¿Un programa de animación rosca
tiene que utilizar Thread.Sleep () para hacer una pausa, o se puede omitir para producir
la animación más rápido posible?

A You have to put some kind of pause in place in an animation program, or the program
will crash or behave erratically. Un Tienes que poner algún tipo de pausa en lugar de un
programa de animación, o el programa se bloqueará o se comportan de forma errática.
Your applet is running as part of a bigger program, the Web browser or , and that
program won't be able to keep up with constant requests without the pause. El applet se
ejecuta como parte de un programa más grande, el navegador Web o appletviewer, y
que el programa no será capaz de mantenerse al día con pintar constante () las
solicitudes sin pausa. Part of the process of animation design in Java is finding the right
display speed that all applet-running environments can handle. Parte del proceso de
diseño de animación en Java es encontrar la velocidad de pantalla de la derecha que todos
los entornos que utilizan applet puede manejar.

Q What happens if you draw something such as an image to coordinates that aren't
within the applet window? Q ¿Qué pasa si dibuja algo así como una imagen a las
coordenadas que no están dentro de la ventana del applet?

A Methods that draw something to a coordinate will continue to draw it even if none of it
is visible within the area shown by the applet window. Un métodos que dibujar algo a una
cota seguirá dibujarlo, aunque nada de esto es visible en el área indicada por la ventana
del applet. To see this in action, reduce the height of the applet as it runs in the tool. Para
ver esto en acción, reducir la altura del applet de rebote ya que se ejecuta en la
herramienta appletviewer. The tennis ball will drop below the window and bounce
back upwards into the window. La pelota de tenis se reducirá por debajo de la ventana y
rebotan hacia arriba en la ventana.

Quiz Quiz
Animate yourself as much as you can muster and answer the following questions to test
your skills. Animar a ti mismo todo lo que pueda reunir y responder las siguientes
preguntas para poner a prueba sus habilidades.

Questions Preguntas

1. Where is the (0,0) coordinate on an applet window? 1. ¿Dónde está el (0,0) coordinar
en una ventana del applet?

(a) In the off-screen double-buffering area (A) En el área de búfer de pantalla doble de
(b) The exact center of the window (B) El centro exacto de la ventana
(c) The upper-left corner of the applet window (C)-La esquina superior izquierda de la
ventana del applet
2. What thing did you not learn during this hour? 2. ¿Qué cosa no se aprende en esta
hora?

(a) How to use and objects to create an off-screen workspace (A) ¿Cómo utilizar
gráficos y objetos en la imagen para crear un espacio de trabajo fuera de la pantalla
(b) How to override the method to reduce animation flickering (B) Cómo reemplazar el
método update () para reducir el parpadeo de animación
(c) Why Thurston Howell III and his wife Lovey packed so much clothing for a three-hour
tour (C) ¿Por qué Thurston Howell III y su esposa Lovey lleno de mucha ropa para una gira
de tres horas

3. In a threaded animation applet, where should you handle most of the movement of an
image? 3. En un applet de animación de rosca, que debe manejar la mayoría del
movimiento de una imagen?

(a) The method (A) El método run ()


(b) The method (B) El método init ()
(c) The method (C) El método update ()

Answers Respuestas

1. c. 1. C. The x value increases as you head to the right, and the y value increases as you
head downward. El valor de x aumenta a medida que la cabeza hacia la derecha, y el
incremento del valor y del mismo modo la cabeza hacia abajo.

2. c. 2. C. If the tiny ship had not been so weighted down with smoking jackets and
evening gowns, the Skipper and Gilligan might have been able to outrun the storm. Si el
buque pequeño no había sido tan cargados con esmoquin y trajes de noche, el
comandante y Gilligan podría haber sido capaz de escapar de la tormenta.

3. a. 3. A. Some movement might be handled by statements in the method, but most of it


will take place in or a method called from within . Algunos movimientos pueden ser
manipulados por las declaraciones en el método paint (), pero la mayor parte se llevará
a cabo en run () o un método llamado desde dentro de run ().

Activities Actividades
Before you're stranded and the subject of graphics is abandoned, picture yourself doing the
following activities: Antes de que se quedara varado y el tema de los gráficos se abandona,
una imagen que estás haciendo las siguientes actividades:

 Change the applet so that the ball loses 10 percent of its bouncing strength each time it
hits the ground. Cambiar el applet para que rebote la pelota pierde el 10 por ciento de su
fuerza rebotando cada vez que toca el suelo. You can do this by changing the variable at a
certain time within the method. Puede hacer esto cambiando la variable de la altura
en un momento determinado en el método run ().
 Create an animation applet where the object or objects you move wrap around the edges
of the applet window, coming back through the opposite side. Crear un applet de
animación donde el objeto o los objetos que se mueven envoltura alrededor de los bordes
de la ventana del applet, volviendo por el lado opuesto

 19 horas
o La construcción de una sencilla interfaz de usuario
 El kit de herramientas de ventana de Resumen
 Utilización de componentes
 Figura 19.1.
 Las etiquetas y campos de texto
 Figura 19.2.
 Casillas de verificación
 Figura 19.3.
 Listas de opciones
 Figura 19.4.
 Áreas de texto
 Figura 19.5.
 Uso de Controladores de Distribución
 Listado de 19.1. El texto completo de Crisis.java.
 Listado de 19.2. El texto completo de Crisis.html.
 Figura 19.6.
 El Administrador de GridLayout
 Figura 19.7.
 El Administrador de BorderLayout
 Figura 19.8.
 Taller: Diseñar un Applet
 Figura 19.9.
 Listado de 19.3. El texto completo de LottoGUI.java.
 Listado de 19.4. El texto completo de LottoGUI.html.
 Figura 19.10.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 19 19 horas

Building a Simple User Interface La construcción de una


sencilla interfaz de usuario

Because of the popularity of Microsoft Windows and Apple Macintosh systems, computer
users have come to expect certain things from their software. Debido a la popularidad de
los sistemas Microsoft Windows y Apple Macintosh, los usuarios de computadoras han
llegado a esperar ciertas cosas de su software. It should use a graphical user interface, be
controllable with a mouse, and work like a lot of their other programs do. Debe utilizar una
interfaz gráfica de usuario, se puede controlar con un ratón, y hacer un trabajo como
muchos de sus otros programas. These expectations are a far cry from the heyday of MS-
DOS and other command-line systems, when the user interface varied greatly with each
program you used and point-and-click was something photographers did. Estas expectativas
están muy lejos de los buenos tiempos de MS-DOS y otros sistemas de línea de comandos,
cuando la interfaz de usuario muy variable con cada programa que usted utiliza y el punto y
hacer clic se fotógrafos algo lo hizo.

Today's programs that use a graphical user interface and mouse control are called
windowing software. Los programas de hoy que utilizan una interfaz gráfica de usuario y el
control del ratón se denominan ventanas de software. Although you've been using a
command-line interface to write Java programs, you can create windowing programs using
a group of classes called the Abstract Windowing Toolkit (AWT). Aunque usted ha estado
usando una interfaz de línea de comandos para escribir programas Java, puede crear
ventanas de los programas que utilizan un grupo de clases llamado Abstract Windowing
Toolkit (AWT). You'll learn how to create a windowing program during this hour. Usted
aprenderá a crear un programa de ventanas durante esta hora.

The following topics will be covered: Los siguientes temas serán cubiertos:

 Using user interface components such as buttons Utilización de componentes de interfaz


de usuario tales como botones
 Putting components on-screen Poner los componentes de la pantalla
 Putting components onto other components Poner componentes en otros componentes
 Using layout managers to organize an interface Uso de los administradores de diseño para
organizar una interfaz
 Organizing components into a grid La organización de los componentes en una rejilla
 Using labels, text fields, and other components El uso de etiquetas, campos de texto, y
otros componentes
 Testing an interface Pruebas de una interfaz

The Abstract Windowing Toolkit El kit de herramientas de ventana de Resumen


Because Java is a cross-platform language that enables you to write programs for many
different operating systems, its windowing software must be flexible. Debido a que Java es
un lenguaje multi-plataforma que le permite escribir programas para muchos sistemas
operativos diferentes, su software de ventanas deben ser flexibles. Instead of catering only
to the Microsoft Windows-style of windowing or the Apple Macintosh version, it must
handle both, along with other platforms. En lugar de atender sólo a la de Microsoft
Windows-estilo de ventanas o la versión de Apple Macintosh, debe manejar ambos, junto
con otras plataformas. The Abstract Windowing Toolkit gets its name because it is a set of
classes intended to work with any platform that runs Java programs. El resumen de
ventanas Toolkit recibe su nombre debido a que es un conjunto de clases destinadas a
funcionar con cualquier plataforma que lleva a cabo programas de Java. This approach was
needed so that programmers could offer their applets on the World Wide Web, which is
used by people on dozens of different types of computers, operating systems, and Web
browsers. Este enfoque era necesario para que los programadores pueden ofrecer a sus
applets en la World Wide Web, que es utilizado por las personas en docenas de diferentes
tipos de computadoras, sistemas operativos y navegadores Web.

The Toolkit classes include everything you need to write programs that use a GUI
(pronounced gooey). Las clases de kit de herramientas incluye todo lo necesario para
escribir programas que utilizan una interfaz gráfica de usuario (pegajosa pronunciado). If
you think a GUI is the brother of Huey, Louie, and Dewey, know that the acronym stands
for graphical user interface. Si usted piensa que una interfaz gráfica de usuario es el
hermano de Huey, Louie y Dewey, sabemos que el acrónimo de la interfaz gráfica de
usuario. With Java's windowing toolkit, you can create a GUI that includes all of the
following: Con el kit de herramientas de ventanas de Java, puede crear una interfaz gráfica
de usuario que incluye todas las características siguientes:

 Buttons, check boxes, labels, and other simple components Botones, casillas de
verificación, etiquetas y otros componentes simples
 Text fields and more complex components Los campos de texto y componentes más
complejos
 Dialog boxes and other windows Cuadros de diálogo y ventanas
 Pull-down menus Los menús desplegables
 Applets that offer these interface components Applets que ofrecen estos componentes de
la interfaz

The Toolkit also includes classes that you have been using up to this point to offer fonts,
color, and graphics in your programs. El kit de herramientas también incluye las clases que
usted ha estado utilizando hasta ahora para ofrecer fuentes, colores, y gráficos en sus
programas. Another element of the Toolkit you'll be learning about during Hour 20,
"Responding to User Events," is how the Toolkit can be used to receive mouse clicks and
other user input. Otro de los elementos del kit de herramientas usted aprenderá sobre
durante horas 20, "Responder a eventos de usuario," es como el kit de herramientas se
pueden utilizar para recibir clics del ratón y la entrada de otro usuario.

Using Components Utilización de componentes


To use components such as buttons and text fields in a Java program, you create a
component object and use the method to add it to an existing component. Para utilizar los
componentes, como botones y campos de texto en un programa Java, se crea un objeto
componente y utilizar el método add () para añadirlo a un componente existente. For
example, a component is a clickable button with a label that describes what clicking the
button will do. Por ejemplo, un componente Button es un botón que se pulse con una
etiqueta que describe lo que hacer clic en el botón hará. One of the most basic ways to use a
component such as a button is to add it to an applet. Una de las maneras más básicas para
usar un componente como un botón para agregarlo a un applet. You can add a button to an
applet with two statements, one to create the object and one to add it to the applet itself.
Puede agregar un botón a un applet con dos estados, uno para crear el objeto Button y uno
para añadirlo a la propia applet. The following short Java applet will do this: El siguiente
applet de Java breve hará lo siguiente:

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

public class ShowButton extends java.applet.Applet {


public class ShowButton extiende java.applet.Applet {
Button panicButton = new Button("Panic"); Botón
panicButton = new Button ("Pánico");

public void init() { public void init () {


add(panicButton); añadir (panicButton);
} }

} }

The object is created as an object variable so that you can use it in all methods of the applet
program. El objeto panicButton se crea como una variable de objeto, para que pueda
utilizarlo en todos los métodos del programa del applet. The argument used with specifies
the label of the button. El argumento utilizado con el nuevo botón de especifica la
etiqueta del botón. The statement adds the component to the applet. El complemento
(panicButton); sentencia añade el componente Button al applet ShowButton. Figure
19.1 shows what the output of this program would be. Figura 19.1 muestra lo que la salida
de este programa sería.

Figura 19.1. A component. Un componente Button.

Each of the user components available as part of the Abstract Windowing Toolkit can be
added in this manner. Cada uno de los componentes disponibles para el usuario como parte
de la Guía Resumen de ventanas se puede agregar de esta manera.

Because so many different things must be introduced during this hour, the full source code
used to create each figure is not listed here. Porque las cosas tan diferentes se deben
introducir durante esta hora, el código fuente completo para crear cada figura no figuran en
esta lista. You can find full versions of each program on the book's CD-ROM in the
directory or on this book's Web site at . Usted puede encontrar las versiones completas de
cada programa en el libro de los CD-ROM en el directorio
Win95nt4/Book/Source/Hour19 o en sitio web del libro en este
http://www.prefect.com/java24 . Choose the link from the front page. Elija 19 horas
de programas de enlace desde la página principal.

Labels and Text Fields Las etiquetas y campos de texto

A component displays a string that cannot be modified by the user. Un componente Label
muestra una cadena que no puede ser modificado por el usuario. These components get
their name from their usefulness as a way to label other components in an interface. Estos
componentes deben su nombre a su utilidad como una forma de etiqueta de otros
componentes en una interfaz. They often are used to identify text fields. A menudo se
utilizan para identificar los campos de texto. A component is an area where a user can
enter a single line of text. Un componente TextField es un área donde un usuario puede
escribir una sola línea de texto. You can set up the width of the box when you create the
text field. Puede configurar el ancho de la caja cuando se crea el campo de texto.

The following statements create a component and object and add them to an applet: Las
declaraciones siguientes se crea un componente Label y un objeto TextField y añadirlos a
un applet:

Label eMailLabel = new Label("E-mail address: ",


Label.RIGHT); Etiqueta eMailLabel = new Label ("E-mail:"
Label.RIGHT);
TextField eMailAddress = new TextField(25); EmailAddress
TextField = TextField nuevos (25);
add(eMailLabel); añadir (eMailLabel);
add(eMailAddress); añadir (EmailAddress);

Figure 19.2 shows this label and text field side-by-side. Figura 19.2 muestra esta etiqueta y
campo de texto de lado a lado-. Both of the statements in this example use an argument to
configure how the component should look. Tanto de las declaraciones en este ejemplo
utiliza un argumento para configurar el modo en el componente debe mirar. The label is set
up with the text and a argument. La etiqueta eMailLabel está configurado con el E-mail
de texto, y un argumento Label.RIGHT. This last value indicates that the label should
appear flush right. aligns the label text flush left, and centers it. Este último valor indica
que la etiqueta debe aparecer alineados a la derecha. Label.LEFT alinea el texto de la
etiqueta alineada a la izquierda, y los centros de Label.CENTER ella. The argument used
with indicates that the text field should be approximately 25 characters wide. El argumento
utilizado con TextField indica que el campo de texto debe ser de aproximadamente 25
caracteres de ancho. You also can specify default text that will appear in the text field with
a statement such as the following: También puede especificar el texto por defecto que
aparecerá en el campo de texto con una declaración como la siguiente:

TextField state = newTextField("TX", 2); Estado TextField


= newTextField ("TX", 2);

This statement would create a object that is two characters wide and has the text in the
field. Esta declaración se crea un objeto TextField que es de dos caracteres de ancho y
tiene la TX texto en el campo.

Figura 19.2. and components. Label y TextField componentes.

Check Boxes Casillas de verificación

A component is a box next to a line of text that can be checked or unchecked by the user.
Un componente Casilla de verificación es un cuadro al lado de una línea de texto que
puede ser activada o desactivada por el usuario. The following statements create a object
and add it to an applet: Las siguientes sentencias crean un objeto de casilla de
verificación y agregarlo a un applet:

Checkbox jumboSize = new Checkbox("Jumbo Size"); Casilla


de verificación jumboSize = new Casilla ("tamaño jumbo");
add(jumboSize); añadir (jumboSize);

The argument to the constructor method indicates the text to be displayed alongside the
box. El argumento de la) constructor de método (casilla de verificación indica el
texto que se mostrará junto a la caja. If you wanted the box to be checked, you could use
the following statement instead: Si desea que el cuadro que deben controlar, se puede
utilizar la siguiente declaración en su lugar:

Checkbox jumboSize = new Checkbox("Jumbo Size", true);


Casilla de verificación jumboSize = new Casilla ("Jumbo
Size", true);

A can be presented singly or as part of a group. Una casilla de verificación se


pueden presentar por separado o como parte de un grupo. In a group of check boxes, only
one can be checked at a time. En un grupo de casillas de verificación, sólo uno se puede
comprobar a la vez. To make a object part of a group, you have to create a object. Para
realizar una parte de objetos de casilla de verificación de un grupo, tienes que crear
un objeto CheckboxGroup. Consider the following: Considere lo siguiente:

CheckboxGroup meals = new CheckboxGroup(); CheckboxGroup


comidas = new CheckboxGroup ();
Checkbox frogLegs = new Checkbox("Frog Leg Grande", true,
meals); Casilla de verificación frogLegs = new Casilla
("rana pierna Grande", las comidas true);
Checkbox fishTacos = new Checkbox("Fish Taco Platter",
false, meals); fishTacos Checkbox = new Casilla ("Fish Taco
Plato", comidas false);
Checkbox emuNuggets = new Checkbox("Emu Nuggets", false,
meals); emuNuggets Checkbox = new Casilla ("Emu Nuggets",
comidas false);
add(frogLegs); añadir (frogLegs);
add(fishTacos); añadir (fishTacos);
add(emuNuggets); añadir (emuNuggets);

This code creates three check boxes that are all grouped under the object called . Este
código crea tres casillas de verificación que se han agrupado bajo el CheckboxGroup objeto
llamado comidas. The box is checked initially, but if the user checked one of the other
meal boxes, the check next to would disappear automatically. La Rana Pata Grande
cuadro se comprueba al principio, pero si el usuario comprueba una de las cajas de comida,
la verificación situada junto a la rana pierna Grande desaparecería automáticamente.
Figure 19.3 shows the different check boxes from this section. Figura 19.3 muestra las
casillas de verificación diferente de esta sección.

Figura 19.3. components. Casilla de verificación de componentes.

Choice Lists Listas de opciones

A component is a pop-up list of choices from which a single choice can be made. Un
componente Choice es una lista emergente de opciones de las que se puede elegir un solo
hecho. It serves a similar purpose to a group of check boxes, except that only one of the
selections is visible unless the pop-up list is being displayed. Se sirve un propósito similar a
un grupo de casillas de verificación, con la excepción de que sólo una de las selecciones es
visible a menos que la lista de pop-up se está mostrando.

To create a object, you have to add each of the choices after creating the object, as in the
following example: Para crear un objeto de elección, tiene que agregar cada una de las
opciones después de crear el objeto, como en el ejemplo siguiente:
Choice profession = new Choice(); Elección de profesión =
new Choice ();
profession.add("Butcher"); profession.add ("Carnicero");
profession.add("Baker"); profession.add ("Baker");
profession.add("Candlestick maker"); profession.add
("fabricante de vela");
profession.add("Fletcher"); profession.add ("Fletcher");
profession.add("Fighter"); profession.add ("Fighter");
profession.add("Technical writer"); profession.add
("escritor técnico");
add(profession); añadir (profesión);

This example creates a single component that provides six choices for the user to select
from. En este ejemplo se crea un componente de opción única que ofrece seis opciones
para el usuario para elegir. When one is selected, it appears in the display of the
component. Cuando se selecciona, aparece en la pantalla del componente. Figure 19.4
shows this example while the pop-up list of choices is being displayed. La figura 19.4
muestra este ejemplo, mientras que la lista emergente de opciones se visualiza.

Figura 19.4. A component. Un componente Choice.

Text Areas Áreas de texto

A component is a text field that enables the user to enter more than one line of text. Un
componente TextArea es un campo de texto que permite al usuario introducir más de una
línea de texto. You can specify the width and height of the component. Usted puede
especificar la anchura y la altura del componente. For example, the following statements
create a component with an approximate width of 50 characters and a height of 10 lines
and then add the component to an applet: Por ejemplo, las siguientes afirmaciones crear un
componente TextArea con un ancho aproximado de 50 caracteres y una altura de 10 líneas
y luego agregar el componente a un applet:

TextArea comments = new TextArea("", 10, 50); comentarios


TextArea = new TextArea ("", 10, 50);
add(comments); añadir (comentarios);

You can specify a string in the constructor method to be displayed in the text area. Puede
especificar una cadena en el) constructor de método (TextArea que se mostrará en el área
de texto. You can use the newline character to send text to the next line, as in the
following: Usted puede utilizar el carácter de nueva línea \ n para enviar mensajes de texto
a la línea siguiente, como en el siguiente:

TextArea desire = new TextArea("I should have been a


pair\nof ragged claws.", 10, 25); TextArea deseo = new
TextArea ("Debería haber sido un par \ n de las garras
desiguales.", 10, 25);

If the user enters text that extends beyond the component's area, scrollbars will become
active on the sides of the component, as shown in Figure 19.5. Si el usuario escribe el texto
que se extiende más allá del área del componente, barras de desplazamiento se activa en los
lados del componente, como se muestra en la Figura 19.5. This is 10 lines tall and
approximately 50 characters wide. Este TextArea es de 10 líneas de alto y
aproximadamente 50 caracteres de ancho.

Figura 19.5. A component. Un componente TextArea.

Using Layout Managers Uso de Controladores de Distribución


The last of the components you'll learn to create during this hour are objects. objects are
part of of a broader category of objects known as containers. objects don't display
anything. El último de los componentes que va a aprender a crear durante esta hora son los
objetos del panel. Panel de objetos son parte de una categoría más amplia de objetos
conocidos como contenedores. Panel de objetos no muestra nada. Instead, they are used to
contain other components. En su lugar, se utilizan para contener otros componentes. The
purpose of objects is to subdivide a display area into different groups of components. El
propósito de los objetos del panel es para subdividir un área de visualización en
diferentes grupos de componentes. When the display is divided into sections, you can use
different rules for how each section is displayed on-screen. Cuando la pantalla está dividida
en secciones, puede utilizar diferentes reglas para la forma en que cada sección se muestra
en pantalla.

You can create a object and add it to an applet with the following statements: Usted puede
crear un objeto Panel y agregarlo a un applet con las siguientes afirmaciones:

Panel topRow = new Panel(); TopRow Grupo = new Panel ();


add(topRow); añadir (TopRow);

When you place components onto an applet or some other kind of container, the way they
are organized on-screen is highly variable. Cuando se coloca los componentes en un applet
o algún otro tipo de contenedor, la forma en que se organizan en la pantalla es muy
variable. The layout of buttons, text fields, and other components can be affected by the
following things: La disposición de botones, campos de texto, y otros componentes pueden
ser afectados por las siguientes cosas:

 The size of the applet window El tamaño de la ventana del applet


 The size of other components and containers El tamaño de otros componentes y
contenedores
 The layout manager that is being used El controlador de distribución que se utiliza

There are several layout managers that you can use to affect how components are shown.
Hay diversos gestores de diseño que puede usar para afectar a cómo los componentes se
muestran. The default manager is the class, which is what has been used for all of the
examples shown up to this point. El administrador por defecto es la clase FlowLayout, que
es lo que se ha utilizado para todos los ejemplos mostrados hasta el momento. Under ,
components are dropped onto an area in the same way words are organized on a printed
page--from left to right, and on to the next line when there's no more space. Bajo
FlowLayout, los componentes se dejó caer en una zona del mismo modo que las palabras
se organizan en una página impresa - de izquierda a derecha, y luego a la siguiente línea
cuando no hay más espacio.

To set up an applet to work under , create a object and then use it as an argument to the
method: Para crear un applet para trabajar bajo FlowLayout, crear un objeto FlowLayout y
luego utilizarlo como un argumento a la setLayout () método:

FlowLayout topLayout = new FlowLayout(); topLayout


FlowLayout FlowLayout = new ();
setLayout(topLayout); setLayout (topLayout);

You also can set up a layout manager to work within a specific container, such as a object.
También puede configurar un controlador de disposición para trabajar dentro de un
contenedor específico, tales como un objeto del panel. You can do this by using the
method of that container object. Usted puede hacer esto utilizando la setLayout () de ese
objeto contenedor. The following statements create a object called and set it up to use as
its layout manager: Las siguientes sentencias crean un objeto llamado Grupo inputArea y
configurarlo para usar FlowLayout como su controlador de distribución:

Panel inputArea = new Panel(); inputArea Grupo = new Panel


();
FlowLayout inputLayout = new FlowLayout(); inputLayout
FlowLayout FlowLayout = new ();
inputArea.setLayout(inputLayout); inputArea.setLayout
(inputLayout);
To give you an idea of how the different layout managers work, a simple applet will be
shown under each of the classes. Para que os hagáis una idea de cómo el diseño de trabajo
diferentes gerentes, un sencillo aplique será mostrado en cada una de las clases. The applet
has a graphical user interface with five buttons. El applet de la crisis tiene una interfaz
gráfica de usuario con cinco botones. Load your word processor and open up a new file
called . Cargue su procesador de textos y abrir un nuevo archivo llamado Crisis.java.
Enter Listing 19.1, and save the file when you're done. Introduzca Listado 19.1, y guarde el
archivo cuando haya terminado.

Listing 19.1. Listado de 19.1. The full text of Crisis.java. El texto completo de Crisis.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Crisis extends java.applet.Applet { 3:
Crisis de la clase pública se extiende java.applet.Applet {
4: Button panicButton = new Button("Panic"); 4:
panicButton botón nuevo botón = ("Pánico");
5: Button dontPanicButton = new Button("Don't Panic"); 5:
dontPanicButton botón nuevo botón = ("Don't Panic");
6: Button blameButton = new Button("Blame Others"); 6:
blameButton botón = new Button ("culpar a otros");
7: Button mediaButton = new Button("Notify the Media");
7: Botón mediaButton = Botón de nuevo ("Aviso de los Medios
de Comunicación");
8: Button saveButton = new Button("Save Yourself"); 8:
saveButton botón = Botón de nuevo ("Save Yourself");
9: 9:
10: public void init() { 10: public void init () {
11: add(panicButton); 11: agregar (panicButton);
12: add(dontPanicButton); 12: agregar (dontPanicButton);
13: add(blameButton); 13: agregar (blameButton);
14: add(mediaButton); 14: agregar (mediaButton);
15: add(saveButton); 15: agregar (saveButton);
16: } 16:}
17:}

After saving the source file , you need to create a simple Web page that will display this
applet. Después de guardar el archivo de origen Crisis.java, es necesario crear una
página Web simple que mostrará este applet. Create a new file called and enter Listing
19.2. Crear un nuevo archivo llamado Crisis.html y entrar en lista 19.2.

Listing 19.2. Listado de 19.2. The full text of Crisis.html. El texto completo de
Crisis.html.

1: <applet code="Crisis.class" height=228 width=308> 1:


<applet code="Crisis.class" height=228 width=308>
2: </ applet>

Save the Web page, and then compile the file with the compiler tool. Guarde la página
Web y, a continuación, compile el archivo Crisis.java con la herramienta del compilador
javac. This applet does not specify a layout manager to use, so the rules default to . Este
applet no especifica un controlador de distribución para el uso, por lo que la omisión de las
normas FlowLayout. Use to load the Web page, and you should see something resembling
Figure 19.6. appletviewer utiliza para cargar la página Web, y usted debería ver algo
parecido a la figura 19.6.

The class uses the dimensions of its container as the only guideline for how to lay out
components. La clase FlowLayout usa las dimensiones de su envase como la única guía
para saber cómo diseñar los componentes. Resize the window of as it is, showing the
applet. Cambiar el tamaño de la ventana del appletviewer como es, que muestra el applet
de la crisis. Make the window twice as wide, and you'll see all of the components now
are shown on the same line. Hacer la ventana el doble de ancho, y verás todos los
componentes del botón ahora se muestran en la misma línea. Java programs that use the
Abstract Windowing Toolkit often will behave differently when their display area is
resized. Programas Java que utilizan el kit de herramientas de ventana de Resumen menudo
se comportan de forma diferente cuando el área de la pantalla cambia de tamaño.

Figura 19.6. The applet with all of its components laid out under the class. El applet de
crisis con todos sus componentes establecidos en el marco de la clase FlowLayout.

The GridLayout Manager El Administrador de GridLayout

The class organizes all components in a container into a specific number of rows and
columns. La clase GridLayout organiza todos los componentes en un recipiente en un
número específico de filas y columnas. All components are allocated the same amount of
space in the display area. Todos los componentes se asignan la misma cantidad de espacio
en el área de visualización. To see the applet with a grid layout, load the file back into
your word processor and edit the method. Para ver el applet de la crisis con un diseño
de red, cargue el archivo Crisis.java de nuevo en su procesador de texto y editar el
método init (). Right after the statement, add the following statements: Inmediatamente
después de su público (void init) {la declaración, agregue las siguientes
instrucciones:

GridLayout crisisLayout = new GridLayout(2, 3);


crisisLayout GridLayout = new GridLayout (2, 3);
setLayout(crisisLayout); setLayout (crisisLayout);

Save and compile the new version of and load the Web page back into . Guardar y
compilar la nueva versión de Crisis.java y la carga de páginas web Crisis.html de
nuevo en appletviewer. The output should resemble Figure 19.7. La salida debe ser
similar a la figura 19.7.

Figura 19.7. The applet with all of its components laid out under the class. El applet de
crisis con todos sus componentes establecidos en el marco de la clase GridLayout.

places all components as they are added into a place on a grid. GridLayout coloca todos
los componentes a medida que se agregan en un lugar en una cuadrícula. Components are
added from left to right until a row is full, and then the leftmost column of the next grid is
filled. Los componentes se añaden de izquierda a derecha hasta que una fila está llena, y
luego la columna de la izquierda de la parrilla del día, se llena.

The BorderLayout Manager El Administrador de BorderLayout

The last layout manager left to experiment with is the class. El controlador de distribución
pasado dejó de experimentar es la clase BorderLayout. Return to the file in your word
processor, and replace the method with the following statements: Vuelva al archivo
Crisis.java en su procesador de textos, y reemplace el método init () con las
siguientes afirmaciones:

public void init() { public void init () {


BorderLayout crisisLayout = new BorderLayout();
crisisLayout BorderLayout BorderLayout = new ();
setLayout(crisisLayout); setLayout (crisisLayout);
add(panicButton, "North"); añadir (panicButton,
"Norte");
add(dontPanicButton, "South"); añadir
(dontPanicButton, "Sur");
add(blameButton, "East"); añadir (blameButton,
"Oriente");
add(mediaButton, "West"); añadir (mediaButton,
"Oeste");
add(saveButton, "Center"); añadir (saveButton,
"Centro");
} }

After you save the change and recompile the applet, the page you load with the should
resemble Figure 19.8. Después de guardar el cambio y volver a compilar el applet de la
crisis, la página que carga con el appletviewer debe parecerse a la figura 19.8.

Figura 19.8. The applet with all of its components laid out under the class. El applet de
crisis con todos sus componentes establecidos en el marco de la clase BorderLayout.

The manager arranges components into five areas: four denoted by compass directions and
one for the center area. El administrador BorderLayout ordena los componentes en cinco
zonas: cuatro denotado por direcciones de la brújula y otro para la zona centro. When you
add a component under this layout, the method includes a second argument to specify
where the component should be placed. Cuando se agrega un componente en esta
disposición, el método add () incluye un segundo argumento para especificar que el
componente debe ser colocado. The strings , , , , and are used for this argument. Las
cadenas de "Norte", "Sur", "Oriente", "Occidente", y "Centro" se utilizan para
este argumento.

Like the class, devotes all available space to the components. Al igual que la clase
GridLayout, BorderLayout dedica todo el espacio disponible para los componentes. The
component placed in the center is given all space that isn't needed for the four border
components, so it usually is the largest. El componente situado en el centro se le da todo el
espacio que no es necesario para los cuatro componentes de la frontera, por lo que
generalmente es el más grande.

Workshop: Laying Out an Applet Taller: Diseñar un Applet


The layout managers that you have seen thus far were applied to an entire applet; the
method of the applet was used, and all components followed the same rules. Los directores
de diseño que he visto hasta el momento se han aplicado a un applet todo, el setLayout ()
de la applet se utilizan, y todos los componentes seguido las mismas reglas. This setup can
be suitable for some programs, but as you try to develop a graphical user interface with the
Abstract Windowing Toolkit, you often will find that none of the layout managers fits. Esta
configuración puede ser conveniente para algunos programas, pero a medida que tratan de
desarrollar una interfaz gráfica de usuario con el kit de herramientas de ventana de
Resumen, que a menudo se dará cuenta de que ninguno de los administradores de diseño se
adapta. One way around this problem is to use a group of objects as containers to hold
different parts of the applet window. Una forma de evitar este problema es utilizar un grupo
de objetos del panel como contenedores para sostener las diferentes partes de la ventana
del applet. You can set up different layout rules for each of these parts by using the
methods of each object. Puede configurar el diseño de reglas diferentes para cada una de
estas partes mediante el setLayout () de cada objeto del panel.

This hour's workshop will be to develop a full interface for the program that you will write
during the next hour, "Responding to User Events." Este taller de hora será el desarrollo de
una interfaz completa para el programa que va a escribir durante la hora siguiente,
"Responder a eventos de usuario." The program is a Lotto number cruncher that will assess
a user's chance of winning one of the multimillion-dollar Lotto contests in the span of a
lifetime. El programa es una supercomputadora número de lotería que evaluará posibilidad
de un usuario de ganar uno de los varios millones de dólares Lotto concursos en el
transcurso de toda la vida. This chance will be determined by running random six-number
Lotto drawings again and again until the user's numbers turn up as a big winner. Esta
oportunidad se determinará mediante la ejecución de seis números al azar dibujos Lotto una
y otra vez hasta que los números del usuario a su vez como un gran ganador. Figure 19.9
shows the GUI that you will be developing for the applet. Figura 19.9 muestra la interfaz
gráfica de usuario que se va a desarrollar para el applet.

Figura 19.9. The applet. El applet LottoGUI.

Create a new file in your word processor called . Crear un nuevo archivo en el procesador
de textos llamado LottoGUI.java. Enter Listing 19.3, and save the file when you're done.
Introduzca Listado 19.3, y guarde el archivo cuando haya terminado.

Listing 19.3. Listado de 19.3. The full text of LottoGUI.java. El texto completo de
LottoGUI.java.
1: import java.awt.*; 2: 3: public class LottoGUI extends
java.applet.Applet { 4: // set up row 1 5: Panel row1 = new
Panel(); 6: CheckboxGroup option = new CheckboxGroup(); 7:
Checkbox quickpick = new Checkbox("Quick Pick", option,
true); 8: Checkbox personal = new
Checkbox("Personal",option, false); 9: // set up row 2 10:
Panel row2 = new Panel(); 11: Label numbersLabel = new
Label("Your picks: ", Label.RIGHT); 12: TextField[] numbers
= new TextField[6]; 13: Label winnersLabel = new
Label("Winners: ", Label.RIGHT); 14: TextField[] winners =
new TextField[6]; 15: // set up row 3 16: Panel row3 = new
Panel(); 17: Button stop = new Button("Stop"); 18: Button
play = new Button("Play"); 19: Button reset = new
Button("Reset"); 20: // set up row 4 21: Panel row4 = new
Panel(); 22: Label got3Label = new Label("3 of 6: ",
Label.RIGHT); 23: TextField got3 = new TextField(); 24:
Label got4Label = new Label("4 of 6: ", Label.RIGHT); 25:
TextField got4 = new TextField(); 26: Label got5Label = new
Label("5 of 6: ", Label.RIGHT); 27: TextField got5 = new
TextField(); 28: Label got6Label = new Label("6 of 6: ",
Label.RIGHT); 29: TextField got6 = new TextField(10); 30:
Label drawingsLabel = new Label("Drawings: ", Label.RIGHT);
31: TextField drawings = new TextField(); 32: Label
yearsLabel = new Label("Years: ", Label.RIGHT); 33:
TextField years = new TextField(); 34: 35: public void
init() { 36: GridLayout appletLayout = new GridLayout(5, 1,
10, 10); 37: setLayout(appletLayout); 38: 39: FlowLayout
layout1 = new FlowLayout(FlowLayout.CENTER, 10, 10); 40:
row1.setLayout(layout1); 41: row1.add(quickpick); 42:
row1.add(personal); 43: add(row1); 44: 45: GridLayout
layout2 = new GridLayout(2, 7, 10, 10); 46:
row2.setLayout(layout2); 47: row2.setLayout(layout2); 48:
row2.add(numbersLabel); 49: for (int i = 0; i < 6; i++)
{ 50: numbers[i] = new TextField(); 51:
row2.add(numbers[i]); 52: } 53: row2.add(winnersLabel); 54:
for (int i = 0; i < 6; i++) { 55: winners[i] = new
TextField(); 56: winners[i].setEditable(false); 57:
row2.add(winners[i]); 58: } 59: add(row2); 60: 61:
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10,
10); 62: row3.setLayout(layout3); 63: row3.add(stop); 64:
row3.add(play); 65: row3.add(reset); 66: add(row3); 67: 68:
GridLayout layout4 = new GridLayout(2, 3, 20, 10); 69:
row4.setLayout(layout4); 70: row4.add(got3Label); 71:
got3.setEditable(false); 72: row4.add(got3); 73:
row4.add(got4Label); 74: got4.setEditable(false); 75:
row4.add(got4); 76: row4.add(got5Label); 77:
got5.setEditable(false); 78: row4.add(got5); 79:
row4.add(got6Label); 80: got6.setEditable(false); 81:
row4.add(got6); 82: row4.add(drawingsLabel); 83:
drawings.setEditable(false); 84: row4.add(drawings); 85:
row4.add(yearsLabel); 86: years.setEditable(false); 87:
row4.add(years); 88: add(row4); 89: } 1: import
java.awt .*; 2: 3: public class LottoGUI extiende
java.applet.Applet {4: / / establecer la fila 1 5: Panel de
row1 nuevo Panel = (); 6: opción CheckboxGroup = new
CheckboxGroup () ; 7: QuickPick Checkbox = new Casilla
("Quick Pick", opción, true); 8: Casilla de verificación
personal = new Casilla ("Personal", opción, false); 9: / /
establecer la fila 2 10: Panel de row2 = new Panel (); 11:
numbersLabel etiqueta = new Label ("Su recoge:"
Label.RIGHT); 12: TextField [] = new TextField números [6],
13: winnersLabel etiqueta = new Label ("ganadores", marca
de . DERECHA); 14: TextField [] = new TextField ganadores
[6], 15: / / establecer la fila 3 16: Panel de row3 = Grupo
nuevo (); 17: parada del botón = new Button ("Stop"); 18:
botón de reproducción = new Button ("Play"); 19: Botón de
reset = new Button ("Reset"); 20: / / establecer la fila 4
21: = new row4 Panel Panel (); 22: got3Label etiqueta = new
Label ( "3 de 6:" Label.RIGHT); 23: TextField = TextField
got3 nuevo (); 24: got4Label etiqueta = new Label ("4 de
6:" Label.RIGHT); 25: TextField = new TextField got4 ( );
26: got5Label etiqueta = new Label ("5 de 6:" Label.RIGHT);
27: TextField got5 nueva TextField = (); 28: got6Label
etiqueta = new Label ("6 de 6:" Label.RIGHT ); 29:
TextField = new TextField got6 (10); 30: drawingsLabel
etiqueta = new Label ("Dibujos", Label.RIGHT); 31: dibujos
TextField = TextField () nuevo; 32: yearsLabel etiqueta =
new Label (" años: "Label.RIGHT); 33: año nuevo TextField =
TextField (); 34: 35: public void init () {36: appletLayout
GridLayout = new GridLayout (5, 1, 10, 10); 37: setLayout (
appletLayout); 38: 39: FlowLayout FlowLayout layout1 =
nuevo (FlowLayout.CENTER, 10, 10); 40: row1.setLayout
(layout1); 41: row1.add (QuickPick); 42: row1.add
(personal), 43 : agregar (row1); 44: 45: GridLayout Layout2
= new GridLayout (2, 7, 10, 10); 46: row2.setLayout
(Layout2); 47: row2.setLayout (Layout2); 48: row2.add
(numbersLabel ); 49: 0; <i 6; for (int i = i + +) {50: Los
números de i] = new TextField [(); 51: row2.add (números de
[i]); 52:} 53: row2.add (winnersLabel); 54: para (<i 6; int
i = 0; i + +) {55: ganadores [i] = nuevo TextField (); 56:
ganadores [i]. setEditable (false); 57 row2.add ( ganadores
[i]); 58:} 59: agregar (row2); 60: 61: FlowLayout
FlowLayout layout3 nueva = (FlowLayout.CENTER, 10, 10); 62:
row3.setLayout (layout3); 63: row3.add ( parada); 64:
row3.add (obra teatral); 65: row3.add (reset); 66: añadir
(row3); 67: 68: GridLayout layout4 nueva GridLayout = (2,
3, 20, 10); 69: row4 . setLayout (layout4); 70: row4.add
(got3Label); 71: got3.setEditable (false); 72: row4.add
(got3); 73: row4.add (got4Label); 74: got4.setEditable
(falso) ; 75: row4.add (got4); 76: row4.add (got5Label);
77: got5.setEditable (false); 78: row4.add (got5); 79:
row4.add (got6Label); 80: got6. setEditable (false); 81:
row4.add (got6); 82: row4.add (drawingsLabel); 83:
drawings.setEditable (false); 84: row4.add (dibujos); 85:
row4.add (yearsLabel); 86: years.setEditable (false); 87:
row4.add (años); 88: añadir (row4); 89:} 90:}

Compile this file with the compiler tool, and return to your word processor to create a Web
page for this applet. Compilar este archivo con la herramienta del compilador javac, y
regreso a su procesador de textos para crear una página Web de este applet. Create a new
file called and enter Listing 19.4. Crear un nuevo archivo llamado LottoGUI.html y entrar
en lista 19.4. Save the file when you're done. Guarde el archivo cuando haya terminado.

Listing 19.4. Listado de 19.4. The full text of LottoGUI.html. El texto completo de
LottoGUI.html.

1: <html> 1: <html>
2: <head> 2: <head>
3: <title>Lotto Madness</title> 3: <title> Lotto Madness
</ title>
4: </head> 4: </ head>
5: <body bgcolor="#4b4b4b"> 5: bgcolor="#4b4b4b"> <body
6: <applet code="LottoGUI.class" width=550 height=270> 6:
<applet code="LottoGUI.class" width=550 height=270>
7: </applet> 7: </ applet>
8: </body> 8: </ body>
9: </ html>

Try this Web page out with the tool, and you'll get a chance to see how the applet will
work. Pruebe esta la página Web con la herramienta appletviewer, y usted tendrá la
oportunidad de ver cómo el applet LottoGUI funcionará. Even though you haven't added
any statements that make the program do anything yet, you can make sure that the graphical
interface does what you need it to do. A pesar de que aún no ha añadido ninguna de las
declaraciones que hacen que el programa haga algo, sin embargo, puede asegurarse de que
la interfaz gráfica es lo que usted necesita que haga.

This applet uses several different layout managers. En esta aplicación se utiliza varios
controladores de distribución diferentes. If you look carefully at each of the components,
you might be able to determine which manager is in use in the different areas of the
program. Si se mira con detenimiento cada uno de los componentes, puede ser capaz de
determinar qué gestor está en uso en las diferentes áreas del programa. To get a clearer
picture of how the applet is laid out, take a look at Figure 19.10. Para tener una idea más
clara de cómo el applet se presenta, echar un vistazo a la Figura 19.10. The interface is
divided into five horizontal rows. La interfaz se divide en cinco filas horizontales. Each of
these rows is a object, and the overall layout manager of the applet organizes these rows
into a of five rows and one column. Cada una de estas filas es un objeto del panel, y el
controlador de distribución general del subprograma organiza estas filas en un GridLayout
de cinco filas y una columna.

Figura 19.10. The way the class is organized. La forma en la clase LottoGUI se organiza.

Within the rows, different layout managers are used to determine how the components
should appear. Dentro de las filas, los administradores de diferentes diseño se utilizan para
determinar cómo los componentes deben aparecer. Rows 1 and 3 use objects. Las filas 1 y
3 objetos FlowLayout uso. Line 39 of the program shows how these objects are created: La
línea 39 del programa muestra cómo estos objetos se crean:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10,


10); FlowLayout layout1 = new FlowLayout
(FlowLayout.CENTER, 10, 10);
Three arguments are used with the constructor method. Tres argumentos se utilizan con el
FlowLayout () método constructor. The first argument, , indicates that the components
should be centered within their container--the horizontal they are placed on. El primer
argumento, FlowLayout.CENTER, indica que los componentes deben estar centrados dentro
de su contenedor - la horizontal del panel que se colocan en. The last two components
specify the width and height each component should be moved away from other
components. Los dos últimos componentes especificar la anchura y la altura de cada
componente debe estar alejado de otros componentes. Using a width of 10 pixels and a
height of 10 pixels puts a small amount of extra distance between the components. El uso
de un ancho de 10 píxeles y una altura de 10 píxeles pone una pequeña cantidad de la
distancia extra entre los componentes.

Row 2 of the applet is laid out into a grid that is two rows tall and seven columns wide. Fila
2 de la applet se presenta en una cuadrícula que tiene dos filas de alto y de ancho siete
columnas. The constructor also specifies that components should be set apart from other
components by 10 pixels in each direction. El GridLayout () constructor también
especifica que los componentes deben ser apartados de otros componentes en un 10 píxeles
en cada dirección. Lines 45 and 46 set up this grid: Líneas 45 y 46 creó esta red:

GridLayout layout2 = new GridLayout(2, 7, 10, 10);


GridLayout Layout2 = new GridLayout (2, 7, 10, 10);
row2.setLayout(layout2); row2.setLayout (Layout2);

Row 4 uses to arrange components into a grid that is two rows tall and six columns wide.
Fila 4 usa GridLayout para organizar los componentes en una cuadrícula que tiene dos
filas de alto y seis columnas de ancho.

The applet uses several of the components described during this hour. El applet LottoGUI
utiliza varios de los componentes descritos en esta hora. Lines 4-33 are used to set up
objects for all of the components that make up the interface. Las líneas 4 a 33 se utilizan
para configurar los objetos de todos los componentes que conforman la interfaz. The
statements are organized by row. Los estados están organizados por filas. First, a object for
the row is created, and then each component that will go on the row is set up. En primer
lugar, un objeto del panel de la fila se crea, y luego cada componente que vaya en la fila
se establece. This code creates all of the components and containers, but they will not be
displayed unless an method is used to put them onto the display area. Este código crea
todos los componentes y contenedores, pero no se mostrará a menos que un método add ()
se utiliza para ponerlos en el área de visualización.
In Lines 36-88, the components are added. En las líneas 36 a 88, los componentes se
agregan. Lines 39-43 are indicative of the entire method: Líneas 39-43 son indicativos de
la totalidad de inicio () método:

FlowLayout layout1 = new FlowLayout(FlowLayout.CENTER, 10,


10); FlowLayout layout1 = new FlowLayout
(FlowLayout.CENTER, 10, 10);
row1.setLayout(layout1); row1.setLayout (layout1);
row1.add(quickpick); row1.add (QuickPick);
row1.add(personal); row1.add (personal);
add(row1); añadir (row1);

After a layout manager object is created, it is used with the method of the row's object--
in this case. Después de un objeto de controlador de distribución se crea, se utiliza con la
setLayout () de la fila de un grupo especial objeto - row1 en este caso. Once the
layout has been specified, components are added to the object by using its method. Una
vez que el diseño se ha especificado, se agregan componentes al objeto del panel,
utilizando su método add (). Once all of the components have been placed, the entire
object is added to the applet window using its own method. Una vez que todos los
componentes han sido colocados, todo el row1 objeto se añade a la ventana del applet
usando su propia agregar () método.

Summary Resumen
Users have come to expect a point-and-click, visual environment for the programs that they
run. Los usuarios han llegado a esperar un punto y hacer clic, el medio ambiente visual para
los programas que se ejecutan. This expectation makes creating software more of a
challenge, but Java puts these capabilities into your hands with the windowing toolkit. Esta
expectativa hace que la creación de software más de un desafío, pero Java pone estas
capacidades en sus manos con el kit de herramientas de ventanas. The Abstract Windowing
Toolkit provides all the classes you will need to provide a working, useful GUI in the
tradition of Windows and Macintosh software--regardless of what kind of setup you're
running Java programs on. El resumen de ventanas Toolkit proporciona todas las clases que
se necesitan para proporcionar un trabajo, útil interfaz gráfica de usuario en la tradición de
Windows y software para Macintosh - sin importar de qué tipo de instalación que se está
ejecutando programas de Java en.

During the next hour, you'll learn more about the function of a graphical user interface.
Durante la hora siguiente, usted aprenderá más acerca de la función de una interfaz gráfica
de usuario. You'll get a chance to see the interface in use as it churns through lottery
drawings and tallies up winners. Usted tendrá la oportunidad de ver la interfaz LottoGUI en
uso, ya que se agita a través de dibujos de la lotería y cuentas a los ganadores.

Q&A Q & A
Q Why are some of the text fields in the LottoGUI applet shaded in gray while others are
white? Q ¿Por qué son algunos de los campos de texto del applet LottoGUI sombreadas
en color gris, mientras que otros son blancos?

A The method has been used on the gray fields to make them impossible to edit. A El
setEditable () método se ha utilizado en los campos grises para que sean imposibles
de modificar. The default behavior of a text field is to enable users to change the value of
the text field by clicking within its borders and typing any desired changes. El
comportamiento predeterminado de un campo de texto es permitir a los usuarios cambiar
el valor del campo de texto haciendo clic dentro de sus fronteras y escribir los cambios
que desee. However, some fields are intended to display information rather than take
input from the user. Sin embargo, algunos campos están destinados a mostrar la
información en lugar de tomar la entrada del usuario. The method prevents users from
changing a field that they should not modify. El setEditable () método impide que los
usuarios cambien de un campo que no debe modificar.

Q Can more than one line of text be displayed on a Label object? Q ¿Puede más de una
línea de texto se muestren en un objeto Label?

A No, labels are limited to a single line of text. R No, las etiquetas se limita a una sola línea
de texto. You cannot use newline characters (` ') as you might with a object to create
default text that is more than one line long. No puede utilizar caracteres de nueva línea
('\ n') como se puede con un objeto TextArea para crear un texto por defecto que es
más que una línea larga.

Quiz Quiz
If your brain hasn't been turned into a GUI mush with this hour's toil, test your skills by
answering the following questions. Si su cerebro no se ha convertido en una papilla interfaz
gráfica de usuario con esta hora de trabajo, probar sus habilidades al contestar las siguientes
preguntas.

Questions Preguntas

1. Which user component is used as a container to hold other components? 1. Usuario del
componente que se utiliza como un recipiente para contener otros componentes?

(a) (A) Tupperware


(b) (B) la Comisión Técnica
(c) (C) Elección

2. Which of the following must be done first within a container? 2. ¿Cuál de los siguientes
deben hacerse en primer lugar dentro de un contenedor?
(a) Establish a layout manager (A) Establecer un esquema director de
(b) Add components (B) Agregar componentes
(c) Doesn't matter (C) No importa

3. Where does the class get its name? 3. ¿De dónde viene la clase BorderLayout su
nombre?

(a) The border of each component (A) El borde de cada componente


(b) The way components are organized along the borders of a container (B) Los
componentes manera se organizan a lo largo de las fronteras de un contenedor
(c) Sheer capriciousness on the part of Java's developers (C) Pura arbitrariedad por parte
de los desarrolladores de Java

Answers Respuestas

1. b. 1. B.

2. a. 2. A. You must specify the layout manager before the components so that you can
add them in the correct way. Debe especificar el controlador de distribución antes de los
componentes para que pueda añadirlos en la forma correcta.

3. b. 3. B. The border position of components must be specified as they are added to a


container with the use of directional strings such as "East" and "West." La posición
fronteriza de los componentes deben ser especificados, ya que se agregan a un
contenedor con el uso de cadenas de dirección, tales como "Este" y "Occidente".

Activities Actividades
To interface further with the subject of GUI design, undertake the following activity: Para
interactuar más con el tema del diseño de interfaz gráfica de usuario, realizar la actividad
siguiente:

 Create a modified version of the applet with the and objects organized under one layout
manager and the remaining three buttons under another. Crear una versión modificada
del applet con la crisis de pánico y objetos dontPanic organizada bajo un
controlador de distribución y los otros tres botones debajo de otra.

 20 horas
o Responder a eventos de usuario
 Cómo hacer llegar su Programas para escuchar
 Configuración de los componentes a ser escuchado
 Gestión de eventos de usuario
 Revise y elección Eventos Caja
 Otros eventos de campo de texto
 Activación y desactivación de los componentes
 Taller: Una locura Lotto poco
 Figura 20.1.
 Listado de 20.1. El texto completo de LottoMadness.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 20 20 horas

Responding to User Events Responder a eventos de


usuario

The graphical user interface that you developed during the past hour can run on its own
without any changes. La interfaz de usuario gráfica que se desarrolló durante la última hora
se puede ejecutar por su cuenta sin ningún cambio. Buttons can be clicked, text fields filled
with text, and the applet window can be resized with wild abandon. Los botones pueden
hacer clic, los campos de texto lleno de texto, y la ventana del applet puede cambiar el
tamaño con abandono salvaje. Sooner or later, however, even the least discriminating user
is going to be left wanting more. Tarde o temprano, sin embargo, incluso los usuarios
menos exigentes se van a quedar con ganas de más. The graphical user interface that a
program offers has to cause things to happen when a mouse click or keyboard entry occurs.
La interfaz gráfica de usuario que ofrece un programa tiene que hacer que las cosas suceden
cuando un clic del ratón o la entrada de teclado se produce. Text areas and other
components must be updated to show what's happening as the program runs. Las áreas de
texto y otros componentes debe ser actualizado para mostrar lo que está sucediendo en el
programa se ejecuta.

These things are possible when your Java program can respond to user events. Estas cosas
son posibles cuando el programa Java puede responder a eventos de usuario. An event is
something that happens when a program runs, and user events are things that a user causes
by using the mouse, keyboard, or another input device. Un evento es algo que sucede
cuando un programa se ejecuta, y los eventos de usuario son cosas que un usuario hace con
el ratón, teclado u otro dispositivo de entrada. Responding to user events often is called
event-handling, and it's the activity you'll be learning about during this hour. Responder a
eventos de usuario a menudo se llama de control de eventos, y es la actividad que estará
aprendiendo acerca de durante esta hora.

The following topics will be covered: Los siguientes temas serán cubiertos:
 Making your programs aware of events Realización de los programas tanto de los
acontecimientos
 Setting up a component so it can cause events La creación de un componente de lo que
puede hacer que los eventos
 Components that can be ignored Los componentes que pueden ser ignorados
 Where events end up in a program Cuando los eventos finales en un programa
 Storing information in the interface Almacenamiento de información en la interfaz
 Using numeric variables with text fields Uso de variables numéricas con campos de texto

Getting Your Programs to Listen Cómo hacer llegar su Programas para escuchar
Responding to user events in a Java program requires the use of one or more interfaces. En
respuesta a los eventos de usuario en un programa Java requiere el uso de una o más
interfaces EventListener. As you might recall from using the interface for multithreaded
programs, interfaces are special classes that enable a class of objects to inherit behavior that
it would not be able to use otherwise. Como se puede recordar el uso de la interface
Runnable para programas multihilo, las interfaces son clases especiales que permiten a una
clase de objetos a heredar un comportamiento que no sería capaz de utilizar de otra manera.
Adding an interface involves two things right away. Añadiendo una interfaz
EventListener implica dos cosas de inmediato. First, because the listening classes are part
of the group of classes, you must make them available with the following statement: En
primer lugar, porque las clases de música son parte del grupo java.awt.event de clases,
deberá ponerlos a disposición con la siguiente declaración:

import java.awt.event.*; importación java.awt.event .*;

Secondly, the class must use the statement to declare that it will be using one or more
listening interfaces. En segundo lugar, la clase debe utilizar los implementos declaración a
declarar que va a utilizar una o más interfaces de escucha. The following statement creates
a class that uses , an interface used with buttons and other components: La siguiente
sentencia crea una clase que utiliza ActionListener, una interfaz que se utiliza con los
botones y otros componentes:

public class Graph extends java.applet.Applet implements


ActionListener { public class Gráfico extiende
java.applet.Applet implements ActionListener {

The interfaces enable a component of a graphical user interface to generate user events.
Las interfaces EventListener permitir un componente de una interfaz gráfica de usuario
para generar eventos de usuario. Without one of the listeners in place, a component cannot
do anything that can be heard by other parts of a program. Sin uno de los oyentes en su
lugar, un componente no puede hacer cualquier cosa que pueda ser oído por otras partes de
un programa. A program must include a listener interface for each type of component it
wants to listen to. Un programa debe incluir un interfaz de escucha para cada tipo de
componente que quiere escuchar. To have the program respond to a mouse click on a
button or the Enter key being pressed in a text field, you must include the interface. Para
que el programa responde a un clic del ratón sobre un botón o la tecla Enter siendo
presionado en un campo de texto, debe incluir la interfaz ActionListener. To respond to
the use of a choice list or check boxes, the interface is needed. Para responder al uso de la
opción o la lista de casillas de verificación una, la interfaz ItemListener es necesario.
When you require more than one interface, separate their names with commas after the
statement. Cuando se requieren más de una interfaz, separe sus nombres con comas después
de la implementa comunicado. The following is an example: El siguiente es un ejemplo:

public class Graph3D extends java.applet.Applet implements


ActionListener, MouseListener { Graph3D clase pública se
extiende java.applet.Applet implementa ActionListener,
MouseListener {

Setting Up Components to Be Heard Configuración de los componentes a ser escuchado


Once you have implemented the interface that is needed for a particular component, you
have to set up that component so that it generates user events. Una vez que haya
implementado la interfaz que se necesita para un componente en particular, tiene que
configurar el componente para que genere eventos de usuario. A good example to consider
is the use of objects as components. Un buen ejemplo a considerar es el uso de objetos
Button como componentes. When you use a button in an interface, something has to happen
in response to the click of the button. Cuando se utiliza un botón en una interfaz, algo tiene
que ocurrir en respuesta a un clic del botón. Otherwise, the button's not needed for the
interface at all. De lo contrario, el botón no es necesario para la interfaz en absoluto.

The program that needs to respond to the button click should use the interface. El
programa que tiene que responder a las haga clic en el botón debe utilizar la interfaz
ActionListener. The name of the interface comes from calling a button click or the press
of the Enter key an action event, because it signifies that some kind of action should be
taken. El nombre de la interfaz viene de llamar a un clic de botón o la presión de la tecla
Intro un evento de acción, porque significa que algún tipo de medidas deben adoptarse. To
make a object generate an event, use the method, as in the following: Para hacer que un
objeto Button generar un evento, utilice la addActionListener () método, como en el
siguiente:

Button fireTorpedoes = new Button("Fire torpedoes");


fireTorpedoes.addActionListener(this); Botón fireTorpedoes
= new Button ("Fuego torpedos");
fireTorpedoes.addActionListener (este);
This code creates the object and then calls that object's method. Este código crea el objeto
fireTorpedoes y luego llama a objeto de que addActionListener () método. The
statement indicates that the current class of objects will receive the user event and handle it
as needed. La declaración indica que la clase actual de los objetos recibirá el evento de
usuario y manejarlo según sea necesario.

Handling User Events Gestión de eventos de usuario


When a user event is generated by a component that has a listener, a method will be called
automatically. Cuando un evento de usuario es generada por un componente que tiene un
oyente, un método será llamado automáticamente. The method must be found in the class
that was specified when the listener was attached to the component. El método se debe
encontrar en la clase que se especificó cuando el oyente se adjunta con el componente. For
instance, in the example of the object, the method must be located in the same program
because the statement was used. Por ejemplo, en el ejemplo del objeto fireTorpedoes, el
método debe estar ubicado en el mismo programa porque la instrucción que se utilizó.

Each listener has different methods that are called to receive their events. Cada oyente tiene
métodos diferentes que son llamados a recibir sus eventos. The interface sends events to a
class called . La interfaz ActionListener envía eventos a una clase llamada
actionPerformed (). The following is a short example of an method: El siguiente es un
breve ejemplo de un actionPerformed () método:

void public actionPerformed(ActionEvent evt) { public void


actionPerformed (ActionEvent evt) {
// method goes here / / Método va aquí
} }

All action events sent in the program will go to this method. Todos los temas de acción
enviadas en el programa se dirija a este método. If only one component in a program can
possibly send action events, you can put statements in this method to handle the event. Si
sólo uno de los componentes en un programa posiblemente puede enviar eventos de acción,
usted puede poner las declaraciones en este método para controlar el evento. If more than
one component can send these events, you need to use the object that is sent to the method.
Si más de un componente puede enviar estos eventos, es necesario utilizar el objeto que se
envía al método.

In this case, an object is sent to the method. En este caso, un objeto ActionEvent se envía
a la actionPerformed () método. There are several different classes of objects that
represent the user events that can be sent in a program. Hay varias clases diferentes de
objetos que representan los eventos de usuario que se pueden enviar en un programa. These
classes have methods you can use to determine which component caused the event to
happen. Estas clases tienen métodos que puede utilizar para determinar qué componente
causó el evento que ocurra. In the method, if the object is named , you can identify the
component with the following statement: En el actionPerformed () método, si el objeto
ActionEvent evt se denomina, puede identificar el componente con la siguiente
declaración:

String cmd = evt.getActionCommand(); String cmd =


evt.getActionCommand ();

The method sends back a string. El getActionCommand () método devuelve una cadena.
If the component is a button, the string will be the label that is on the button. Si el
componente es un botón, la cadena será la etiqueta que está en el botón. If it's a text field,
the string will be the text entered in the field. Si se trata de un campo de texto, la cadena
será el texto introducido en el campo. The method sends back the object that caused the
event. El método getSource () devuelve el objeto que causó el evento.

You could use the following method to receive events from three components: a object
called , a called , and another called : Usted puede utilizar el siguiente
actionPerformed () para recibir eventos de tres componentes: un botón de objeto de
inicio llamada, una llamada velocidad TextField, y otro TextField llamado
viscosidad:

void public actionPerformed(ActionEvent evt) { public void


actionPerformed (ActionEvent evt) {
Object source = evt.getSource(); fuente de objetos =
evt.getSource ();
if (source == speed) { if (fuente de velocidad ==) {
// speed field caused event / / Campo de velocidad
causó evento
} else if (source == viscosity) { } Else if (origen ==
viscosidad) {
// viscosity caused event / / Viscosidad causada
evento
} else } Else
// start caused event / / Inicio del evento
causado

You can use the method with all types of user events to identify the specific object that
caused the event. Usted puede utilizar el getSource () con todo tipo de eventos de usuario
para identificar el objeto específico que provocó el evento.
Check Box and Choice Events Revise y elección Eventos Caja

Choice lists and check boxes require the interface. las listas de opciones y casillas de
verificación requiere la interfaz ItemListener. To make one of these components
generate events, use the method. Para hacer uno de estos componentes generan eventos,
utilice el addItemListener () método. For example, the following statements create a
check box called and cause it to send out user events when selected or deselected: Por
ejemplo, las siguientes afirmaciones crear una casilla de verificación llamada SuperSize y
hacer que se envían los eventos del usuario cuando está seleccionado o no seleccionado:

Checkbox superSize = new Checkbox("Super Size", true);


Casilla de verificación SuperSize = new Casilla ("Super
Size", true);
superSize.addItemListener(this); superSize.addItemListener
(este);

These events are received by the method, which takes an object as an argument. Estos
eventos son recibidos por el itemStateChanged () método, que toma un objeto
ItemEvent como argumento. To see which object caused the event, you can use the
method. Para ver el objeto que causó el evento, puede utilizar el getItem () método.

To determine whether a check box is selected or deselected, use the method with the
constants and . Para determinar si una casilla está activada o desactivada, utilice el
getStateChange () con las constantes ItemEvent.SELECTED y ItemEvent.DESELECTED.
The following is an example for an object called : El siguiente es un ejemplo de un objeto
llamado ItemEvent artículo:

int status = item.getStateChange(); int status =


item.getStateChange ();
if (status == ItemEvent.SELECTED) if (estado ==
ItemEvent.SELECTED)
// item was selected / / Tema fue seleccionado

To determine the value that has been selected in a object, use and convert that value to a
string, as in the following: Para determinar el valor que ha sido seleccionada en un objeto
de elección, getItem uso () y convertir ese valor en una cadena, como en lo siguiente:

Object which = item.getItem(); Objeto que item.getItem =


();
String answer = (String) which; String respuesta =
(String) que;
Other Text Field Events Otros eventos de campo de texto

If you want to check on a text field or text area after its value has been changed, use the
interface. Si desea comprobar en un campo de texto o área de texto después de que su valor
se ha modificado, utilice la interfaz TextListener. The method makes a text component
actively generate user events, and the method receives the events. El addTextListener
() método permite un componente de texto activamente generar eventos de usuario, y el
textValueChanged () método recibe los eventos. The following example receives events
from objects called and : El siguiente ejemplo se reciben los eventos de los objetos
TextField llamado dirección y código postal:

public void textValueChanged(TextEvent txt) { public void


textValueChanged (txt TextEvent) {
Object source = txt.getSource(); fuente de objetos =
txt.getSource ();
if (source == address) si (la dirección de origen ==)
String newAddress = address.getText();
NuevaDireccion String = address.getText ();
} else } Else
String newZipCode = zipCode.getText(); newZipCode
String = zipCode.getText ();

} }

The method is used with text components to retrieve their values. El gettext () se utiliza
con los componentes de texto para recuperar sus valores. The method can set the value of a
text field or text area. El método setText () puede establecer el valor de un campo de
texto o área de texto.

Enabling and Disabling Components Activación y desactivación de los componentes

You may have seen a component in a program that appears shaded instead of its normal
appearance. Usted puede haber visto un componente de un programa que aparece
sombreado en lugar de su apariencia normal. This shading indicates that users cannot do
anything to the component because it is disabled. Este sombreado indica que los usuarios
no pueden hacer nada al componente porque está deshabilitado. Disabling and enabling
components as a program runs is done with the method of the component. Desactivación y
activación de los componentes de un programa se ejecuta como se hace con el () de
setEnabled del componente. A Boolean value is sent as an argument to the method, so
enables a component for use, and disables a component. Un valor booleano que se envía
como un argumento para el método, por lo que setEnabled (verdadero) permite a un
componente para su uso y setEnabled false) desactiva (un componente.

This method is an effective way to prevent a component from sending a user event when it
shouldn't. Este método es una manera eficaz de prevenir el envío de un componente de un
evento de usuario cuando no debe. For example, if you're writing a Java applet that takes a
user's address in text fields, you might want to disable a Continue button until all of the
fields have some kind of value. Por ejemplo, si usted está escribiendo un applet de Java que
tiene la dirección de un usuario en los campos de texto, es posible que desee desactivar un
botón Continuar hasta que todos los campos tienen algún tipo de valor.

Workshop: A Little Lotto Madness Taller: Una locura Lotto poco


For more examples of how event-handling works in the context of a Java program, you will
finish the Lotto applet that you began during Hour 19, "Building a Simple User Interface."
Para más ejemplos de cómo funciona la gestión de eventos en el contexto de un programa
Java, que terminará el applet Lotto que comenzó durante la hora 19, "Creación de una
interfaz de usuario sencilla." The name of the applet will be changed from to to reflect its
status as a program. El nombre del applet se cambiará de LottoGUI a LottoMadness para
reflejar su estatus como un programa. The purpose of this applet is to assess the user's
chances of winning a six-number Lotto drawing in a lifetime. El objetivo de este
subprograma es evaluar las posibilidades del usuario de ganar un sorteo de seis números de
Lotto en la vida. Figure 20.1 shows a screen capture of the program as it continues to run.
Figura 20.1 muestra una captura de pantalla del programa, ya que sigue funcionando.

Instead of using probability to figure out this problem, the computer will take a more
anecdotal approach: It will conduct drawing after drawing after drawing until you win. En
lugar de utilizar la probabilidad de descubrir este problema, el equipo tendrá un enfoque
más anecdótico: Se llevará a cabo el dibujo después de dibujar después de dibujar hasta que
gane. Because the 6-out-of-6 win is extremely unlikely, the program also will report on any
combination of three, four, or five winning numbers. Debido a la victoria de 6 fuera de 6 es
muy poco probable, el programa también informará sobre cualquier combinación de tres,
cuatro o cinco números ganadores.

The interface that you created includes 12 text fields for Lotto numbers and two check
boxes labeled Quick Pick and Personal. La interfaz que creó incluye 12 campos de texto
para los números de lotería y dos casillas de verificación denominada Quick Pick y
personal. Six of the text fields are disabled from input; they will be used to display the
winning numbers of each drawing. Seis de los campos de texto están desactivados desde la
entrada, sino que se utiliza para mostrar los números ganadores de cada sorteo. The other
six text fields are for the user's choice of numbers. Los otros seis campos de texto son para
la elección del usuario de los números. If the user wants to select six numbers manually, he
should select the Personal check box. Si el usuario quiere seleccionar seis números de
forma manual, se debe seleccionar la casilla de verificación personal. If he selects the
Quick Pick box instead, six random numbers will appear in the text fields. Si activa la
casilla de selección rápida en lugar de seis números al azar aparecerá en los campos de
texto.

Figura 20.1. The applet continues to run. El applet LottoMadness sigue funcionando.

Three buttons control the activity of the program: Stop, Play, and Reset. Tres botones de
control de la actividad del programa: Stop, Play, y el reajuste. When the Play button is
pressed, the program starts a thread called and generates Lotto drawings as fast as it can.
Cuando el botón se pulsa Play, el programa se inicia un subproceso llama a jugar y genera
dibujos Lotto tan rápido como puede. Pressing the Stop button stops the thread, and
pressing Reset clears all fields so the user can start the number-crunching all over again. Al
pulsar el botón Stop detiene el hilo, y pulsando Restaurar borra todos los campos que el
usuario pueda iniciar el procesamiento de datos numéricos de nuevo.

The applet implements three interfaces: , , and . El applet LottoMadness implementa tres
interfaces: ActionListener, ItemListener y ejecutables. The first two are needed to
listen to user events generated by the buttons and check boxes on the applet. Los dos
primeros son necesarios para escuchar a los eventos generados por los usuarios de los
botones y casillas de verificación en el applet. The program does not need to listen to any
events related to the text fields, because they will be used strictly to store the user's choice
of numbers. El programa no necesita escuchar ningún evento relacionado con los campos
de texto, ya que se utilizarán estrictamente para almacenar la elección del usuario de los
números. The user interface handles this function automatically. La interfaz de usuario se
encarga de esta función automáticamente.

Listing 20.1 shows the full text of the applet. Listado de 20.1 muestra el texto completo del
applet LottoMadness. The shaded lines in the listing were unchanged from . Las líneas de
sombra en el listado se mantuvieron sin cambios desde LottoGUI.java. The unshaded
statements are what must be added to respond to user events and run the Lotto drawings.
Los estados sin sombra es lo que hay que añadir para responder a eventos de usuario y
ejecutar los dibujos Lotto.

Making this program aware of user events for some components requires only a few
additions. Hacer este programa tanto de los eventos de usuario para algunos componentes
sólo requiere algunas adiciones. The statement in Lines 4-6 is changed to use the
interfaces. La declaración de clase en las líneas 4-6 se cambia para utilizar las interfaces.
Lines 46-51 add the listeners that are needed for the two check boxes and three button
components. Líneas 46-51 añadir los oyentes que se necesitan para las dos casillas de
verificación y tres componentes de botón. One line is added to the program in the method
where components are placed on the user interface. Una línea se añade al programa en el
método init () donde los componentes se colocan en la interfaz de usuario. In Line 77,
the object is disabled with the method. En la línea 77, el objeto de parada con
discapacidad con la setEnabled (falso) método. Because no drawings are taking place
when the program begins running, the Stop button should not be usable at that point.
Debido a que no son dibujos que tienen lugar cuando el programa comienza a funcionar, el
botón de parada no debe ser utilizable en ese momento.

The following methods are used in the program to accomplish specific tasks: Los siguientes
métodos se utilizan en el programa para realizar tareas específicas:

 Lines 146-156: The method causes all text fields in the applet to be emptied out. Líneas
146-156: El clearAllFields () método hace que todos los campos de texto del applet
para ser vaciado. This method is handled when the Reset button is pressed. Este método
se controla cuando el botón Reset.
 Lines 159-162: The method converts a text field to an integer, increments it by one, and
converts it back into a text field. Líneas 159-162: El addOneToField () método
convierte un campo de texto a un número entero, lo incrementa en uno, y lo convierte de
nuevo en un campo de texto. Because all text fields are stored as strings, you have to take
special steps to use some of them as numbers. Debido a que todos los campos de texto se
almacenan como cadenas, usted tiene que tomar medidas especiales para poder usar
algunas de ellas como números.
 Lines 165-169: The method takes three arguments--a single number from a Lotto drawing,
an array that holds several objects, and a integer. Líneas 165-169: El numberGone ()
toma tres argumentos - un número único de un dibujo de Lotto, una matriz que contiene
varios objetos TextField y un entero de la cuenta. This method makes sure that each
number in a drawing hasn't been selected already in the same drawing. Este método se
asegura de que cada número en un sorteo no se ha seleccionado ya está en el mismo
dibujo.
 Lines 172-178: The method takes two arguments--a object and an array of six objects.
Líneas 172-178: El matchedOne () toma dos argumentos - un objeto TextField y una
serie de seis objetos TextField. This method checks to see whether one of the user's
numbers is a winner. Este método comprueba para ver si uno de los números que el
usuario es un ganador.

The method of the applet receives the action events caused when the user presses Stop,
Play, or Reset. El () método actionPerformed del applet recibe los eventos de acción
produce cuando el usuario pulsa Stop, Play, o Reset. The method retrieves the label of the
button, which is used to determine which component was pressed. El getActionCommand
() método recupera la etiqueta del botón, que se utiliza para determinar qué componente se
ha presionado. Pressing the Play button causes four components to be disabled so that they
do not interfere with the drawings as they are taking place. Al pulsar el botón Reproducir
hace cuatro componentes para ser desactivado para que no interfieran con los dibujos, ya
que se están produciendo. Pressing Stop reverses this by enabling every component except
for the Stop button. Al pulsar Detener invierte esta permitiendo a todos los componentes
excepto el botón de parada.

The method receives the user events caused when one of the check boxes is selected. El
itemStateChanged () método recibe los eventos de usuario produce cuando una de las
casillas de verificación está activada. The method sends back an , which is converted to a
string to determine the label of the check box. El getItem () método devuelve un
objeto, que se convierte en una cadena para determinar la etiqueta de la casilla de
verificación.

One last thing to note about the applet is the lack of variables used to keep track of things
like the number of drawings, winning counts, and Lotto number text fields. Una última cosa
a la nota sobre el applet LottoMadness es la falta de variables que se utilizan para realizar
un seguimiento de cosas como el número de dibujos, ganando cuenta, y el número de
campos de texto Lotto. This element of user interface programming differs from other types
of programs. Este elemento de la programación de la interfaz de usuario es diferente de
otros tipos de programas. You can use the interface to store values and display them
automatically. Usted puede utilizar la interfaz para almacenar los valores y los muestra de
forma automática.

Load the original program into your word processor and save the file under the new name
. Cargue el programa original de LottoGUI.java en su procesador de texto y guarde el
archivo bajo el nuevo nombre LottoMadness.java. After changing the statement to
reflect the new name of the program and the interfaces it will use, insert all of the non-
shaded lines from Listing 20.1 and save the file. Después de cambiar la declaración de
clase para reflejar el nuevo nombre del programa y las interfaces que va a utilizar, insertar
todas las líneas de sombra-no del listado 20.1 y guardar el archivo.

Listing 20.1. Listado de 20.1. The full text of LottoMadness.java. El texto completo de
LottoMadness.java.
1: import java.awt.*; 2: import java.awt.event.*; 3: 4:
public class LottoMadness extends java.applet.Applet 5:
implements ItemListener, ActionListener, 6: Runnable { 7:
8: Thread playing; 9: 10: // set up row 1 11: Panel row1 =
new Panel(); 12: CheckboxGroup option = new
CheckboxGroup(); 13: Checkbox quickpick = new
Checkbox("Quick Pick", option, false); 14: Checkbox
personal = new Checkbox("Personal",option, true); 15: //
set up row 2 16: Panel row2 = new Panel(); 17: Label
numbersLabel = new Label("Your picks: ", Label.RIGHT); 18:
TextField[] numbers = new TextField[6]; 19: Label
winnersLabel = new Label("Winners: ", Label.RIGHT); 20:
TextField[] winners = new TextField[6]; 21: // set up row 3
22: Panel row3 = new Panel(); 23: Button stop = new
Button("Stop"); 24: Button play = new Button("Play"); 25:
Button reset = new Button("Reset"); 26: // set up row 4 27:
Panel row4 = new Panel(); 28: Label got3Label = new
Label("3 of 6: ", Label.RIGHT); 29: TextField got3 = new
TextField(); 30: Label got4Label = new Label("4 of 6: ",
Label.RIGHT); 31: TextField got4 = new TextField(); 32:
Label got5Label = new Label("5 of 6: ", Label.RIGHT); 33:
TextField got5 = new TextField(); 34: Label got6Label = new
Label("6 of 6: ", Label.RIGHT); 35: TextField got6 = new
TextField(10); 36: Label drawingsLabel = new
Label("Drawings: ", Label.RIGHT); 37: TextField drawings =
new TextField(); 38: Label yearsLabel = new Label("Years:
", Label.RIGHT); 39: TextField years = new TextField(); 40:
41: public void init() { 42:
setBackground(Color.lightGray); 43: GridLayout appletLayout
= new GridLayout(5, 1, 10, 10); 44:
setLayout(appletLayout); 45: 46: // Add listeners 47:
quickpick.addItemListener(this); 48:
personal.addItemListener(this); 49:
stop.addActionListener(this); 50:
play.addActionListener(this); 51:
reset.addActionListener(this); 52: 53: FlowLayout layout1 =
new FlowLayout(FlowLayout.CENTER, 10, 10); 54:
row1.setLayout(layout1); 55: row1.add(quickpick); 56:
row1.add(personal); 57: add(row1); 58: 59: GridLayout
layout2 = new GridLayout(2, 7, 10, 10); 60:
row2.setLayout(layout2); 61: row2.setLayout(layout2); 62:
row2.add(numbersLabel); 63: for (int i = 0; i < 6; i++)
{ 64: numbers[i] = new TextField(); 65:
row2.add(numbers[i]); 66: } 67: row2.add(winnersLabel); 68:
for (int i = 0; i < 6; i++) { 69: winners[i] = new
TextField(); 70: winners[i].setEditable(false); 71:
row2.add(winners[i]); 72: } 73: add(row2); 74: 75:
FlowLayout layout3 = new FlowLayout(FlowLayout.CENTER, 10,
10); 76: row3.setLayout(layout3); 77:
stop.setEnabled(false); 78: row3.add(stop); 79:
row3.add(play); 80: row3.add(reset); 81: add(row3); 82: 83:
GridLayout layout4 = new GridLayout(2, 3, 20, 10); 84:
row4.setLayout(layout4); 85: row4.add(got3Label); 86:
got3.setEditable(false); 87: row4.add(got3); 88:
row4.add(got4Label); 89: got4.setEditable(false); 90:
row4.add(got4); 91: row4.add(got5Label); 92:
got5.setEditable(false); 93: row4.add(got5); 94:
row4.add(got6Label); 95: got6.setEditable(false); 96:
row4.add(got6); 97: row4.add(drawingsLabel); 98:
drawings.setEditable(false); 99: row4.add(drawings); 100:
row4.add(yearsLabel); 101: years.setEditable(false); 102:
row4.add(years); 103: add(row4); 104: } 105: 106: public
void actionPerformed(ActionEvent event) { 107: String
command = event.getActionCommand(); 108: if (command ==
"Reset") 109: clearAllFields(); 110: if (command == "Play")
{ 111: playing = new Thread(this); 112: playing.start();
113: play.setEnabled(false); 114: stop.setEnabled(true);
115: reset.setEnabled(false); 116:
quickpick.setEnabled(false); 117:
personal.setEnabled(false); 118: } 119: if (command ==
"Stop") { 120: playing.stop(); 121: stop.setEnabled(false);
122: play.setEnabled(true); 123: reset.setEnabled(true);
124: quickpick.setEnabled(true); 125:
personal.setEnabled(true); 126: } 127: 128: } 129: 130:
public void itemStateChanged(ItemEvent event) { 131: String
command = (String) event.getItem(); 132: if (command ==
"Quick Pick") { 133: for (int i = 0; i < 6; i++) { 134: int
pick; 135: do { 136: pick = (int)Math.floor(Math.random() *
50 + 1); 137: } while (numberGone(pick, numbers, i)); 138:
numbers[i].setText("" + pick); 139: } 140: } else { 141:
for (int i = 0; i < 6; i++) 142: numbers[i].setText(null);
143: } 144: } 145: 146: void clearAllFields() { 147: for
(int i = 0; i < 6; i++) { 148: numbers[i].setText(null);
149: winners[i].setText(null); 150: } 151:
got3.setText(null); 152: got4.setText(null); 153:
got5.setText(null); 154: got6.setText(null); 155:
drawings.setText(null); 156: years.setText(null); 157: }
158: 159: void addOneToField(TextField field) { 160: int
num = Integer.parseInt("0" + field.getText()); 161: num++;
162: field.setText("" + num); 163: } 164: 165: boolean
numberGone(int num, TextField[] pastNums, int count) { 166:
for (int i = 0; i < count; i++) 167: if
(Integer.parseInt(pastNums[i].getText()) == num) 168:
return true; 169: return false; 170: } 171: 172: boolean
matchedOne(TextField win, TextField[] allPicks) { 173: for
(int i = 0; i < 6; i++) { 174: String winText =
win.getText(); 175: if
( winText.equals( allPicks[i].getText() ) ) 176: return
true; 177: } 178: return false; 179: } 180: 181: public
void run() { 182: while (true) { 183:
addOneToField(drawings); 184: int draw =
Integer.parseInt(drawings.getText()); 185: float numYears =
(float)draw / 104; 186: years.setText("" + numYears); 187:
188: int matches = 0; 189: for (int i = 0; i < 6; i++)
{ 190: int ball; 191: do { 192: ball =
(int)Math.floor(Math.random() * 50 + 1); 193: } while
(numberGone(ball, winners, i)); 194: winners[i].setText(""
+ ball); 195: if (matchedOne(winners[i], numbers)) 196:
matches++; 197: } 198: switch (matches) { 199: case 3: 200:
addOneToField(got3); 201: break; 202: case 4: 203:
addOneToField(got4); 204: break; 205: case 5: 206:
addOneToField(got5); 207: break; 208: case 6: 209:
addOneToField(got6); 210: stop.setEnabled(false); 211:
play.setEnabled(true); 212: playing.stop(); 213: } 215: }
216: } 1: import java.awt .*; 2: java.awt.event
importación .*; 3: 4: LottoMadness clase pública se
extiende java.applet.Applet 5: implementa ItemListener,
ActionListener, 6: Ejecutable {7: 8: jugar mensaje , 9: 10:
/ / establecer la fila 1 11: Panel de row1 nuevo Panel =
(); 12: CheckboxGroup opción = new CheckboxGroup (); 13:
QuickPick Checkbox = new Casilla ("Quick Pick", opción,
false); 14 : Casilla de verificación personal = new Casilla
("Personal", opción, true); 15: / / establecer la fila 2
16: Panel de row2 nuevo Panel = (); 17: numbersLabel
etiqueta = new Label ("Su recoge:", marca. DERECHA); 18:
TextField [] = new TextField números [6]; 19: winnersLabel
Label = new Label ("ganadores", Label.RIGHT); 20: TextField
[] = new TextField ganadores [6]; 21: / / establecer la
fila 3 22: Panel de row3 = Grupo nuevo (); 23: parada del
botón = new Button ("Stop"); 24: jugar botón = new Button
("Play"); 25: Botón de reset = new Button (" Reset ");
26: / / establecer la fila 4 27: Panel de row4 nuevo Panel
= (); 28: got3Label Label = new Label (" 3 de 6:
"Label.RIGHT); 29: TextField = new TextField got3 ( ); 30:
got4Label Label = new Label ("4 de 6:" Label.RIGHT); 31:
TextField got4 nueva TextField = (); 32: got5Label etiqueta
= new Label ("5 de 6:" Label.RIGHT ); 33: TextField =
TextField got5 nuevo (); 34: got6Label etiqueta = new Label
("6 de 6:" Label.RIGHT); 35: TextField = new TextField got6
(10); 36: drawingsLabel etiqueta = new Label ("Dibujos",
Label.RIGHT); 37: TextField = TextField dibujos nuevos ();
38: yearsLabel etiqueta = new Label ("Años", Label.RIGHT);
39 años TextField = new TextField () 40; : 41: public void
init () {42: setBackground (Color.lightGray); 43:
appletLayout GridLayout = new GridLayout (5, 1, 10, 10);
44: setLayout (appletLayout); 45: 46: / / Añadir los
oyentes 47: quickpick.addItemListener (este); 48:
personal.addItemListener (este); 49: stop.addActionListener
(este); 50: play.addActionListener (este); 51:
reset.addActionListener (este); 52: 53: FlowLayout layout1
= new FlowLayout (FlowLayout.CENTER, 10, 10); 54:
row1.setLayout (layout1); 55: row1.add (QuickPick); 56:
row1.add (personal); 57: añadir (row1); 58: 59: GridLayout
Layout2 nueva GridLayout = (2, 7, 10, 10); 60:
row2.setLayout (Layout2); 61: row2.setLayout (Layout2); 62:
row2.add (numbersLabel); 63: for (int i = 0; i <6; i + +)
{64: Los números de i] = new TextField [(); 65: row2.add
(números de [i]); 66:} 67: row2.add (winnersLabel); 68:
para ( int i = 0; i <6; i + +) {69: ganadores [i] = nuevo
TextField (); 70: ganadores [i]. setEditable (falso), 71
row2.add (ganadores [i]); 72: } 73: agregar (row2); 74: 75:
FlowLayout FlowLayout layout3 = nuevo (FlowLayout.CENTER,
10, 10); 76: row3.setLayout (layout3); 77: stop.setEnabled
(false); 78: row3.add (parada); 79: row3.add (obra
teatral); 80: row3.add (reset); 81: añadir (row3); 82: 83:
GridLayout layout4 = new GridLayout (2, 3, 20, 10); 84:
row4.setLayout (layout4); 85: row4.add (got3Label); 86:
got3.setEditable (false); 87: row4.add (got3); 88: row4.add
(got4Label); 89: got4.setEditable (falso ); 90: row4.add
(got4); 91: row4.add (got5Label); 92: got5.setEditable
(false); 93: row4.add (got5); 94: row4.add (got6Label); 95:
got6 . setEditable (false); 96: row4.add (got6); 97:
row4.add (drawingsLabel); 98: drawings.setEditable (false);
99: row4.add (dibujos); 100: row4.add (yearsLabel) ; 101:
years.setEditable (false); 102: row4.add (años); 103:
agregar (row4); 104:} 105:: 107: 106 public void
actionPerformed (ActionEvent evento) {String comando =
event.getActionCommand ( ); 108: if (comando == "Reset")
109: clearAllFields (); 110: if (comando == "Play") {111:
jugar = new Thread (this); 112: playing.start (); 113 :
play.setEnabled (false); 114: stop.setEnabled (true); 115:
reset.setEnabled (false); 116: quickpick.setEnabled
(false); 117: personal.setEnabled (false); 118:} 119: si
(comando == "Stop") {120: playing.stop (); 121:
stop.setEnabled (false); 122: play.setEnabled (true); 123:
reset.setEnabled (true); 124: quickpick.setEnabled ( true);
125: personal.setEnabled (true); 126:} 127: 128:} 129::
131: 130 public void (itemStateChanged ItemEvent evento)
{String comando = (String) event.getItem (); 132: si
( comando == "Quick Pick") {133: for (int i = 0; i <6; i +
+) {134: int selección; 135: do {136: elegir = (int)
Math.floor (Math.random () * 50 + 1); 137:} while
(numberGone (selección, números, i)); 138: números de [i].
setText ("" + pick); 139} 140:} else {141: for (int i = 0;
i <6; i + +) 142: números de [i]. setText (null); 143}
144:} 145:: 147: 146 vacío clearAllFields () {for (int i =
0; i <6; i + + ) {148: números de [i]. setText (null); 149
ganadores [i]. setText (null); 150} 151: got3.setText
(null); 152: got4.setText (null); 153: got5 . setText
(null); 154: got6.setText (null); 155: drawings.setText
(null); 156: years.setText (null); 157:} 158: 159:
addOneToField vacío (campo TextField) {160: int num =
Integer.parseInt ("0" + field.getText ()); 161: numero + +;
162: field.setText ("" + num); 163:} 164: 165: numberGone
booleano (int num, TextField [pastNums] , int count) {166:
for (int i = 0; i cuenta <; i + +) 167: si (pastNums [].
gettext () i (Integer.parseInt) == num) 168: return true;
169: return false ; 170:} 171: 172: matchedOne booleano
(TextField ganar, TextField [allPicks]) {173: for (int i =
0; i <6; i + +) {174: winText String = win.getText (); 175:
si (winText.equals (allPicks [i]). gettext ()) 176: return
true; 177:} 178: return false; 179:} 180:: 182 públicos:
181 void Run () {while (true) {183: addOneToField
(dibujos); 184: dibujar int = Integer.parseInt
(drawings.getText ()); 185: numYears flotante = (float)
dibujar / 104 y 186: years.setText ("" + numYears); 187:
188: int partidos = 0; 189: for (int i = 0; i <6; i + +)
{190: pelota int; 191: do {192: bola = (int) Math.floor
(Math.random () * 50 + 1) ; 193:} while (numberGone (bola,
los ganadores, i)); 194: ganadores [i]. setText ("+" bola);
195 if (matchedOne (ganadores [i], número de)) 196:
partidos + + 197; :} 198: interruptor (los partidos) {199:
Caso 3: 200: addOneToField (got3); 201: break; 202: Caso 4:
203: addOneToField (got4); 204: break; 205: caso 5: 206:
addOneToField ( got5); 207: break; 208: Caso 6: 209:
addOneToField (got6); 210: stop.setEnabled (false); 211:
play.setEnabled (true); 212: playing.stop (); 213:} 215: }
216:} 218:}

After saving the file, load the file into your word processor and make one change--the text
should be . Después de guardar el archivo LottoMadness.java, cargue el archivo
LottoGUI.html en su procesador de textos y hacer un cambio - el texto debe ser
LottoGUI.class LottoMadness.class. Save it under the new name . Guárdelo en el
marco del LottoMadness.html nuevo nombre. Compile the applet with the compiler tool
and then try out the applet by loading its Web page into the . Compilar el subprograma
LottoMadness con la herramienta del compilador javac y luego probar el applet de carga
de su página Web en el appletviewer.

Summary Resumen
Using the Abstract Windowing Toolkit and Java's event-handling features, you can create a
professional-looking program with a modest amount of programming. Usando el kit de
herramientas de ventana de Resumen y características de Java de control de eventos, puede
crear un programa de aspecto profesional con una modesta cantidad de programación.
Although the applet is longer than many of the examples you have worked on during the
last 20 hours, half of the program was comprised of statements to build the interface.
Aunque el applet LottoMadness es más largo que muchos de los ejemplos que han
trabajado durante las últimas 20 horas, la mitad del programa se compone de los estados
para construir la interfaz.

If you spend some time running the applet, you will become even more bitter and envious
about the good fortune of the people who win these six-number lottery drawings. Si usted
pasa algún tiempo en marcha el subprograma LottoMadness, que será aún más amarga y
envidiosos de la buena fortuna de las personas que ganan estos números de la lotería y seis
dibujos. The run of the program shown in Figure 20.1 indicates that you could blow 27
grand and the best 266 years of your life buying tickets, only to win a handful of 4-of-6 and
3-of-6 prizes. La ejecución del programa se muestra en la figura 20.1 indica que podría
volar 27 grandes y mejores los 266 años de su vida comprando entradas, sólo para ganar un
puñado de 4 de los 6 y 3 de los 6 premios. In comparison to those odds, the chance to make
Java programming skills pay off almost seems like a sure thing. En comparación con las
probabilidades, la posibilidad de que las aptitudes de programación Java pagar casi parece
una cosa segura.

Q&A Q & A
Q Is there a way to use different colors in an interface? Q ¿Hay una manera de utilizar
colores diferentes en una interfaz?

A You can use objects to change the appearance of each component in several ways. A
Usted puede utilizar objetos de colores para cambiar el aspecto de cada componente de
varias maneras. The method designates the background elements, and sets foreground
elements. El setBackground () designa el método de los elementos de fondo, y
setForeground () establece los elementos en primer plano. You must use these
methods with the components themselves. Debe utilizar estos métodos con los mismos
componentes. The method of the applet will not change the color of containers and
components within the applet. El setBackground () de la applet no va a cambiar el
color de los contenedores y componentes en el applet.

Q Do you need to do anything with the paint() or repaint() method to indicate that a text
field has been changed? Q ¿Es necesario hacer nada con la pintura () o pintar () para
indicar que un campo de texto se ha cambiado?

A After the method of a text component is used to change its value, nothing else needs to
be done. A Después del setText () de un componente de texto se utiliza para cambiar
su valor, nada más hay que hacer. The Abstract Windowing Toolkit handles the updating
that is necessary to show the new value. El resumen de ventanas Toolkit se encarga de la
actualización que es necesario para mostrar el nuevo valor.

Quiz Quiz
After the program has soured you on games of chance, play a game of skill by answering
the following questions. Después del programa LottoMadness le ha agriado en los juegos
de azar, jugar un juego de habilidad de responder a las siguientes preguntas.

Questions Preguntas

1. Why are action events called by that name? 1. ¿Por qué los eventos de acción llamado
por ese nombre?

(a) They occur in reaction to something else. (A) Se producen como reacción a otra cosa.
(b) They indicate that some kind of action should be taken in response. (B) Indican que
algún tipo de acción se debe tomar en respuesta.
(c) They honor cinematic adventurer Action Jackson. (C) Honran cine aventurero de acción
de Jackson.

2. What does signify as the argument to an method? 2. ¿Qué significa esto como
argumento para una addActionListener () método?

(a) "This" listener should be used when an event occurs. (A) "El presente" oyente debe ser
usado cuando se produce un evento.
(b) "This" event takes precedence over others. (B) "Este" evento tiene prioridad sobre los
demás.
(c) "This" class of objects will handle the events. (C) "Esta" clase de objetos se encargará
de los eventos.

3. Which component stores user input as integers? 3. ¿Qué tiendas de la entrada del
usuario componente como números enteros?
(a) (A) TextArea
(b) (B) TextField
(c) Neither does (C) Tampoco

Answers Respuestas

1. 1. b. b.

2. c. 2. C. If the name of another class were used as an argument instead of the


statement, that class would receive the events and be expected to handle them. Si el
nombre de otra clase se utiliza como un argumento en lugar de la declaración de esta,
esa clase que recibirá los eventos y se espera que ellos manejan.

3. c. and components store their values as text, so their values must be converted before
they can be used as integers, floating-point numbers, or other nontext values. 3. C.
componentes TextArea y TextField guardar sus valores en forma de texto, por lo que
sus valores deben ser convertidos antes de que puedan ser utilizados como números
enteros, números de punto flotante, o no son de texto de otros valores.

Activities Actividades
If the main event of this hour didn't provide enough action for your taste, interface with the
following activities: Si el evento principal de esta hora no proporcionó suficiente acción
para su gusto, la interfaz con las siguientes actividades:

 Add a text field to the applet that works in conjunction with a statement to slow down
the rate at which drawings are conducted. Agregar un campo de texto al applet
LottoMadness que trabaja en conjunto con un Thread.Sleep () para disminuir la
velocidad a la que los dibujos se llevan a cabo.
 Use the interface and related methods to make sure that users of enter valid numbers
from 1 to 50 for the drawings. Utilizar la interfaz TextListener y métodos relacionados
para asegurarse de que los usuarios de LottoMadness introducir números válido de 1 a
50 para los dibujos.

 21 horas
o Jugar juegos con Java
 Dados
 Organizador del Programa
 Crear una clase de matrices
 Configuración de los valores iniciales
 Tirar el dado
 Dibujo Die
 Figura 21.1.
 Figura 21.2.
 Listado de 21.1. El código fuente de Die.java.
 Prueba de la clase morir
 Listado de 21.2. El código fuente completo de TestDie.java.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 21 21 horas

Playing Games with Java Jugar juegos con Java

At this point, you have more than enough Java programming skills to be a danger to
yourself and others. En este punto, usted tiene más que suficientes conocimientos de
programación Java para ser un peligro para sí mismo y otros. You can write programs for
the World Wide Web and programs to run locally on your computer. Usted puede escribir
programas para la World Wide Web y los programas se ejecuten localmente en el equipo.
The next several hours will test your skills as you apply them to some practical examples of
programming. Las próximas horas pondrá a prueba sus habilidades a medida que los
aplican a algunos ejemplos prácticos de la programación.

The program you'll be writing during this hour and the next hour will serve two purposes.
El programa que va a estar escribiendo durante esta hora y la hora siguiente servir a dos
propósitos. First, it will give you a chance to create an object and use it in another program.
En primer lugar, le dará la oportunidad de crear un objeto y usarlo en otro programa.
Second, you'll be building gambling skills that will hold you in good stead at the next illicit
gambling den you visit. En segundo lugar, usted será la construcción de habilidades de
juego que le mantenga en una buena posición en el garito junto ilícitos que visita. During
this hour, you'll create a object and test it out with a simple Java program. Durante esta
hora, va a crear un objeto de morir y lo prueba con un simple programa Java. Once it
works, you'll be using the object in a applet during Hour 22, "Writing a Game for the
Web." Una vez que funciona, que va a utilizar el objeto de morir en un applet dados
durante 22 horas, "Escribir un juego para la Web."

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 How to play craps Cómo jugar a los dados


 Creating an object to handle a task Creación de un objeto para manejar una tarea
 Generating random numbers for dice rolls La generación de números aleatorios para los
rodillos de los dados
 Drawing dice using polygons dados de dibujo utilizando polígonos
 Determining what to display using - blocks La determinación de lo que desea mostrar
utilizando si - entonces bloques
 Using methods of the class Utilizando métodos de la clase Math
 Storing values in the variables of a class Almacenamiento de los valores en las variables de
una clase
 Using arguments with methods Uso de argumentos con los métodos
 Setting up variables in a constructor method Configuración de las variables en un método
constructor

Craps Dados
Everyone has different recollections of childhood, but who doesn't have memories of
skipping school, staying out all night, and blowing all your lunch money at the craps table
with some of the neighborhood drug dealers? Todo el mundo tiene diferentes recuerdos de
la infancia, pero que no tiene recuerdos de faltar a la escuela, permaneciendo toda la noche,
y soplando todo el dinero del almuerzo en la mesa de dados con algunos de los
distribuidores de drogas de vecindad? Most of us don't have these memories, unfortunately,
because of restrictive parents and their crazy notion that a good education and sleep were
important for their kids. La mayoría de nosotros no tenemos esos recuerdos, por desgracia,
a causa de los padres restrictivas y su loca idea de que una buena educación y el sueño son
importantes para sus hijos.

Luckily, you can simulate a little of that gambling den experience by playing a craps game
on your computer. Por suerte, se puede simular un poco de esa experiencia garito jugando
un juego de dados en el equipo. Craps, in case you're particularly sheltered, is a game
involving two six-sided dice. Dados, en caso de que esté especialmente protegido, es un
juego con dos dados de seis caras. The goal is to roll a winning number with the dice before
you roll a losing number. El objetivo es sacar un número ganador con los dados antes de
rodar una serie de perder. Craps has some complicated rules for gambling, but the program
you'll write during this hour will focus on dice rolling, winning numbers, and losing
numbers. Dados tiene algunas reglas complicadas para el juego, pero el programa que voy a
escribir durante esta hora se centrará en tirar dados, números ganadores, y pierde. The
number of winning rolls and losing rolls will be totaled up as you play, giving you an idea
of how often a craps player rolls a winning pair of dice. El número de rollos de ganar y de
perder los rollos se sumaron a medida que juegas, que le da una idea de cuántas veces un
jugador de dados tira un par de ganadores de los dados.

When a player rolls the dice for the first time, any combination of the two dice that adds up
to 7 or 11 is a winner. Cuando un jugador tira los dados por primera vez, cualquier
combinación de los dos dados que se suma a 7 o 11 es un ganador. Any dice total that
equals 2, 3, or 12 is an immediate loser and is called craps, as in "Oh, crap, I just lost the
money I needed for liposuction surgery!" Cualquier total de dados que es igual a 2, 3, o 12
es un perdedor inmediato y se llama juego de dados, como en "Oh, mierda, me acaba de
perder el dinero que necesitaba para la cirugía de liposucción!" If the first roll is not an
immediate winner or a loser, the total of the dice becomes known as the point. Si el primer
rollo no es un ganador o un perdedor inmediato, el total de los dados se conoce como el
punto. For all successive rolls, the player will win a game if the point is rolled again. Para
todas las tiradas sucesivas, el jugador va a ganar un juego si el punto se rueda otra vez.
However, if a 7 is rolled before the point is rolled, the player craps out. Sin embargo, si se
lanza un 7 antes del punto se rueda, el jugador de dados a cabo.

The following is a sample game rolled by motion picture star Pia Zadora: El siguiente es un
juego de la muestra de cine rodado por estrellas Pia Zadora:

1. Pia rolls a 5 and a 6, adding up to 11. 1. Pia saca un 5 y un 6, que suman 11. She wins the
game instantly. Ella gana la partida al instante.

That example wasn't long enough for illustrative purposes, so here's another game from Ms.
Zadora: Ese ejemplo no fue lo suficientemente largo para fines ilustrativos, así que aquí
tiene otro juego de la Sra. Zadora:

1. Pia rolls a 6 and a 2. 1. Pia saca un 6 y un 2. This roll makes 8 the point. Este rollo hace 8
el punto. On all successive rolls, an 8 will win, and a 7 will lose. En todas las tiradas
sucesivas, un 8 va a ganar, y un 7 perderá.

2. Pia rolls a 4 and a 2, adding up to 6. 2. Pia saca un 4 y un 2, que suman 6. She must roll
again. Se debe tirar de nuevo.

3. Pia rolls snake eyes--2. 3. Pia rollos de ojos de serpiente - 2. She didn't roll the point (8),
so she has to roll again. Ella no hizo rodar el punto (8), por lo que tiene que tirar de nuevo.

4. Pia rolls a 3 and 4 (for a total of 7), crapping out. 4. Pia saca un 3 y 4 (para un total de 7),
cagando a cabo.

Now that you know how craps works, it's time to teach the game to your computer. Ahora
que sabes cómo funciona el juego de dados, es el momento de enseñar el juego en tu
ordenador. When you're done, you'll be writing a applet that you can put on a World Wide
Web page. Cuando haya terminado, se le escribe un applet dados que usted puede poner en
una página del World Wide Web.

Organizing the Program Organizador del Programa


Before you tackle any programming project, spend some time thinking about how it should
be implemented. Antes de abordar cualquier proyecto de programación, pasar algún tiempo
pensando en cómo debe ser implementado. Planning ahead can prevent you from doing
work in the program that has to be redone later because it wasn't done correctly. Planear
con anticipación puede evitar que usted está trabajando en el programa que tiene que
hacerse de nuevo más tarde porque no se ha realizado correctamente. It also can make the
finished program easier to understand and easier to maintain later on. También puede hacer
que el programa termine más fácil de entender y fácil de mantener después.

If you're particularly organized, you might want to create a flowchart that illustrates the
way the program will function. Si usted está organizada en particular, es posible que desee
crear un diagrama de flujo que ilustra la forma en que el programa funcionará. Flowcharts
are an effective way to demonstrate the logic a computer should follow as it handles a
program. Diagramas de flujo son una manera efectiva de demostrar la lógica de un equipo
debe seguir ya que maneja un programa. Even if you don't create flowcharts, you should
make a list of the things your program must do. Incluso si usted no crear diagramas de
flujo, debe hacer una lista de las cosas que su programa tiene que hacer. Think about each
task that must be handled for the program to work, and don't worry about putting them in
any order. Piense en cada tarea que debe ser manejado por el programa de trabajo, y no
preocuparse por su puesta en cualquier orden.

For example, the applet includes the following list of tasks: Por ejemplo, el applet dados
incluye la siguiente lista de tareas:

 Roll two dice and add them up Lanza dos dados y sumarlos
 Figure out if the dice total is a winner or a loser Averiguar si el total de los dados es un
ganador o un perdedor
 Draw the dice on the screen Dibuja los dados en la pantalla
 Keep track of the point value if the first roll doesn't win or lose No pierda de vista el valor
de puntos si la primera tirada no gana o pierde
 Count the number of wins and losses Cuente el número de victorias y derrotas
 Create a way for the player to roll the dice Crear una forma para que el jugador tira los
dados

As you can see, almost all aspects of the applet will involve the dice. Como puede ver, casi
todos los aspectos del applet dados implicará los dados. During Hour 10, "Creating Your
First Object," you saw how a computer program can be thought of as a group of objects that
work together to accomplish a task. Durante la hora 10, "Creación de su primer objeto," vio
cómo un programa de ordenador puede ser considerado como un grupo de objetos que
trabajan juntos para realizar una tarea. One way to conceptualize the program is to create
an object that represents a six-sided die. Una forma de conceptualizar el programa de los
dados es crear un objeto que representa un dado de seis caras. If you can create a class that
can roll itself, draw itself, and keep track of its own value, most of the work of a applet
will be done. Si usted puede crear una clase que puede morir en sí rollo, dibujarse a sí
misma y realizar un seguimiento de su propio valor, la mayor parte de la obra de un applet
dados se llevará a cabo. An advantage to creating a separate class of objects is that you can
use this class in any program you write that involves dice. Una ventaja de la creación de un
separado Muere clase de objetos es que se puede utilizar esta clase en cualquier programa
que escriba y que consiste en dados. The only things left for the applet to do are to create
two objects, ask them to roll themselves, take user input, and keep score. Lo único que
queda para el applet que hacer es crear dos matrices objetos, pídales que se despliegue,
tomar la entrada del usuario, y llevar la cuenta.

Creating a Die Class Crear una clase de matrices


The class of objects that you will create must handle the following tasks: La suerte de
clase de objetos que va a crear debe manejar las siguientes tareas:

 Set up an initial value for itself when it is created Establecer un valor inicial para sí mismo
cuando se crea
 Roll itself Roll se
 Keep track of its own value Lleve un registro de su propio valor
 Draw itself Dibujar en sí

Using your word processor, create a new file named . Utilizando el procesador de textos,
crear un nuevo archivo llamado Die.java. Each section of the class will be described as
you enter the text. Cada sector de la clase matrices se describe como entrar en el texto.
Begin with the following line: Empiece con la siguiente línea:

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

This line makes Java's Abstract Windowing Toolkit classes available for use in the class.
Esta línea hace que la ventana de clases de Java Resumen Herramientas disponibles para su
uso en la matriz de clases.

Throughout this section, is described as a class of objects rather than as a program. A lo


largo de esta sección, matrices se describe como una clase de objetos y no como un
programa. Class, object, and program are largely synonymous in Java, but it's helpful to
think of them in the following way: A program is a set of computer instructions that handle
a task. Clase, objeto, y el programa son en gran parte sinónimo en Java, pero es útil pensar
en ellos de la siguiente manera: Un programa es un conjunto de instrucciones de
computadora que se encargan de una tarea. Objects are used by a program to accomplish its
work. Los objetos son utilizados por un programa para llevar a cabo su labor. A class is the
template that determines how an object is created and what it can do. Una clase es la
plantilla que determina cómo se crea un objeto y lo que puede hacer.

After adding a blank line, enter the following statements: Después de agregar una línea en
blanco, escriba las siguientes declaraciones:

public class Die { public class matrices {


public int value; int valor público;
The first line begins the class and indicates that the name of the source file should be .
does not use the statement along with , so it does not inherit any capabilities from other
objects. La primera línea comienza la clase de matrices e indica que el nombre del archivo
de origen debe ser Die.java. Morir no utiliza la declaración se extiende a lo largo de la
clase pública, por lo que no hereda ninguna capacidad de otros objetos. It's a unique
class of objects. Es una clase única de objetos.

The second line creates an integer variable called . La segunda línea crea una variable
entera llamada valor. This variable will be used to store the value of the die after it is
rolled. Esta variable se utiliza para almacenar el valor de la matriz después de que se
enrolla. Because the object is a six-sided die, the variable will store a value ranging from 1
to 6. Dado que el objeto es un dado de seis caras, la variable almacenará un valor que va
desde 1 a 6.

Setting Up Initial Values Configuración de los valores iniciales

The first task that the object must handle is to set up any variables that are needed when
the object is created. La primera tarea que el objeto Muere debe manejar es la creación de
las variables que son necesarios cuando se crea el objeto. Insert a blank line after and then
enter the following: Insertar una línea en blanco después de valor int pública, y luego
escriba lo siguiente:

public Die() { pública morir () {


value = 0; valor = 0;
} }

This method is called a constructor because it is called automatically whenever another


program creates a object. Este método se llama un constructor, ya que se llama
automáticamente cada vez que otro programa crea un objeto de morir. The method does
only one thing: It sets the variable equal to 0. El método no sólo una cosa: Se establece la
variable de valor igual a 0.

Rolling the Die Tirar el dado

The next step is to write a method that handles the rolling of the die. El siguiente paso es
escribir un método que controla el balanceo de la matriz. Insert a blank line at the bottom of
your file and then enter the following: Insertar una línea en blanco en la parte inferior de su
archivo y luego escriba lo siguiente:

public void rollValue(int maxValue) { rollValue public


void (maxValue int) {
double tempValue = Math.random() * maxValue; tempValue
doble = Math.random () * maxValue;
value = (int) Math.floor(tempValue) + 1; valor = (int)
Math.floor (tempValue) + 1;
} }

This method takes one argument, an integer called . Este método toma un argumento, una
llamada maxValue entero. This value will be used to indicate the number of sides on the
die. Este valor se utiliza para indicar el número de lados en el dado. The program you're
writing, a applet, always uses six-sided dice. El programa que estás escribiendo, un applet
de Dados, siempre usa dados de seis caras. However, by using an argument to enable other
types of dice to be used, you make the class of objects more useful with other projects you
might undertake. Sin embargo, utilizando un argumento para permitir que otros tipos de
dados que se utilizarán, a tomar las matrices de clase de los objetos más útiles con otros
proyectos que podrían llevar a cabo.

Two methods of the class are used in the method: and . Dos métodos de la clase de
matemáticas se utilizan en la rollValue () método: Math.floor () y Math.random
(). The class is one of the standard class libraries that are part of the Java language, and it
has several functions to handle mathematic operations. generates a random number ranging
from 0.0 to 1.0. La clase de matemáticas es una de las bibliotecas de clases estándar que
son parte del lenguaje Java, y tiene varias funciones para manejar operaciones matemáticas.
Math.random () genera un número aleatorio que van desde 0.0 a 1.0. These numbers are
long floating-point numbers such as the following: Estos números son largos números de
punto flotante, tales como las siguientes:

0.7359693177023363 0.7359693177023363
0.5431408045289557 0.5431408045289557
0.03239819056314541 0.03239819056314541

When you multiply by a value, you create a random number ranging from 0 to within .001
of that value. Si se multiplica Math.random () por un valor, se crea un número aleatorio
entre 0 y en 0.001 de ese valor. For instance, multiplying by 6 generates a number ranging
from 0.0 to almost 6.0. Por ejemplo, multiplicar Math.random () por 6 genera un número
que va de 0,0 a casi 6,0. Adding 1 to this, as the method does, generates a random number
from 1.0 to almost 7.0. Agregar 1 a la presente, como el rollValue () método no genera
un número aleatorio de 1,0 a casi 7,0.

But just try rolling a six-sided die until you come up with 2.71570402264! Pero sólo
intento lanzar un dado de seis caras hasta llegar a 2,71570402264! To create a dice-like
effect, the number must be rounded down to an integer. Para crear un efecto similar a los
dados, el número debe ser redondeado a un entero. The method does exactly this. El
Math.floor () de hace exactamente esto. By using both and , the method generates a
random number from 1 to and stores the number in the variable. Al utilizar tanto en el
piso () y aleatorio (), el rollValue () método genera un número aleatorio entre 1 y
maxValue y almacena el número en la variable de valor.

Drawing the Die Dibujo Die

The last thing the class of objects needs to do is draw the die. La última cosa que el morir
clase de objetos tiene que hacer es señalar a la muerte. Instead of displaying the value of the
die as text, you can make your program more appealing by showing the die on-screen. En
lugar de mostrar el valor de la matriz en forma de texto, usted puede hacer su programa más
atractivo, mostrando el dado en la pantalla. Java has several different polygon-drawing
methods that you can use to depict a die. Java tiene varios métodos de dibujo de polígonos
que se pueden utilizar para describir un dado. The final look of a die depends on its value.
El aspecto final de un dado depende de su valor. Figure 21.1 shows six dice with values
that range from 1 to 6. La figura 21.1 muestra seis dados con valores que van de 1 a 6.

Figura 21.1. The possible values on a six-sided die. Los valores posibles en un dado de
seis caras.

You can show dice in a computer program by drawing a rectangle with rounded corners
and circles for each number on a side. Puede mostrar el resultado de los dados en un
programa de ordenador por dibujar un rectángulo con esquinas redondeadas y círculos para
cada número en un lado. One way to handle this procedure in a Java program would be to
use a - block with six different sets of drawing statements. Una manera de manejar este
procedimiento en un programa Java sería utilizar un interruptor - bloque case con seis
diferentes conjuntos de declaraciones de dibujo. One dot could be drawn for a 1, two dots
could depict a 2, and so on. Un punto podría ser elaborado por un 1, dos puntos pueden
representar un 2, y así sucesivamente. However, this solution involves a lot of redundant
statements because many of the faces on a six-sided die contain the same dots. Sin
embargo, esta solución implica una gran cantidad de declaraciones redundantes, porque
muchas de las caras en un dado de seis caras contienen los mismos puntos. As you can see
in Figure 21.1, values 2 through 6 all have dots in the upper-left corner and lower-right
corner. Como se puede ver en la Figura 21.1, los valores de 2 a 6 tienen puntos en la
esquina superior izquierda y la esquina inferior derecha. Using and would require the
same statements to be repeated five times for these dots. Usando el interruptor y el
caso se requieren las mismas declaraciones que se repite cinco veces para estos puntos.
Instead of repeating the same statements in several places, you can take a different
approach. En lugar de repetir las mismas declaraciones en varios lugares, se puede tomar un
enfoque diferente. Figure 21.2 shows each dot that might be seen on a die and the values
that are associated with the dot. Figura 21.2 muestra cada punto que pueda ser visto en un
dado y los valores que se asocian con el punto. You can use this information to draw a die
more simply. Usted puede utilizar esta información para elaborar una matriz más sencilla.

Listing 21.1 shows the full source code of the file . Listado de 21.1 muestra el código
fuente completo del archivo Die.java. All of the statements you have entered up to this
point should look like Lines 1-13. Todas las declaraciones que ha ingresado hasta este
punto debe ser similar a las líneas 1-13. Go to the bottom of your file and insert Lines 14-
37 of Listing 21.1. Ir a la parte inferior de su archivo e insertar las líneas 14 a 37 del listado
21.1. Save the file when you're done. Guarde el archivo cuando haya terminado.

Figura 21.2. Matching the dots to the values associated with them. Coincidencia de los
puntos para los valores asociados con ellos.

Listing 21.1. Listado de 21.1. The source code of Die.java. El código fuente de Die.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class Die { 3: public class matrices {
4: public int value; 4: int valor público;
5: 5:
6: public Die() { 6: Muere pública () {
7: value = 0; 7: valor = 0;
8: } 8:}
9: 9:
10: public void rollValue(int maxValue) { 10: public void
rollValue (maxValue int) {
11: double tempValue = Math.random() * maxValue; 11:
tempValue doble = Math.random () * maxValue;
12: value = (int) Math.floor( tempValue ) + 1; 12: valor =
(int) Math.floor (tempValue) + 1;
13: } 13:}
14: 14:
15: public void drawDie(Graphics screen, int x, int y) {
15: public void drawDie (pantalla de gráficos, int x, int
y) {
16: screen.setColor(Color.red); 16: screen.setColor
(Color.Red);
17: screen.fillRoundRect(x, y, 100, 100, 20, 20); 17:
screen.fillRoundRect (x, y, 100, 100, 20, 20);
18: screen.setColor(Color.black); 18: screen.setColor
(Color.Black);
19: screen.drawRoundRect(x, y, 100, 100, 20, 20); 19:
screen.drawRoundRect (x, y, 100, 100, 20, 20);
20: screen.setColor(Color.white); 20: screen.setColor
(Color.white);
21: if (value > 1) { 21: if (valor> 1) {
22: screen.fillOval(x+5, y+5, 20, 20); 22: screen.fillOval
(x + 5, y 5, 20, 20);
23: screen.fillOval(x+75, y+75, 20, 20); 23:
screen.fillOval (x 75, y 75, 20, 20);
24: } 24:}
25: if (value > 3) { 25: if (valor> 3) {
26: screen.fillOval(x+75, y+5, 20, 20); 26:
screen.fillOval (x 75, y 5, 20, 20);
27: screen.fillOval(x+5, y+75, 20, 20); 27:
screen.fillOval (x + 5, y 75, 20, 20);
28: } 28:}
29: if (value == 6) { 29: if (valor == 6) {
30: screen.fillOval(x+5, y+40, 20, 20); 30:
screen.fillOval (x + 5, y 40, 20, 20);
31: screen.fillOval(x+75, y+40, 20, 20); 31:
screen.fillOval (x 75, y 40, 20, 20);
32: } 32:}
33: if (value % 2 == 1) { 33: if (valor% 2 == 1) {
34: screen.fillOval(x+40, y+40, 20, 20); 34:
screen.fillOval (x 40, y 40, 20, 20);
35: } 35:}
36: } 36:}
The method takes three arguments: 37:} El drawDie () toma
tres argumentos:

 A object indicates where all graphics operations should be displayed. Un objeto Graphics
indica que todas las operaciones gráficas se debe mostrar. In the program you'll be
writing, all drawing will take place on the applet's main window. En el programa de los
dados se le escritura, todos los dibujos se llevará a cabo en la ventana principal del applet.
 The two integers ( and ) determine the x and y coordinates where the die should be
drawn. Los dos números enteros (x, y) determinar las coordenadas X e Y en el dado
debe ser elaborado.

The following things are taking place in the method: Los siguientes factores están teniendo
lugar en el drawDie () método:

 Line 16 sets the current color to red using the variable of the class. Línea 16 establece el
color actual a rojo con la variable de color rojo de la clase Color. All drawing
methods that are used after this statement will appear in red until the current color is
changed again. Todos los métodos de dibujo que se utilizan después de esta declaración
aparecerá en rojo hasta que el color actual ha cambiado de nuevo.
 Line 17 draws a filled rectangle with rounded corners, so a red box appears on-screen that
looks like a die without any numbers on it. La línea 17 se dibuja un rectángulo lleno de
esquinas redondeadas, por lo que aparece un cuadro rojo en la pantalla que se ve como
un dado sin ningún tipo de números. The first two arguments to are the x and y
coordinates of the rectangle. Los dos primeros argumentos para fillRoundRect son las
coordenadas X e Y del rectángulo. These arguments use the same x and y values that were
sent to the method in Line 14. Estos argumentos se utilizan los mismos valores X e Y que
se enviaron a la drawDie () en la línea 14. The next two arguments, , designate the
height and width of the rectangle in pixels. Los siguientes dos argumentos, 100, 100,
que designe a la altura y la anchura del rectángulo en píxeles. The final two arguments, ,
determine how rounded the rectangle's corners should appear. Los dos últimos
argumentos, 20, 20, determinar la forma de rectángulo redondeado de las esquinas
deben aparecer. The higher the number, the more rounded the corners appear to be.
Cuanto mayor sea el número, más redondeado las esquinas parecen ser.
 Line 18 sets the current color to black. La línea 18 establece el color actual negro.
 Line 19 draws an unfilled rectangle with rounded corners using the same arguments as the
red rectangle that already has been drawn. Línea 19 dibuja un rectángulo sin relleno con
las esquinas redondeadas utilizando los mismos argumentos que el rectángulo rojo que ya
se ha elaborado. This line creates a black outline around the red die. Esta línea crea un
contorno negro alrededor de la muerte roja.
 Line 20 sets the current color to white. La línea 20 establece el color actual con el blanco.
 Lines 21-35 draw white circles on the die using the method. Líneas 21-35 dibujar círculos
blancos en el dado con el fillOval () método. Which circles are drawn depends on the
variable, which keeps track of the die's value. Que se dibujan círculos depende de la
variable valor, que realiza un seguimiento de morir de valor. The method has four
arguments. El fillOval () método tiene cuatro argumentos. The first two represent
the x and y coordinates of the oval, and the last two represent the height and width of the
oval. Los dos primeros representan la coordenadas x e y del óvalo, y los dos últimos
representan la altura y la anchura del óvalo. Because the height and width are equal in
these statements ( ), the ovals are circles. Debido a la altura y anchura son iguales en
estos estados (20, 20), los óvalos son círculos.
 Lines 21-24 are handled only if the variable is greater than one. Líneas 21-24 se manejan
sólo si la variable valor es mayor que uno. They draw circles in the upper-left and lower-
right corners of the die. Dibujan círculos en las esquinas superior izquierda e inferior
derecha de la matriz. On a six-sided die, all numbers from 2 upward have circles in these
corners. En un dado de seis caras, todos los números del 2 al alza tienen círculos en estas
esquinas.
 Lines 25-28 are handled only if the variable is greater than 3. Líneas 25 a 28 se tratan sólo
si la variable valor es mayor que 3. They draw circles in the upper-right and lower-left
corners of the die. Dibujan círculos en las esquinas superior derecha e inferior izquierda de
la matriz.
 Lines 29-32 are handled only if equals 6. Líneas 29 a 32 se tratan sólo si el valor es igual
a 6. They draw circles in the middle of the left side and the middle of the right side of the
die. Dibujan círculos en el centro del lado izquierdo y el centro de la parte derecha de la
matriz.
 Lines 33-35 take care of the last circle that might be found on a die--the one in the center.
Líneas 33-35 cuidar el último círculo que se pueden encontrar en un dado - el que está en
el centro. This circle is present in the numbers 1, 3, and 5. Este círculo está presente en los
números 1, 3 y 5. All of these are odd numbers. Todos estos son números impares.
Because the modulus operator produces the remainder of a division operation, you can
take advantage of the fact that odd numbers divided by 2 have a remainder of 1, and even
numbers have no remainder. Debido a que el operador módulo% produce el resto de una
operación de división, puede aprovechar el hecho de que los números impares dividido
por 2 tiene un resto de 1, e incluso los números no tienen el resto. The expression only
equals 1 when is an odd number. El% de valor de la expresión 2 sólo es igual a 1
cuando el valor es un número impar. Lines 33-35 draw a circle in the center of the die for
odd-numbered die values. Líneas 33-35 dibujar un círculo en el centro de la matriz de los
valores impares mueren.
 Line 36 marks the end of the method, and Line 37 marks the end of the class. Línea 36
marca el final de la drawDie () método, y Línea 37 marca el final de la clase Die.

Save the file, using the name , and compile it. Guarde el archivo con el nombre de
Die.java, y compilarlo. Once it compiles successfully, you will have a class of objects
that can be used in any program where you want to use six-sided dice. Una vez que se
compila correctamente, usted tendrá un dado clase de objetos que se pueden utilizar en
cualquier programa en el que desea utilizar dados de seis caras.

Testing the Die Class Prueba de la clase morir


The class of objects that you have created isn't intended to function as a stand-alone
program. La clase de matrices de objetos que ha creado no tiene la intención de funcionar
como un programa stand-alone. If you tried to run it with the tool, it would result in an
error because there is no statement in the class. Si has intentado correr con la herramienta
Java, que se traduciría en un error porque no hay principal () en la clase Die. To try
out your new class, you need to use it inside another Java program. Para probar su nueva
clase, que hay que usarla dentro de otro programa Java. You can do this in the same way
you used classes such as , , and in your class. Usted puede hacer esto en la misma forma
que utiliza clases como matemáticas, gráficos y color en la clase Die. Create a new
file with your word processor and call it . Crear un nuevo archivo con su procesador de
textos y lo llaman TestDie.java. Enter the text of Listing 21.2 and save the file.
Introduzca el texto del listado 21.2 y guardar el archivo.

Listing 21.2. Listado de 21.2. The full source code of TestDie.java. El código fuente
completo de TestDie.java.
1: class TestDie { 2: public static void main(String[]
arguments) { 3: Die firstDie = new Die(); 4: Die secondDie
= new Die(); 5: firstDie.rollValue(6); 6:
secondDie.rollValue(6); 7: System.out.println("The first
die rolled a " + firstDie.value); 8:
System.out.println("The second die rolled a " +
secondDie.value); 9: } 1: clase TestDie {2: public static
void main (String [argumentos]) {3: Die firstDie = new
morir () 4: Die secondDie = new morir (); 5:
firstDie.rollValue (6); 6: secondDie . rollValue (6), 7:
System.out.println ("El primer dado rodar una" +
firstDie.value); 8: System.out.println ("El segundo dado
rodar una" + secondDie.value); 9: } 10:}

This program creates two dice called and , rolls each of them using the method, and
displays the value stored in the variable of each object. Este programa crea dos dados
llamado firstDie y secondDie, rollos de cada uno de ellos con el rollValue () método,
y muestra el valor almacenado en la variable de valor de cada objeto morir. The
argument of is used with the method in Lines 5 and 6. El argumento de 6 se utiliza con el
rollValue () en las líneas 5 y 6. This argument causes a dice roll ranging from 1 to 6 to
occur, and the result is stored in . Este argumento provoca una tirada de dados de 1 a 6 a
ocurrir, y el resultado se almacena en el valor.

Compile and run it from the command line with the tool. Compilar TestDie.java y
ejecutarlo desde la línea de comandos con la herramienta Java. The output should
resemble the following: El resultado debería parecerse a lo siguiente:

The first die rolled a 2 El primer dado laminado de 2


The second die rolled a 5 El segundo dado laminados a 5

Run it several times to see that the rolls of the dice are random. Ejecutar varias veces para
ver que los rodillos de los dados son al azar.

As with most programming languages, Java does not generate completely random numbers.
Al igual que con muchos lenguajes de programación, Java no genera un número
completamente al azar. However, the results are random enough for most uses. Sin
embargo, los resultados son aleatorios suficiente para la mayoría de usos. One use that the
class would not be sufficient for is encryption. Uno de los usos que la clase al azar no
sería suficiente para que es el cifrado. Java 1.1 introduces a new subclass of called . Java
1.1 introduce una nueva subclase de Random llamado SecureRandom. This class can be
used in Java programs that encrypt information so that it cannot be viewed without being
decrypted first. Esta clase se puede utilizar en los programas de Java que encriptar la
información para que no se pueden ver sin ser descifrados primero.
Summary Resumen
This hour provided some practical experience with the object-oriented approach of the Java
language. Esta hora siempre algo de experiencia práctica con el enfoque orientado a objetos
del lenguaje Java. The class of objects that you created simulates the behavior of a type of
real-world object: a six-sided die. La suerte de clase de objetos que ha creado simula el
comportamiento de un tipo de objeto del mundo real: un dado de seis caras. Object-oriented
programming requires more initial effort than some other approaches, but it has several
advantages: Programación orientada a objetos requiere más esfuerzo inicial que algunos
otros enfoques, pero tiene varias ventajas:

 The structure of the program is more familiar because objects share features such as
constructor methods and class variables. La estructura del programa es más familiar, ya
compartir objetos de características tales como los métodos de constructor y variables de
clase.
 The program is self-contained, so you can understand what it does without looking at any
other programs. El programa es en sí misma, para que pueda entender lo que hace sin
mirar a ningún otro programa.
 The program can be instantly reused with other programs. El programa puede ser
inmediatamente utilizado con otros programas.

You now have the class of objects to use whenever a die needs to be used in a program.
Ahora tiene la Morir clase de objetos a utilizar cada vez que un dado tiene que ser utilizado
en un programa. You'll be using it in a applet in the coming hour. Usted estará usando en
un applet dados en la hora siguiente.

Q&A Q & A
Q Does the Craps applet require the use of a class of objects to represent the dice? Q ¿El
applet dados requieren el uso de una clase de objetos para representar a los dados?

A It's not a requirement--you could combine all the dice-related tasks and the
scorekeeping tasks into the same Java program. Un No es un requisito - que podría
combinar todas las tareas relacionadas con los dados y las tareas registro de resultados en
el mismo programa Java. If you look at the source code of applets that are available on the
World Wide Web, you'll see many that handle all of their functionality within a single
program. Si nos fijamos en el código fuente de los applets que están disponibles en la
World Wide Web, puedes encontrar muchos que se ocupan de todas sus funcionalidades
en un solo programa. However, this type of structure doesn't take advantage of the
benefits of object-oriented programming, and the program is harder to understand,
harder to reuse elsewhere, and more prone to bugs. Sin embargo, este tipo de estructura
no se aprovecha de los beneficios de la programación orientada a objetos, y el programa
es más difícil de entender, difícil de reutilizar en otros lugares, y más propenso a errores.

Q Does the public statement in front of a variable declaration mean that the variable can
be modified from other Java programs? Q ¿La declaración pública frente a una
declaración de variable significa que la variable puede ser modificado a partir de otros
programas de Java?
A Yes. R Sí. As you'll see in the applet in the next hour, you can change the value of
variables in other objects. Como podrá ver en el applet dados en la siguiente hora, puede
cambiar el valor de las variables públicas en otros objetos. If you create a object with
the name , you can set its variable with a statement such as the following: Si crea un
objeto con el morir firstDie nombre, puede establecer su valor variable con una
declaración como la siguiente:

firstDie.value = 0; firstDie.value = 0;
Q Can you have more than one constructor method in a class of objects? Q ¿Se puede
tener más de un método constructor en una clase de objetos?

A You can have more than one constructor method if they have different argument lists
within their parentheses. A Usted puede tener más de un método constructor si tienen
argumentos diferentes listas dentro de su paréntesis. One constructor could have no
arguments, as in , and another permitted constructor could be . Un constructor no podía
tener argumentos, como en el público morir (), y permite a otro constructor puede
ser público Die (maxValue int). One would be used when is used in a program
without any arguments, and the other would be used when is used with a single integer
as an argument. Se podría utilizar cuando morir () se utiliza en un programa sin ningún
argumento, y el otro se utiliza cuando morir () se utiliza con un solo número entero
como argumento.

Q Where can I find out the full list of classes that I can use in my Java programs and the
public methods that can be used with these classes? Q ¿Dónde puedo encontrar la lista
completa de clases que puedo usar en mis programas de Java y los métodos públicos
que se pueden utilizar con estas clases?

A The Java Developer's Kit includes a large number of Web pages that document all classes
that are standard parts of the Java programming language. El Java Developer Kit A incluye
un gran número de páginas Web que el documento todas las clases que son piezas
estándar del lenguaje de programación Java. You also can view these pages at the JavaSoft
Web site with any Web browser. También puede ver estas páginas en el sitio Web de
JavaSoft con cualquier navegador Web. Visit the following page: Visita la siguiente página:

http://www.javasoft.com/products/JDK/1.1/docs/
Q What colors can be used in conjunction with the setColor() method? Q ¿Qué colores se
puede utilizar en conjunto con el setColor () método?

A In addition to , , and , you can use the following variables as an argument to : , , , , ,


, , , , and . Un Además, negro, blanco y rojo, puede utilizar las siguientes variables
como argumento para setColor (): azul, cian, darkGray, gris, verde,
gris_claro, magenta, naranja, rosa y amarillo. There also are methods of the
class that can be used to create a color based on RGB values, a popular system for
specifying a wide range of possible colors. También hay métodos de la clase de color
que se pueden utilizar para crear un color basado en los valores RGB, un popular sistema
para especificar una amplia gama de colores posibles. RGB values are used on Web pages
with the attribute of the tag. Los valores RGB se utilizan en las páginas Web con el
atributo BGCOLOR de la etiqueta <BODY>.

Quiz Quiz
Roll the dice and put your knowledge of object creation on the line by answering the
following questions. Tira los dados y poner su conocimiento de la creación de objetos en la
línea de responder a las siguientes preguntas.

Questions Preguntas

1. What's the name for a method that is automatically called when an object is created? 1.
¿Cuál es el nombre de un método que se llama automáticamente cuando un objeto se
crea?

(a) an automat (A) un autómata


(b) a constructor (B) un constructor
(c) an method (C) un método init ()

2. In Java, which of the following isn't a synonym for program? 2. En Java, ¿cuál de los
siguientes no es un sinónimo para el programa?

(a) a class (A) una clase


(b) a method (B) un método
(c) an object (C) un objeto

3. What's the name of the method in the class that rounds a number down to the next
lowest integer? 3. ¿Cuál es el nombre del método en la clase de matemáticas que
redondea un número hacia abajo al entero más próximo?

(a) (A) el suelo ()


(b) (B) todo el año ()
(c) (C) siguiente ()

Answers Respuestas

1. b. 1. B. An object's constructor method is called when it is created. método de un objeto


constructor se llama cuando se crea. The method might sound familiar because it's
handled automatically when an applet is first loaded. El método init () puede sonar
familiar porque se maneja de forma automática cuando un applet se carga por primera
vez.

2. b. 2. B. A program also can be considered as a class of objects or an object itself. Un


programa también puede ser considerado como una clase de objetos o un objeto en sí.

3. a. 3. A. The method adds 0.5 to a number before finding the next lowest integer,
rounding it off to the closest integer. La ronda () añade 0,5 a un número antes de
encontrar el número entero inmediatamente inferior, el redondeo se fuera al entero más
próximo.

Activities Actividades
Before you continue to the applet, you can expand your knowledge of this hour's topics
with the following activities: Antes de continuar con el subprograma de dados, usted
puede ampliar su conocimiento de la hora de los temas de este con las siguientes
actividades:

 To see whether the method really generates random numbers, create a short application
that rolls 10,000 dice, using an array of integers to keep track of how many times each
value from 1 to 6 is rolled. Para ver si el () método aleatorio realmente genera
números aleatorios, crear una aplicación a corto que rueda 10.000 dados, utilizando una
matriz de enteros para llevar un registro de cuántas veces cada valor de 1 a 6 se rodó.
When the dice have finished rolling, display the contents of the array. Cuando los dados se
han terminado de rodar, mostrar el contenido de la matriz.
 Add an argument to the method that determines the color of the die. Añada el
argumento de la drawDie () que determina el color de la matriz. Use a object for the
argument so you can send values such as and to the method. Utilice un objeto Color
para el argumento para que pueda enviar valores como Color.blue y Color.yellow al
método.

 22 horas
o Escribir un juego para la Web
 Creación de un applet
 Listado de 22.1. La fuente de partida el código de Craps.java.
 Crear variables a utilizar
 Listado de 22.2. Configuración de variables en Craps.java.
 Configuración de variables y la pantalla inicial
 Listado de 22.3. Los estados dentro del método init () de Craps.java.
 Mostrar texto y gráficos
 Listado de 22.4. Los estados dentro de la pintura () de Craps.java.
 Mango de entrada del usuario
 Listado de 22.5. Los estados dentro de la () método actionPerformed de
Craps.java.
 Compruebe los resultados Roll y llevar la cuenta
 Listado de 22.6. Los estados dentro de la checkResult () de Craps.java.
 Listado de 22.7. El código fuente completo de Craps.java.
 Poner el programa en una página
 Listado de 22,8. El código fuente de Craps.html.
 Figura 22.1.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades
Hour 22 22 horas

Writing a Game for the Web Escribir un juego para la


Web

With the class you created during the last hour, you can add dice to any of your Java
programs. Con el dado clase en la que creó durante la última hora, puede añadir los dados a
cualquiera de los programas Java. The program that you will be writing during this hour
uses two dice. El programa de los dados que va a estar escribiendo durante esta hora se
utilizan dos dados. Most of the tasks you have to handle in your game are taken care of by
the class. La mayor parte de las tareas que han de manejar en el juego son atendidos por el
dado clase. What's left for your applet is to display information to users, take input from
users, and keep score. Lo que queda para el applet Craps es para mostrar la información a
los usuarios, tomar la entrada de los usuarios, y llevar la cuenta.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 Creating an applet Creación de un applet


 Using the method in an applet Utilizando el método init () en un applet
 Using the method to display things Utilizando el método paint () para mostrar las cosas
 Using constants in a program El uso de constantes en un programa de
 Putting a button on an applet Poner un botón en un applet
 Responding to button clicks En respuesta a los clics del botón
 Creating objects La creación de matrices de objetos
 Using fonts and color Utilización de fuentes y el color

Creating an Applet Creación de un applet


All applets that you create will have some methods in common. Todos los applets que se
crea tendrá algunos métodos en común. The method is called when an applet loads on a
page for the first time; you can use this method to set up variables and handle other startup
tasks. El método init () se llama cuando se carga un applet en una página por primera
vez, se puede utilizar este método para configurar y manejar las variables de inicio de otras
tareas. The method is called whenever something should be updated on the display. El
método paint () se llama cada vez que algo debe ser actualizado en la pantalla. It also can
be called within a program with the statement. También se puede llamar dentro de un
programa con el repaint (); comunicado. The and methods will be used in your applet.
El init () y paint () métodos se utilizan en el applet dados. You also will use the
method, which is called whenever a user does something to a graphical item such as
clicking on a button or hitting Enter in a text field. También se utiliza el actionPerformed
() método, que es llamada cuando un usuario hace algo con un elemento gráfico, tales
como hacer clic en un botón o pulsando Enter en un campo de texto.

Create a skeletal version of that can be filled in during the hour as each section of the
program is discussed. Crear una versión del esqueleto de los dados que se pueden rellenar
durante la hora y por cada sección del programa se discute. Create a new file in your word
processor and enter Listing 22.1. Crear un nuevo archivo en el procesador de texto y
escriba Listado de 22.1. Save it under the name , making sure that it is saved in the same
directory as and . Guardarlo con el nombre Craps.java, asegurándose de que se guarda
en el mismo directorio que Die.java y Die.class.

Listing 22.1. Listado de 22.1. The starting source code of Craps.java. La fuente de
partida el código de Craps.java.
1: import java.awt.*; 2: import java.awt.event.*; 3: 4:
public class Craps extends java.applet.Applet implements
ActionListener { 5: // create variables here 6: 7: public
void init() { 8: // initialize program 9: } 10: 11: public
void paint(Graphics screen) { 12: // display stuff 13: }
14: 15: public void actionPerformed(ActionEvent event)
{ 16: // receive user input 17: } 18: 19: public void
checkResult(Die d1, Die d2) { 20: // check roll and keep
score 21: } 1: import java.awt .*; 2: java.awt.event
importación .*; 3: 4: Dados clase pública se extiende
java.applet.Applet implementa ActionListener {5: / / crear
variables aquí 6: public void init: 7 () {8: / /
inicializar el programa 9:} 10:) la pantalla pública: 11
void (pintura gráficos {12: / / material de exhibición 13:}
14: 15: public void actionPerformed (ActionEvent evento)
{16: / / recibir la entrada del usuario 17:} 18:: 20
públicas: 19 sin efecto checkResult (Die d1, d2 morir) {/ /
rollo de verificación y llevar la cuenta 21:} 22:}

In addition to the , , and methods, this skeletal version of the applet includes a method
with two objects as parameters. Además de la de inicio (), pintura (), y
actionPerformed () métodos, esta versión del esqueleto del applet dados incluye un
checkResult () con dos matrices objetos como parámetros. As you will see, this method
is used to check the results of a dice roll and keep score. Como verán, este método se utiliza
para comprobar los resultados de una tirada de dados y llevar la cuenta.

Create Variables to Use Crear variables a utilizar


The first task in the applet is to set up all variables that are going to be used in the program.
La primera tarea en el subprograma de Craps es establecer todas las variables que van a ser
utilizados en el programa. In your word processor, delete the comment line and enter
Listing 22.2 in its place. En el procesador de texto, eliminar la línea de comentario / /
crear variables aquí y entrar en lista 22.2 en su lugar.
Listing 22.2. Listado de 22.2. Setting up variables in Craps.java. Configuración de
variables en Craps.java.
1: Die die1 = new Die(); 2: Die die2 = new Die(); 3: int
wins = 0; 4: int losses = 0; 5: int point = 0; 6: final
String WINNER = "WINNER"; 7: final String LOSER = "CRAPS!";
8: String resultText = ""; 1: Die die1 = new morir (), 2:
Die die2 = new morir (); 3: gana int = 0; 4: pérdidas int =
0, 5, punto int = 0; 6: Ganador de la Final String =
"GANADOR" ; 7: final PERDEDOR String = "craps"; 8:
resultText String = ""; 9: rollButton botón = new Button ("Roll
Dice");

Lines 1 and 2 create new variables called and . Las líneas 1 y 2 de crear nuevas matrices
variables llamadas die1 y die2. These variables are set up in the same way other variables
such as strings are created by using the class name, variable name, and the statement. Estas
variables se crean del mismo modo que otras variables tales como cadenas se crean con el
nombre de clase, nombre de la variable, y la nueva declaración. When this statement is
handled in your program, a constructor method of the class is called. Cuando esta
declaración se maneja en su programa, un método constructor de la clase se llama morir.
Because there's nothing in between the parentheses in , the matching constructor with no
arguments is called in the class. Porque no hay nada entre los paréntesis en las nuevas
matrices (), el constructor de juego sin argumentos se le llama en el dado clase.

In Lines 3 and 4, two integer variables are used to keep track of a user's win/loss record:
and . En las líneas 3 y 4, dos variables enteras se utilizan para llevar un registro de usuario
de ganar una y derrotas: victorias y derrotas. The integer variable in Line 5 stores the
point, which is the dice total that must be rolled to win in a craps game after the first roll.
La variable entera punto en la línea 5 tiendas el punto, que es el total de dados que se debe
rodar para ganar en un juego de dados después de la primera tirada.

Lines 6 and 7 create strings named and . Líneas 6 y 7 de crear cadenas con nombre
ganador y un perdedor. The statement is used to declare that these variables are
constants. La declaración final se utiliza para declarar que estas variables son constantes.
A constant is a variable that will never change in value as a program runs. Una constante es
una variable que nunca va a cambiar en valor como un programa se ejecuta. To provide
another hint that the variables are constants, the names and are capitalized. Para mostrar
otro indicio de que las variables son constantes, los nombres de ganador y el perdedor se
capitalizan.

Because constants never change in value, you might wonder why one should ever be used.
Debido a las constantes nunca cambio en el valor, usted podría preguntarse por qué nadie se
debe utilizar. You could just use the value of the constant throughout the program. Usted
sólo puede usar el valor de la constante a lo largo del programa. The advantage of using
constants is that they can make a program easier to understand. La ventaja de usar las
constantes es que se puede hacer un programa más fácil de entender. For example, the
variables and are constants that hold integer values representing the style of the current
font. Por ejemplo, las variables Font.Bold y Font.ITALIC son constantes que tienen
valores enteros que representan el estilo de la fuente actual. The statement provides more
information than does, and both statements make 12-point Helvetica Bold the current font
for text display. La declaración de la fuente ("Helvetica", Font.Bold, 12) ofrece
más información de la Font ("Helvetica", 1, 12) lo hace, y ambos estados hacen 12
puntos Helvetica negrita la fuente actual para mostrar texto.

Line 8 sets up a string called and sets it up with an initial value of --an empty string. Línea
8 establece una cadena llamada resultText y lo establece con un valor inicial de "" - una
cadena vacía. The last line, 9, creates a object called . La última línea, 9, se crea un objeto
Button denominado rollButton. As this object is created, the string is sent to the
constructor method of the object. is a class of objects that handle the display and function
of clickable user buttons. Dado que este objeto se crea, la cadena "Roll Dice" se envía al
método constructor del objeto. Button es una clase de objetos que se encargan de la
pantalla y la función de los botones el usuario puede hacer clic. The object is given the
label . El objeto rollButton se le da la etiqueta Tirar los dados. This button is shown
in the applet window, and it gives the user a chance to request a dice roll. Este botón se
muestra en la ventana del applet, y se le da al usuario la oportunidad de solicitar una tirada
de dados.

Set Up Variables and the Initial Display Configuración de variables y la pantalla inicial
A few things need to be done when the applet first runs on a Web page. Algunas cosas que
hay que hacer cuando el applet dados primero se ejecuta en una página Web. You need to
choose a background color for the window and add the object to the window. Usted tiene
que elegir un color de fondo de la ventana y agregue el rollButton objeto Button a la
ventana. To do these things, replace the comment line with Listing 22.3. Para hacer estas
cosas, sustituir la línea de comentario / / inicializar el programa con la inclusión de
22.3.

Listing 22.3. Listado de 22.3. The statements inside the init() method of Craps.java. Los
estados dentro del método init () de Craps.java.

1: setBackground(Color.green); 1: setBackground
(Color.green);
2: rollButton.addActionListener(this); 2:
rollButton.addActionListener (este);
3: agregar (rollButton);
In Line 1 of Listing 22.3, the constant is used with the method to choose green as the
background color of the applet window. En la Línea 1 del listado 22.3, la constante
Color.green se utiliza con el setBackground () para elegir verde como el color de fondo
de la ventana del applet. When the method is called automatically to display the applet on-
screen, it uses the color defined in . Cuando el método paint () se llama automáticamente
para mostrar el applet en pantalla, utiliza el color definido en setBackground (). If there
is no statement in a Java program, the default is gray. Si no hay setBackground () en un
programa Java, el valor por defecto es gris.

Line 2 makes it possible for the object to generate action events when it is clicked. Línea 2
hace posible que el objeto rollButton para generar eventos de acción cuando se hace clic.
This is done by using the method, which is part of the interface. Esto se hace mediante el
addActionListener () método, que es parte de la interfaz ActionListener. Line 3 adds
the object to the applet window. Línea 3 agrega el objeto rollButton a la ventana del
applet.

Display Text and Graphics Mostrar texto y gráficos


The method is called any time the text and graphics on-screen should be updated. El
método paint () se llama cada vez que el texto y los gráficos en la pantalla debe ser
actualizada. This situation occurs when the program is run to draw something onto a blank
window. Esta situación se produce cuando se ejecuta el programa para dibujar algo en una
ventana en blanco. The method also can be called any time one of the following takes
place: El método paint () también puede ser llamado alguna vez que uno de los siguientes
se lleva a cabo:

 The window of the Web browser displaying the applet is resized La ventana del explorador
Web que muestra el applet se cambia el tamaño
 A window or dialog box displayed in front of the applet is moved Una ventana o cuadro de
diálogo que se muestra en la parte delantera del applet se mueve
 The method is called in a program to force a screen update to occur El repaint () se
llama al método en un programa para forzar una pantalla de actualización que se produzca

In your growing file, delete the comment line inside the method. En su creciente archivo
Craps.java, eliminar la línea de comentario / / cosas de visualización dentro del
método paint (). Replace it with Listing 22.4. Reemplácela con la inclusión de 22.4.

Listing 22.4. Listado de 22.4. The statements inside the paint() method of Craps.java.
Los estados dentro de la pintura () de Craps.java.
1: die1.drawDie(screen, 5, 50); 2: die2.drawDie(screen,
175, 50); 3: screen.setColor(Color.black); 4: Font f = new
Font("Helvetica", Font.BOLD, 15); 5: screen.setFont(f); 6:
if (point != 0) 7: screen.drawString(point + " wins and 7
craps out.", 5, 200); 8: else 9: screen.drawString("7 or 11
win; 2, 3, or 12 crap out.", 5, 200); 10:
screen.drawString("Number of wins: " + wins, 5, 220); 11:
screen.drawString("Number of losses: " + losses, 5, 240);
12: if (resultText != "") { 13: f = new Font("Helvetica",
Font.BOLD, 30); 14: screen.setFont(f); 15:
screen.drawString(resultText, 85, 110); 16: resultText =
""; The following things are taking place in this method:
2, 1: die1.drawDie (Imagen, 5 50);) die2.drawDie (Imagen,
175, 50, 3: screen.setColor (Color.Black), 4: Tipo de letra
f = new Font ("Helvetica", Fuente . BOLD, 15); 5:
screen.setFont (f), 6: si (el punto.! = 0) 7:
screen.drawString (punto ", 5, 200); 8 +" victorias y siete
dados de salida: 9 más : screen.drawString ("7 u 11 ganan,
2, 3, o 12 mierda.", 5, 200); 10: screen.drawString
("Número de victorias:" + victorias, 5, 220); 11:
pantalla . drawString ("El número de pérdidas:" + pérdidas,
5, 240); 12: if (resultText "! =") {13: f = new Font
("Helvetica", Font.Bold, 30); 14: pantalla. setFont (f),
15: screen.drawString (resultText, 85, 110); 16: resultText
= ""; 17:} Los siguientes factores están teniendo lugar en
este método:

 Lines 1 and 2: The method of the class is called to display two dice. Las líneas 1 y 2: El
drawDie () de la clase de morir está llamada a mostrar dos dados. The first argument,
, is the object that tells the class to draw something on-screen. El primer argumento, la
pantalla, es el objeto gráfico que indica el dado clase a dibujar algo en la pantalla.
The second and third arguments are the x and y coordinates where the dice should be
drawn. Los argumentos segundo y tercero son las coordenadas X e Y, donde los dados
deberían proceder.
 Lines 3-5: The current color is set to black with the constant, and the current font is set to
15-point Helvetica Bold. Líneas 3-5: El color actual se establece en negro con la constante
Color.Black, y la fuente actual se establece en 15 puntos Helvetica Bold.
 Lines 6 and 7: If the value does not equal 0, a string is displayed on-screen using the
method. Líneas 6 y 7: Si el valor del punto no es igual a 0, una cadena se muestra en la
pantalla utilizando el drawString () método. The string that is displayed is the value of
followed by the text . La cadena que se muestra es el valor del punto seguido por los
triunfos de texto y 7 dados a cabo. For example, if equals , the string is . Por
ejemplo, si el punto es igual a 5, la cadena es de 5 victorias y 7 dados a cabo.
The last two parameters to the method are the x and y coordinates where the string
should be displayed. Los últimos dos parámetros a la drawString () método son las
coordenadas X e Y, donde la cadena se debe mostrar.
 Lines 8 and 9: Using the statement, if the value does equal , the text is shown. Las líneas
8 y 9: Utilización de la sentencia más, si el valor del punto es igual a 0, el texto de 7 u
11 ganan, 2, 3, o 12 mierda muestra. Es.
 Lines 10 and 11: The user's win/loss record is displayed along with explanatory text. Las
líneas 10 y 11: ganar el usuario y derrotas se muestra junto con un texto explicativo.
 Lines 12-17: This block statement is handled if the value of the is not empty (the null
value ). Líneas 12-17: Este bloque de sentencias si se controla si el valor de la
resultText no está vacío (el valor nulo ""). If has any text in it, this text is displayed
on-screen after the current font is set to 30-point Helvetica Bold. Si resultText tiene
cualquier texto en él, este texto se visualiza en la pantalla después de la fuente actual se
establece en 30 puntos Helvetica Bold. After is displayed, it is set to equal again so that it
will not be displayed twice. Después de resultText se muestra, se establece la igualdad
"" de nuevo para que no aparezca dos veces.

The text that is displayed in the method depends on several things that are going on in
other parts of the program. El texto que se muestra en el método paint () depende de varias
cosas que están sucediendo en otras partes del programa. Because the rolls needed to win or
lose change at different points in a game, uses the value of to determine what should be
displayed. Debido a que los rollos necesarios para ganar o perder, cambia en diferentes
puntos en un juego, la pintura () utiliza el valor del punto para determinar lo que se debe
mostrar. The variable equals at the beginning of a new game of craps because there is no
point until the first roll is over. El punto variable es igual a 0 en el comienzo de un nuevo
juego de los dados, porque no tiene sentido hasta que la primera tirada se acabó. The
variable is displayed only when a game is over. La variable resultText sólo se muestra
cuando un juego ha terminado. It is set initially in another part of the program, the method.
Se establece inicialmente en otra parte del programa, la checkResult () método.

Handle User Input Mango de entrada del usuario


Go to the spot in your program with the comment line and replace it with Listing 22.5. Ir
al lugar en el programa de los dados con la línea de comentario / / recibir la
entrada del usuario y reemplazarlo con la inclusión de 22.5.

Listing 22.5. Listado de 22.5. The statements inside the actionPerformed() method of
Craps.java. Los estados dentro de la () método actionPerformed de Craps.java.
1: die1.rollValue(6); 2: die2.rollValue(6); 3:
checkResult(die1, die2); 1: die1.rollValue (6); 2:
die2.rollValue (6); 3: checkResult (die1, die2); 4: repaint
();

As you learned during Hour 20, "Responding to User Events," the method is called
whenever an action event occurs on a component that can send out those events. Como ha
aprendido durante la hora 20, "Responder a eventos de usuario", el actionPerformed ()
es llamado cada vez que un evento de acción se produce en un componente que puede
enviar los eventos. The applet has only one user interface component, a object called ,
which has been set up with an object so it can generate action events. El applet dados sólo
tiene un componente de la interfaz de usuario, un botón de objeto llamado rollButton,
que se ha creado con un objeto ActionListener por lo que puede generar eventos de
acción.

The object in this program is labeled with the text . El objeto rollButton en este
programa está etiquetado con el texto Tirar los dados. When the button is clicked,
Lines 1 and 2 call the method of each object. Cuando se pulsa el botón, las líneas 1 y 2 de
llamar a la rollValue () de cada objeto morir. The argument, 6, indicates that a number
from 1 to 6 should be rolled on each die. El argumento, 6, indica que un número del 1 al 6
debe ser rodado en cada dado. When a is rolled, the variable is updated with the die's new
value. Cuando se rueda un dado, la variable valor se actualiza con el nuevo valor de la
muerte.

After the dice roll, you should see whether the new total of the dice is a winner or loser.
Después de la tirada de dados, usted debe ver si el nuevo total de los dados es un ganador o
un perdedor. You do this by calling the method of the applet with two arguments: and ,
the two objects. Esto se hace llamando a la checkResult () de la applet con dos
argumentos: die1 y die2, las dos matrices de objetos. The method is detailed in the next
section. El checkResult () se detallan en la siguiente sección.

Line 4 calls the method to force the screen to be updated. Línea 4 llama al pintar () para
forzar la pantalla para ser actualizados. This method is needed because the dice and other
information change with each roll, and those changes should be reflected on-screen. Este
método es necesario porque los dados y cambiar la información de otros con cada rollo, y
esos cambios deben reflejarse en la pantalla.

Check Roll Results and Keep Score Compruebe los resultados Roll y llevar la cuenta
The last thing to handle in the applet is scorekeeping. Lo último que se puede agarrar en el
applet Craps es registro de resultados. The method of your program takes two objects as
arguments. El checkResult () de su programa toma dos matrices objetos como
argumentos. Delete the comment line and replace it with Listing 22.6. Eliminar el
comentario de la línea / / rollo de verificación y llevar la cuenta y sustituirla
con la inclusión de 22.6.

Listing 22.6. Listado de 22.6. The statements inside the checkResult() method of
Craps.java. Los estados dentro de la checkResult () de Craps.java.

1: if (point == 0) { 1: si (punto == 0) {
2: point = d1.value + d2.value; 2: punto = d1.value +
d2.value;
3: if ( (point == 7) | (point == 11) ) 3: if ((punto ==
7) | (punto == 11))
4: resultText = WINNER; 4: resultText = ganador;
5: if ( (point < 4) | (point == 12) ) 5: if ((punto <4) |
(punto == 12))
6: resultText = LOSER; 6: resultText = PERDEDOR;
7: } else { 7:} else {
8: if (d1.value + d2.value == point) 8: si (+ d2.value ==
punto d1.value)
9: resultText = WINNER; 9: resultText = ganador;
10: if (d1.value + d2.value == 7) 10: if (d1.value +
d2.value == 7)
11: resultText = LOSER; 11: resultText = PERDEDOR;
12: } 12:}
13: if (resultText == WINNER) { 13: if (resultText ==
GANADOR) {
14: wins++; 14: gana + +;
15: point = 0; 15: punto = 0;
16: } 16:}
17: if (resultText == LOSER) { 17: if (resultText ==
perdedor) {
18: losses++; 18: pérdidas + +;
19: point = 0; 19: punto = 0;
20:}

Lines 2 -6 of this method are handled only if the variable is equal to . Las líneas 2 a 6 de
este método se manejan sólo si la variable punto es igual a 0. The variable is used
throughout this program as an indicator of the current stage of the craps game. La variable
de coma se utiliza en este programa como un indicador de la etapa actual del juego de
dados. When equals , it shows that the current craps game has just finished its first roll,
because the point has not been established yet. Cuando el punto es igual a 0, muestra que
el juego de dados actual acaba de terminar su primer lanzamiento, porque el punto no ha
sido establecida todavía. If does not equal , the current game must be in its second or
successive rolls. Si el punto no es igual a 0, el juego actual debe estar en su segundo o
sucesivos rollos. When equals , Line 2 sets to the sum of the variables of both objects.
Cuando el punto es igual a 0, la línea 2 conjuntos de puntos a la suma de las variables de
valor de los objetos de morir. The variable keeps track of each die's current value in the
game. La variable de valor hace un seguimiento de los actuales mueren cada valor en el
juego.

Lines 3-6 determine whether a winning roll or a losing roll has happened in the first roll of
a craps game. Líneas 3-6 determinar si un rollo de ganar o perder un rollo que ha sucedido
en el primer lanzamiento de un juego de dados. The dice totals of 7 and 11 are winners, and
the totals of 2, 3, or 12 are losers. Los totales dados de ganadores 7 y 11 son, y los totales
de 2, 3, o 12 son los perdedores. The operator is used in Lines 3 and 5, so if either one
equality test or the other is true, the following statement is handled. El operador OR | se
utiliza en las líneas 3 y 5, así que si cualquiera de las pruebas la igualdad de uno u otro es
cierto, la siguiente declaración se maneja. If is equal to or is equal to , the variable is set
to the value of the variable, which is the text . Si el punto es igual a 7 o el punto es igual
a 11, la variable resultText se establece en el valor de la variable GANADOR, que es el
GANADOR de texto. If is less than or is equal to , is set to the value of the variable, which
is . Si el punto está a menos de 4 o punto es igual a 12, resultText se establece en el
valor de la variable de perdedor, que es CRAP!.

Lines 8-11 of this method are handled only if did not equal in Line 1. Líneas 8-11 de este
método se manejan sólo si el punto no es igual a 0 en la Línea 1. Line 8 tests whether the
current total of the dice is equal to . Línea 8 pruebas si la corriente total de los dados es
igual a la punta. If it is, the variable is set to the value of the variable, which is . Si es
así, la variable resultText se establece en el valor de la variable GANADOR, que es el
ganador. Line 10 tests whether the current dice total equals . Línea 10 pruebas si el total
de los dados actual es igual a 7. If it does, is set to equal the variable, which is Si lo hace,
resultText se establece la igualdad de la variable de perdedor, que es CRAP!

Lines 13-16 are handled if is equal to the variable, which indicates that the current dice
roll was a winner. Líneas 13 a 16 si se manejan resultText es igual a la variable
GANADOR, lo que indica que la tirada actual es un ganador. The variable is increased by 1 in
Line 14 by the increment operator . La variable gana se incrementa en 1 en la línea 14 por
el operador de incremento + +. Also, the variable is set to in Line 15 so that a new game
can begin. Además, la variable se establece en el punto 0 en la línea 15 para que un
nuevo juego puede comenzar.

Lines 17-20 are handled if is equal to the variable. Líneas 17 a 20 si se manejan


resultText es igual a la variable de perdedor. These lines cause the variable to increase
by 1 and to be set to in Line 19. Estas líneas de causar la variable de las pérdidas a un
aumento de un punto y se pone a 0 en la línea 19.

When you're done adding these statements inside the method, your program should
resemble Listing 22.7. Cuando hayas terminado de añadir estas declaraciones dentro de la
checkResult () método, el programa debe ser similar de venta 22.7. The only differences
should be if you indented the program differently, but all statements should be identical.
Las únicas diferencias se si sangría del programa diferente, pero todas las declaraciones
deben ser idénticos. Save your file. Guarde el archivo Craps.java.

Listing 22.7. Listado de 22.7. The complete source code of Craps.java. El código fuente
completo de Craps.java.
1: import java.awt.*; 2: import java.awt.event.*; 3: 4:
public class Craps extends java.applet.Applet implements
ActionListener { 5: Die die1 = new Die(); 6: Die die2 = new
Die(); 7: int wins = 0; 8: int losses = 0; 9: int point =
0; 10: final String WINNER = "WINNER"; 11: final String
LOSER = "CRAPS!"; 12: String resultText = ""; 13: Button
rollButton = new Button("Roll Dice"); 14: 15: public void
init() { 16: setBackground(Color.green); 17:
rollButton.addActionListener(this); 18: add(rollButton);
19: } 20: 21: public void paint(Graphics screen) { 22:
die1.drawDie(screen, 5, 50); 23: die2.drawDie(screen, 175,
50); 24: screen.setColor(Color.black); 25: Font f = new
Font("Helvetica", Font.BOLD, 15); 26: screen.setFont(f);
27: if (point != 0) 28: screen.drawString(point + " wins
and 7 craps out.", 5, 200); 29: else 30:
screen.drawString("7 or 11 win; 2, 3, or 12 crap out.", 5,
200); 31: screen.drawString("Number of wins: " + wins, 5,
220); 32: screen.drawString("Number of losses: " + losses,
5, 240); 33: if (resultText != "") { 34: f = new
Font("Helvetica", Font.BOLD, 30); 35: screen.setFont(f);
36: screen.drawString(resultText, 85, 110); 37: resultText
= ""; 38: } 39: } 40: 41: public void
actionPerformed(ActionEvent event) { 42: die1.rollValue(6);
43: die2.rollValue(6); 44: checkResult(die1, die2); 45:
repaint(); 46: } 47: 48: public void checkResult(Die d1,
Die d2) { 49: if (point == 0) { 50: point = d1.value +
d2.value; 51: if ( (point == 7) | (point == 11) ) 52:
resultText = WINNER; 53: if ( (point < 4) | (point == 12) )
54: resultText = LOSER; 55: } else { 56: if (d1.value +
d2.value == point) 57: resultText = WINNER; 58: if
(d1.value + d2.value == 7) 59: resultText = LOSER; 60: }
61: if (resultText == WINNER) { 62: wins++; 63: point = 0;
64: } 65: if (resultText == LOSER) { 66: losses++; 67:
point = 0; 68: } 69: } Compile the file using the
following command: javac Craps.java 1: import java.awt .*;
2: java.awt.event importación .*; 3: 4: Dados clase pública
se extiende java.applet.Applet implementa ActionListener
{5: Die die1 = new morir (), 6: Die die2 = new morir (); 7:
gana int = 0; 8: pérdidas int = 0, 9, punto int = 0; 10:
GANADOR final String = "ganador"; 11: final PERDEDOR String
= "craps"; 12: resultText cadena = ""; 13: rollButton botón
= new Button ("Roll Dice"); 14: 15: public void init ()
{16: setBackground (Color.green); 17:
rollButton.addActionListener (este); 18: añadir
(rollButton); 19:} 20: 21: void pintura público (gráficos
de la pantalla) {22:) die1.drawDie (Imagen, 5, 50, 23:
die2.drawDie (Imagen, 175, 50); 24: pantalla. setColor
(Color.Black), 25: Tipo de letra f = new Font ("Helvetica",
Font.Bold, 15); 26: screen.setFont (f), 27: if (! punto =
0) 28: screen.drawString ( punto + "victorias y 7 dados a
cabo.", 5, 200); 29: otro 30: screen.drawString ("7 u 11
ganan, 2, 3, o 12 mierda.", 5, 200); 31: pantalla .
drawString ("Número de victorias:" + victorias, 5, 220);
32: screen.drawString ("El número de pérdidas:" + pérdidas,
5, 240); 33: if = "34") {: (resultText! f = new Font
("Helvetica", Font.Bold, 30); 35: screen.setFont (f), 36:
screen.drawString (resultText, 85, 110); 37: resultText =
""; 38:} 39: } 40: 41: public void actionPerformed
(ActionEvent evento) {42: die1.rollValue (6); 43:
die2.rollValue (6); 44: checkResult (die1, die2); 45:
repaint (); 46:} 47 : 48: checkResult public void (Die d1,
d2 morir) {49: if (punto == 0) {50: punto = d1.value +
d2.value; 51: if ((punto == 7) | (punto = = 11)) 52:
resultText = GANADOR; 53: if ((punto <4) | (punto == 12))
54: resultText = PERDEDOR; 55:} else {56: if (d1.value +
d2.value = = punto) 57: resultText = GANADOR; 58: if
(d1.value + d2.value == 7) 59: resultText = PERDEDOR; 60:}
61: if (resultText == GANADOR) {62: gana + +; 63: el punto
= 0; 64:} 65: if (resultText == perdedor) {66: pérdidas +
+; 67: punto = 0; 68:} 69:} 70:} Compilar el archivo
Craps.java con el siguiente comando: javac Craps.java

After fixing any errors that are caused by typos, you're almost ready to test the program.
Después de arreglar los errores que se deben a errores tipográficos, que está casi listo para
probar el programa.

Putting the Program on a Page Poner el programa en una página


Because the program is an applet, it was designed to run only as part of a World Wide Web
page. Debido a que el programa de los dados es un applet, que fue diseñado para
funcionar únicamente como parte de una página del World Wide Web. To place the applet
on a Web page, create a new file called . Para colocar el applet en una página Web, crear
un nuevo archivo llamado Craps.html. Enter Listing 22.8 and save the file in the same
directory as and . Introduzca Listado 22.8 y guardar el archivo en el mismo directorio que
Craps.java y Craps.class.

Listing 22.8. Listado de 22,8. The source code of Craps.html. El código fuente de
Craps.html.

1: <html> 1: <html>
2: <head> 2: <head>
3: <title>Craps applet</title> 3: <title> applet dados </
title>
4: </head> 4: </ head>
5: <body> 5: <body>
6: <applet code="Craps.class" width=285 height=250> 6:
<applet code="Craps.class" width=285 height=250>
7: </applet> 7: </ applet>
8: </body> 8: </ body>
9: </ html>

Most of the HTML tags on the page are just standard tags that are included on any Web
page. La mayoría de las etiquetas HTML en la página son sólo etiquetas estándar que se
incluyen en cualquier página Web. The and attributes of the tag determine how big the
applet will appear on a page. Los atributos de anchura y la altura de la etiqueta <applet>
determinar cuán grande es el applet aparecerá en una página. You can use any dimensions
and the applet will still run because Java creates programs that are flexible when it comes to
how they are displayed. Puede utilizar las dimensiones y el applet seguirá funcionando
porque Java crea programas que son flexibles cuando se trata de la forma en que se
muestran. For optimal appearance, however, use a width of 285 and a height of 250. Por la
apariencia óptima, sin embargo, utilizar un ancho de 285 y una altura de 250.

In order to see the applet, you need to use a Web browser that can handle Java programs.
Para ver el applet, es necesario utilizar un navegador Web que puede manejar los
programas de Java. At the time of this writing, the current versions of Netscape Navigator
and Microsoft Internet Explorer cannot handle new features introduced in version 1.1 of the
Java language. En el momento de escribir esto, las versiones actuales de Netscape
Navigator y Microsoft Internet Explorer no puede manejar las nuevas características
introducidas en la versión 1.1 del lenguaje Java. You have to use the tool that comes with
the Java Developer's Kit to test the applet. Usted tiene que usar la herramienta
appletviewer que viene con Java Developer Kit para la prueba de que el applet dados. If
you're in the same directory as the file, the following command will cause to load the
applet: Si usted está en el mismo directorio que el archivo Craps.html, el siguiente
comando hará que appletviewer para cargar el applet:

appletviewer Craps.html appletviewer Craps.html

Figure 22.1 shows the output of the applet using . La figura 22.1 muestra la salida del
applet dados con appletviewer. Run the program several times to see the different ways
that text and each of the dice can be displayed. Ejecute el programa varias veces para ver
las diferentes maneras en que el texto y cada uno de los dados se pueden mostrar. Because
the dice are drawn with polygons instead of by loading a picture of a die, the applet updates
the graphics quickly as you play. Debido a que los dados están dibujados con polígonos en
lugar de cargar una imagen de un dado, las actualizaciones applet de los gráficos antes de
jugar.

Figura 22.1. The applet on a Web page viewed with the tool. El applet dados en una
página Web vista con la herramienta appletviewer.

Summary Resumen
The applet that you have written shows how you can use Java to offer games on a Web
site. El applet dados que ha escrito muestra cómo se puede usar Java para ofrecer juegos en
un sitio Web. The step-by-step process of creating a program was detailed, including some
of the planning that occurs before you sit down at the computer. El proceso paso-a-paso de
crear un programa detallado, incluyendo algunos de la planificación que se produce antes
de sentarse en la computadora. Because many of the program's tasks involved rolling or
displaying dice, you created a special object to handle all of this functionality. Debido a
que muchas de las tareas del programa participan rodante o mostrar los dados, ha creado un
especial Muere objeto de manejar toda esta funcionalidad. Creating this object enables you
to use some of the work you did for the applet in other programs later on. La creación de
este objeto le permite utilizar algunos de los trabajos que hizo para el applet dados en otros
programas más adelante.

You can use this applet on a Web page in its completed form, and all that is required are the
files and and a Web page with HTML tags to load the applet. Puede utilizar este applet en
una página Web en su formulario completo, y todo lo que se requiere son los archivos
Die.class y Craps.class y una página web con etiquetas HTML para cargar el applet.
Thanks to the global reach of the World Wide Web and Java, you can bring the seedy
charm of craps games to everyone from Afghanistan to Zambia, including Pia Zadora.
Gracias a la proyección internacional de la World Wide Web y Java, que puede traer el
encanto de mala muerte de los juegos de dados para todo el mundo, desde Afganistán hasta
Zambia, Pia Zadora.

Q&A Q & A
Q Do I need to use an import statement to use the Die class or another class of objects
that I create in a program? Q ¿Qué necesito para utilizar una declaración de importación
para uso Die clase u otra clase de objetos que creo en un programa?

A If the class you want to use is in the same directory as your program, an statement is
not required. A Si la clase que usted desea utilizar en el mismo directorio que el programa,
una declaración de importación no es necesaria. The statement makes Java's standard
classes available in a program. La declaración de importación hace que las clases
estándar de Java disponibles en un programa. Place special classes that you create and
other classes that you find on the Web or in books in the same directory as the programs
that use them. Lugar clases especiales que se crean y otras clases que se encuentra en la
Web o en los libros en el mismo directorio que los programas que los utilizan.

Q Isn't constant variable an oxymoron? Q no es una variable constante contradicción?

A Constants never change and variables can change at any time, but it's convenient to call
both variables because they serve the same function. Un Constantes que nunca cambian y
las variables pueden cambiar en cualquier momento, pero es conveniente llamar a ambas
variables, ya que tienen la misma función. Each stores a value for use as a program runs.
Cada uno puede almacenar un valor para su uso como un programa se ejecuta. The
statement is not needed to make a variable a constant in a program-- and would work
the same in the applet without . La declaración final no es necesaria para hacer que
una variable constante en un programa - ganador y un perdedor que funcionan de la
misma en el applet dados sin final. However, it's much safer in your programs to
ensure that a constant remains constant. Sin embargo, es mucho más seguro en sus
programas para asegurar una constante que se mantiene constante.

Q When x and y coordinates are specified in a drawString() statement, where are the x
and y coordinates in relation to the text that is displayed? Q Cuando coordenadas x e y
se especifican en un drawString () declaración, ¿dónde están las coordenadas X e Y en
relación con el texto que se muestra?

A Imagine that there is an invisible box around the text that is exactly big enough to hold
all of the characters. Un Imagina que hay una caja invisible todo el texto que es
exactamente lo suficientemente grande como para contener todos los personajes. The
upper-left corner of this box is the intersection of the x and y coordinates specified as
arguments to . La esquina superior izquierda de este cuadro es la intersección de las
coordenadas x e y especifican como argumentos para drawString ().

Quiz Quiz
If you've become a gambler thanks to this hour's lesson, feel free to make wagers on your
knowledge of programming before you answer the following questions. Si te has
convertido en un jugador gracias a la lección de esta hora, no dude en hacer apuestas en sus
conocimientos de programación antes de contestar las siguientes preguntas.

Questions Preguntas

1. What can you do to make the name of a constant stand out in a program? 1. ¿Qué se
puede hacer para que el nombre de una posición constante en un programa?

(a) Use a foreign language. (A) El uso de una lengua extranjera.


(b) Capitalize the first letter. (B) Poner en mayúscula la primera letra.
(c) Capitalize the whole name. (C) Aprovechar el nombre completo.

2. What method sets the color of the window in an applet? 2. ¿Qué método establece el
color de la ventana en un applet?

(a) (A) setBackground ()


(b) (B) setColor ()
(c) (C) setWindow ()

3. If the first dice roll in a craps game isn't a winner or a loser, what do you call the total of
the roll? 3. Si la tirada por primera vez en un juego de dados no es un ganador o un
perdedor, ¿cómo se llama el total del rollo?

(a) the punt (A) la patada de despeje


(b) the point (B) el punto de
(c) the pint (C) el medio litro

Answers Respuestas
1. c. 1. C. If you only capitalize the first letter, the constant name will look just like the
names of classes in your programs. Si sólo mayúscula la primera letra, el nombre de
constante se parecen a los nombres de las clases en sus programas.

2. a. sets the current color for all successive graphical methods. 2. SetColor a. ()
establece el color actual para todos los métodos gráficos sucesivos.

3. b. 3. B.

Activities Actividades
Now that you have completed your most sophisticated Java project thus far, you can build
your skills with the following activities: Ahora que ha completado su proyecto Java más
sofisticado hasta el momento, usted puede construir sus habilidades con las siguientes
actividades:

 Add a second button to the applet that causes the dice to be constantly rolled until the
button is pressed again. Añade un segundo botón para el applet dados que causa los
dados para estar constantemente rodó hasta que el botón se pulsa de nuevo. The applet
will play craps by itself swiftly, and you can see how often winners and losers are rolled. El
applet jugar a los dados por sí mismo con rapidez, y se puede ver la frecuencia con
ganadores y perdedores se deshacen.
 Add the capability to make wagers on each game of craps in the applet. Añadir la
capacidad de hacer las apuestas en cada juego de los dados en el applet dados. This
capability could be implemented with a choice menu component that lets the user choose
bets of $1, $5, or $10 and a text field that displays the player's current winnings. Esta
capacidad podría ser implementado con un componente de menú a elegir que permite al
usuario elegir las apuestas de $ 1, $ 5 o $ 10 y un campo de texto que muestra las
ganancias actuales del jugador.

 23 horas
o Condimentar una página web
 El applet de Pan
 Viendo las imágenes
 Figura 23.1.
 Taller: Las imágenes de dibujo Durante un Bordes Pantallas
 Listado de 23.1. El texto completo de Pan.java.
 Listado de 23.2. El texto completo de Pan.html.
 Listado de 23.3. El texto completo de Sams.html.
 Figura 23.2.
 Figura 23.3.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades
Hour 23 23 horas

Spicing Up a Web Page Condimentar una página web

When Java was released to the public in late 1995, its creators had some lofty intentions for
the programming language. Cuando Java fue lanzado al público a finales de 1995, sus
creadores habían algunas intenciones nobles para el lenguaje de programación. It was going
to revolutionize the way software was produced and distributed, remove the need to write
versions of a program for different operating systems, and take full advantage of the
Internet as a place to run programs. Se va a revolucionar el software de manera de producir
y distribuir, retire la necesidad de escribir las versiones de un programa para distintos
sistemas operativos, y sacar el máximo provecho de Internet como un lugar para ejecutar
programas. (They probably wanted to make some money, too.) Although some notable
projects created since then with Java advance those goals, many Java programmers worked
under somewhat less noble motivation: show-and-tell. (. Probablemente quería hacer algo
de dinero, también) Aunque algunos proyectos notables creado desde entonces con Java
avanzar esos objetivos, muchos programadores de Java trabajó bajo un poco la motivación
menos noble: mostrar y contar.

For every human who gets a kick out of advancing the causes of humankind, bettering
society, and being the wind beneath someone's wings, there's another who did something
because it looked cool. Para todos los seres humanos que recibe una patada de avanzar las
causas de la humanidad, mejorar la sociedad, y ser el viento bajo las alas de alguien, hay
otro que hizo algo, ya que parecía fresco. Animated Java applets are a case in point.
Animados applets de Java son un ejemplo de ello. There are dozens of different special-
effects applets on the Web that do interesting things with text and graphics. Hay docenas de
diferentes applets de efectos especiales en la Web que hacer cosas interesantes con texto y
gráficos. During this hour you'll set aside the greater good of Javakind and create one of
your own. Durante esta hora usted a un lado el mayor bien de Javakind y crear uno propio.

The following topics will be covered: Los siguientes temas serán cubiertos:

 Controlling an applet with parameters El control de un applet con parámetros


 Loading images from parameters Carga de imágenes a partir de parámetros
 Using off-screen areas for drawing Uso de áreas fuera de la pantalla para dibujar
 Using transparent files Uso transparente. Archivos GIF
 Drawing images off the screen's edges Extracción de imágenes de los bordes de la pantalla
The Pan Applet El applet de Pan
One of the common uses for Java applets has been to animate text or images on a World
Wide Web page. Uno de los usos comunes para los applets de Java ha sido la de animar
texto o imágenes en una página del World Wide Web. This kind of animation can be done
as an attention-getting move; an online catalog might use moving text to inform visitors of
sale items, for example. Este tipo de animación se puede hacer como un movimiento para
captar la atención, un catálogo en línea puede utilizar texto en movimiento para informar a
los visitantes de los artículos en oferta, por ejemplo. It also can be done to provide
information in a more dynamic way. También se puede hacer para proporcionar
información de una manera más dinámica. Several media organizations, such as CNN and
ESPN, have used Java applets as a way to provide constant news and sports updates. Varias
organizaciones de medios, como CNN y ESPN, han utilizado los applets de Java como una
forma de proporcionar noticias y actualizaciones constantes deportes.

A lot of these applets move graphics or text over a static background to produce an
interesting effect. Una gran cantidad de estos gráficos se mueven applets o texto sobre un
fondo estático para producir un efecto interesante. You're going to take the opposite tack
with the applet. Vas a tomar el rumbo opuesto con el applet Panamericana. It will keep
something in the foreground still while the background moves. Asimismo, mantendrá algo
en el primer plano inmóvil mientras se mueve el fondo. The effect could be useful to draw
attention to text or create an interesting logo for a company. El efecto podría ser útil para
llamar la atención sobre el texto o crear un logotipo para una empresa interesante.

The applet uses the same threaded applet structure that you have used in several of the past
hours. El applet Pan utiliza la estructura de rosca applet mismo que ha utilizado en varias
de las últimas horas. A thread called is created in the applet's method and destroyed in the
method. Un llamado corredor hilo se crea en el applet de inicio de la () y destruido en
el método stop (). The object calls the method of the program, which loops continuously
while the program runs. El objeto corredor llama al método run () del programa, que se
repite continuamente mientras se ejecuta el programa.

Three objects are used in the program: , , and . Tres imágenes de objetos se utilizan en
el programa: espalda, primer plano, y el área de trabajo. The first two objects
hold the background image and foreground image that will be displayed. Los primeros dos
objetos tienen la imagen de fondo y primer plano la imagen que se mostrará. The third is
used as an off-screen work area to make the animation appear more smoothly, a trick called
double-buffering that you learned during Hour 18, "Creating Animation." La tercera se
utiliza como área de trabajo fuera de la pantalla para hacer la animación parece más suave,
un truco llamado doble búfer que aprendió durante la hora 18, "Creación de animaciones."
In addition to displaying the background and foreground images, the applet can display a
line of text. Además de mostrar las imágenes de fondo y primer plano, el applet puede
mostrar una línea de texto. This text and both images are specified in parameters on the
Web page that runs the applet. Este texto y las imágenes tanto se especifican en los
parámetros en la página Web que se ejecuta el applet. You can use the following
parameters: Puede utilizar los siguientes parámetros:

 : This parameter is the file name of the background image that will pan across the applet
window from right to left. de fondo: Este parámetro es el nombre del archivo de la
imagen de fondo que desplazarse por la ventana del applet de derecha a izquierda. This
image file must be in or format and must be located in the same place as the file of the
applet. Este archivo de imagen debe estar en formato. GIF o. Formato JPG y deben
estar ubicados en el mismo lugar que el archivo de clase. Del applet.
 : This parameter is the file name of the foreground image that will be displayed as the
background image moves behind it. primer plano: Este parámetro es el nombre del
archivo de la imagen en primer plano que se muestra como la imagen de fondo se mueve
detrás de él. This file should be in format and must have a transparent color. Este archivo
debe estar en formato. Formato GIF y debe tener un color transparente. Otherwise,
nothing will be visible behind the image. De lo contrario, no será visible detrás de la
imagen. This parameter is optional, so you can choose not to display a foreground image
at all. Este parámetro es opcional, por lo que no puede optar por mostrar una imagen de
primer plano en absoluto.
 : This parameter is the line of text to display in front of all images that are being displayed.
texto: Este parámetro es la línea de texto que se mostrará delante de todas las
imágenes que se muestren. If this parameter is omitted, no text will be shown. Si se omite
este parámetro, no hay texto será mostrado.
 : This parameter is the name of the font that the text should be displayed in. Arial is the
default. FontName: Este parámetro es el nombre de la fuente que el texto aparezca in
Arial es el valor predeterminado.
 : This parameter is the size of the text's font, which defaults to 24. tamaño del texto:
Este parámetro es el tamaño del texto de la fuente, que por defecto es 24.

Displaying the Images Viendo las imágenes


All text and images are displayed in the method of the applet. Todos los textos y las
imágenes se muestran en el método paint () del applet Panamericana. An off-screen
object is used for all drawing methods, and when everything has been drawn, the off-screen
area is copied to the applet window. Una pantalla de gráficos a objetos fuera se utiliza
para todos los métodos de dibujo, y cuando todo se ha elaborado, el área frente a la pantalla
se copia en la ventana del applet. Using double-buffering produces much better results than
displaying each image and string in the window individually. Utilizando doble buffer
produce resultados mucho mejores que mostrar cada imagen y la cadena en la ventana de
forma individual.

If a line of text is specified as a parameter, the applet will center it horizontally and
vertically on-screen. Si una línea de texto se especifica como un parámetro, el subprograma
se centrará en forma horizontal y verticalmente en la pantalla. This is done using a class
called , which reports on how large a line of text will be if displayed in a specific font, size,
and style. Esto se hace mediante un llamado FontMetrics clase, que informa sobre el
tamaño de una línea de texto se si aparecen en una fuente específica, el tamaño y estilo. The
following statements create a object and set up a object that is linked to it: Las siguientes
sentencias crean un objeto Font y crear un objeto FontMetrics que está vinculado a la
misma:

Font f = new Font(fontName, Font.BOLD, fontSize); Font f =


new Font (fontName, Font.Bold, fontSize);
FontMetrics fm = getFontMetrics(f); FontMetrics fm =
getFontMetrics (f);

The object is used as an argument to the method. El objeto Font se utiliza como un
argumento a la getFontMetrics () método. Once you create the object, you can use two
of its methods to help you determine how to center a line of text in that font. Una vez
creado el objeto FontMetrics, puede utilizar dos de sus métodos para ayudar a determinar
la forma del centro de una línea de texto en esa fuente. These methods are , which indicates
how wide the text will be, and , which reveals how tall anything in the font will be. Estos
métodos son stringWidth (), que indica el ancho del texto será, y getHeight (), que
revela la altura de cualquier cosa en el tipo de letra será. In the applet you're going to
create, the following statements use these methods: En el applet Panamericana que va a
crear, las siguientes declaraciones utilizar estos métodos:

int xStart = (size().width - fm.stringWidth(text)) / 2;


xStart int =). ancho - / fm.stringWidth ((texto)) 2 tamaño
(;
int yStart = size().height/2 + fm.getHeight()/4; yStart
int = size () 4. altura / 2 + fm.getHeight () /;
offscreen.drawString(text, xStart, yStart);
offscreen.drawString (texto, xStart, yStart);

The and statements are the dimensions of the applet window itself. El tamaño ().
Anchura y tamaño (). Declaraciones altura son las dimensiones de la ventana del applet
en sí. By using these statements with the methods, the program can determine the right
location for the text. Mediante el uso de estas declaraciones con los métodos FontMetrics,
el programa puede determinar la ubicación adecuada para el texto.

Figure 23.1 shows the applet with a line of text centered in the applet window. Figura 23.1
muestra el applet Pan con una línea de texto centrado en la ventana del applet. It's a little
harder to distinguish in black and white, but the text is drawn twice--once in black and
again in white. Es un poco más difíciles de distinguir en blanco y negro, pero el texto se
dibuja dos veces - una en negro y otra vez en blanco. The text is drawn at a slightly
different place the second time, as shown in the following statement: El texto se redacta en
un lugar un poco diferente la segunda vez, como se muestra en la siguiente declaración:

offscreen.drawString(text, xStart-2, yStart-2);


offscreen.drawString (texto, xStart-2, yStart-2);

This statement creates a shadow effect that makes the text easier to see over the
background. Esta sentencia crea un efecto de sombra que hace el texto más fácil de ver
sobre el fondo.

Figura 23.1. The output of the applet running on the Web page . La salida del applet se
ejecuta en el Pan Pan.html página Web.

Workshop: Drawing Images Over a Screens Edges Taller: Las imágenes de dibujo
Durante un Bordes Pantallas
To create the effect of an image panning from right to left, the applet takes advantage of
the way images are displayed with Java. Para crear el efecto de una imagen panorámica de
derecha a izquierda, el applet Pan se aprovecha de la forma se muestran las imágenes con
Java. Before taking a look at this applet, you should get running. Antes de tomar un vistazo
a este subprograma, usted debe conseguir pan en ejecución. Create a new file in your word
processor called , and enter Listing 23.1 into the file. Crear un nuevo archivo en el
procesador de textos llamado Pan.java, y entre 23,1 venta en el archivo. Save it when
you're done. Guardar cuando hayas terminado.

Listing 23.1. Listado de 23.1. The full text of Pan.java. El texto completo de Pan.java.
1: import java.awt.*; 2: 3: public class Pan extends
java.applet.Applet implements Runnable { 4: Thread runner;
5: Image back, fore, workspace; 6: Graphics offscreen; 7:
String text; 8: String fontName; 9: int fontSize = 24; 10:
int x1 = 0; 11: int x2; 12: 13: public void init() { 14:
workspace = createImage(size().width, size().height); 15:
offscreen = workspace.getGraphics(); 16: // get parameters
17: String imageBack = getParameter("background"); 18: if
(imageBack != null) 19: back = getImage(getDocumentBase(),
imageBack); 20: String imageFore =
getParameter("foreground"); 21: if (imageFore != null) 22:
fore = getImage(getDocumentBase(), imageFore); 23: x2 =
size().width; 24: text = getParameter("text"); 25: fontName
= getParameter("font"); 26: if (fontName == null) 27:
fontName = "Arial"; 28: String param =
getParameter("fontsize"); 29: if (param != null) 30:
fontSize = Integer.parseInt("0" + param); 31: } 32: 33:
public void start() { 34: if (runner == null) { 35: runner
= new Thread(this); 36: runner.start(); 37: } 38: } 39: 40:
public void stop() { 41: if (runner != null) { 42:
runner.stop(); 43: runner = null; 44: } 45: } 46: 47:
public void run() { 48: while (true) { 49: repaint(); 50:
try { Thread.sleep(200); } 51: catch (InterruptedException
e) {} 52: x1 = x1 - 1; 53: x2 = x2 - 1; 54: if (x1 <=
(size().width * -1)) 55: x1 = size().width; 56: if (x2 <=
(size().width * -1)) 57: x2 = size().width; 58: } 59: } 60:
61: public void paint(Graphics screen) { 62:
offscreen.drawImage(back, x1, 0, null); 63:
offscreen.drawImage(back, x2, 0, null); 64: if (fore !=
null) 65: offscreen.drawImage(fore, 0, 0, null); 66: if
(text != null) { 67: offscreen.setColor(Color.black); 68:
Font f = new Font(fontName, Font.BOLD, fontSize); 69:
FontMetrics fm = getFontMetrics(f); 70:
offscreen.setFont(f); 71: int xStart = (size().width -
fm.stringWidth(text)) / 2; 72: int yStart = size().height/2
+ fm.getHeight()/4; 73: offscreen.drawString(text, xStart,
yStart); 74: offscreen.setColor(Color.white); 75:
offscreen.drawString(text, xStart-2, yStart-2); 76: } 77:
screen.drawImage(workspace, 0, 0, this); 78: } 79: 80:
public void update(Graphics screen) { 81: paint(screen);
82: } 1: import java.awt .*; 2: 3: public class Pan
extiende java.applet.Applet implementa Runnable {4:
corredor Hilo; 5: Imagen de la espalda, primer plano,
espacio de trabajo; 6: fuera de la pantalla de gráficos; 7:
String texto; 8 : String: fontName, 9 fontSize int = 24;
10: int x1 = 0; 11: int x2, 12: 13: public void init ()
{14: espacio de trabajo = createImage (size ().. ancho, el
tamaño (altura) ), 15: = workspace.getGraphics fuera de la
pantalla (); 16: / / obtener los parámetros 17: imageBack
String getParameter = ("fondo"); 18: (imageBack! if = null)
19: de vuelta = getImage (getDocumentBase (), imageBack );
20: imageFore String getParameter = ("primer plano"); 21:
if (imageFore (! = null) 22: primer plano = getImage
(getDocumentBase), imageFore); 23: = size ().: x2 ancho, 24
= text getParameter ("texto"); 25: fontName = getParameter
("fuente"); 26: if (fontName == null) 27: fontName =
"Arial", 28: String param = getParameter ("tamaño del
texto"); 29: si (param nula! =) 30: fontSize =
Integer.parseInt ("0" + param); 31:} 32:: 34 públicos: 33
sin efecto start () {if (corredor == null) {35: corredor =
new Thread (esto); 36: runner.start (); 37:} 38:} 39:: 41
públicos: 40 sin efecto stop () {if (corredor = null!) {42:
runner.stop (); 43: corredor = nulo; 44:} 45:} 46: 47:
public void run () {48: while (true) {49: repaint (); 50:
try {Thread.Sleep (200);} 51: catch (InterruptedException
e) {} 52: x1 = x1 - 1, 53: x2 = x2 - 1, 54: 55 (= (size ().
ancho x 1 <* -1)): x1 = size (). si el ancho, 56: if ( x2
<= (size () -1. ancho *)) 57: x2 = size ():. ancho; 58}
59:} 60:: 62 públicos: 61 void (pintura gráfica de la
pantalla) {offscreen.drawImage (espalda, x1, 0, null); 63:
offscreen.drawImage (espalda, x2, 0, null); 64: if (primer
plano: =! nula) 65: offscreen.drawImage (primer plano, 0,
0, null); 66 si ( ! text = null) {67: offscreen.setColor
(Color.Black); 68: Font f = new Font (fontName, Font.Bold,
fontSize); 69: FontMetrics fm getFontMetrics = (f); 70:
offscreen.setFont ( f); 71: xStart int = (size ():. width -
fm.stringWidth (texto)) / 2, 72 yStart int = size () fuera
de la pantalla. altura / 2 + fm.getHeight () / 4, 73:.
drawString (texto, xStart, yStart); 74: offscreen.setColor
(Color.white); 75: offscreen.drawString (texto, xStart-2,
yStart-2); 76:} 77: screen.drawImage (espacio de trabajo,
0, 0, este); 78:} 79: 80: public void update (pantalla de
gráficos) {81: pintura (pantalla); 82:} 83:}

Compile this file with the compiler tool, and then return to the word processor to create a
Web page that contains the applet. Compilar este archivo con la herramienta del
compilador javac, y luego regresar al procesador de textos para crear una página Web que
contiene el applet Panamericana. Enter Listing 23.2 and save it as . Introduzca Listado
23.2 y guárdelo como Pan.html. Note that the and attributes of the tag should be the
same dimensions as the background image to achieve the best results. Tenga en cuenta que
la anchura y la altura de los atributos de la etiqueta <APPLET> debe ser las mismas
dimensiones que la imagen de fondo para lograr los mejores resultados.

Listing 23.2. Listado de 23.2. The full text of Pan.html. El texto completo de Pan.html.

1: <applet code="Pan.class" width=460 height=43> 1:


<applet code="Pan.class" width=460 height=43>
2: <param name="background" value="patch.gif"> 2:
name="background" <param value="patch.gif">
3: <param name="font" value="Helvetica"> 3: name="font"
<param value="Helvetica">
4: <param name="fontsize" value="25"> 4: name="fontsize"
<param value="25">
5: <param name="text" value="FRED'S APPETITE
SUPPRESSANTS"> 5: <param name="text" value="FRED'S APETITO
SUPPRESSANTS">
6: </ applet>

Before you can see this applet running on a page, you need to put a copy of the image file
in the same directory as . Para poder ver este applet se ejecuta en una página, es necesario
poner una copia de la patch.gif archivo de imagen en el mismo directorio que Pan.html.
You can find this file on the book's CD-ROM in the directory. Usted puede encontrar este
archivo en el libro de los CD-ROM en el directorio Win95nt4/Book/Source/Hour23. You
also can retrieve a copy from the book's official Web site at . También puede obtener una
copia del sitio web oficial del libro en http://www.prefect.com/java24 . Take the link
from the site's front page labeled , and you'll be able to download . Tome el enlace desde
la primera página en el sitio marcado 23 horas de imágenes en movimiento, y usted
será capaz de descargar patch.gif. Get a copy of two other image files called and also to
save time later. Obtenga una copia de dos archivos de imagen y otro llamado
samsback.gif samslogo.gif también para ahorrar tiempo después.

When you use to load this Web page, you will see the banner shown in Figure 23.1.
Cuando se utiliza appletviewer cargar esta página web, podrás ver Fred Apetito la
bandera Supresores muestra en la Figura 23.1. No foreground element is specified on the
page, so the text appears over a moving background. Ningún elemento de primer plano se
especifica en la página, por lo que el texto aparece sobre un fondo en movimiento.

By using parameters to load all images and text, the applet is able to vary its performance
greatly. Mediante el uso de parámetros para cargar todas las imágenes y el texto, el applet
Pan es capaz de variar su rendimiento en gran medida. You can create a new Web page by
using different images and different parameters. Puede crear una nueva página web con
diferentes imágenes y diferentes parámetros. Return to your word processor and create a
new file called . Regreso a su procesador de textos y crear un nuevo archivo llamado
Sams.html. Enter the text of Listing 23.3 and save the file. Introduzca el texto del listado
23.3 y guardar el archivo.

Listing 23.3. Listado de 23.3. The full text of Sams.html. El texto completo de Sams.html.

1: <applet code="Pan.class" width=229 height=166> 1:


<applet code="Pan.class" width=229 height=166>
2: <param name="background" value="samsback.gif"> 2:
name="background" <param value="samsback.gif">
3: <param name="foreground" value="samslogo.gif"> 3:
name="foreground" <param value="samslogo.gif">
4: </ applet>

As with the previous example, you need to copy some image files before loading this Web
page into . Al igual que con el ejemplo anterior, es necesario copiar algunos archivos de
imagen antes de cargar esta página Web en appletviewer. The files are and . Los
archivos se samsback.gif y samslogo.gif. As shown in Figure 23.2, this applet shows a
moving background underneath a static logo of Sams.net Publishing. Como se muestra en
la Figura 23.2, este applet muestra un fondo en movimiento debajo de un logotipo estático
de Sams.net publicación. The Sams logo makes use of transparency so that the background
image can be seen. El logotipo de Sams hace uso de la transparencia para que la imagen de
fondo se puede ver.
The panning effect used by this applet is possible because of the way the method can be
drawn to off-screen coordinates. El efecto panorámico utilizado por este subprograma es
posible debido a la forma en que drawImage () puede ser atraído por fuera de las
coordenadas de la pantalla. Normally, when you draw an image to an applet window or a
workspace, the (x, y) coordinates that you specify are within the display area of the
program. Normalmente, cuando se dibuja una imagen a una ventana del applet o un espacio
de trabajo, la (x, y) las coordenadas que especifique se encuentran dentro del área de
visualización del programa. Otherwise, the graphics can't be seen. De lo contrario, los
gráficos no se pueden ver. However, there's no prohibition against drawing to coordinates
that make most of an image appear off-screen. Sin embargo, no hay prohibición de dibujo a
las coordenadas que hacen que la mayor parte de la imagen aparecen fuera de la pantalla.
The method will display the portion of the image that does appear on-screen and disregard
the rest. El método drawImage () se mostrará la porción de la imagen que aparece en la
pantalla y el desprecio de los demás.

Figura 23.2. The output of the applet running on the Web page . La salida del applet se
ejecuta en el Pan Sams.html página Web.

By drawing the background image twice at different positions, the program makes the
image seem to move. Al elaborar la imagen de fondo dos veces en diferentes posiciones, el
programa Pan hace que la imagen parece moverse. The exact positions of the images vary
as the program runs, which creates the animation effect, but they always are shown right
next to each other. La posición exacta de las imágenes varían en cuanto se ejecuta el
programa, que crea el efecto de animación, pero siempre se muestra a la derecha junto a la
otra. Figure 23.3 shows how this happens with the page. Figura 23.3 muestra cómo esto
sucede con la página Sams.html. Black borders have been drawn around the background
image so that you can see that it is being drawn twice. fronteras Negro se han elaborado en
torno a la imagen de fondo, para que pueda ver que se está elaborando dos veces. The thick
black border indicates the visible display area of the applet--everything outside of it would
not be seen. El borde negro grueso indica el área de la pantalla visible del applet - fuera de
todo lo que no sería visto.

Figura 23.3. Two copies of the background image partially displayed in the applet
window. Dos copias de la imagen de fondo en parte aparecen en la ventana del applet.

The applet uses the integer variables and to determine the two x coordinates where the
background should be drawn. El applet Pan utiliza las variables de número entero X1 y X2
para determinar las dos coordenadas x, donde el fondo debe ser establecido. The images do
not move up and down, so no y coordinates are needed. Las imágenes no se mueven arriba
y abajo, así que no hay coordenadas son necesarios. The variable begins with the value of
0, and starts out at the width of the applet: 229. La variable x1 comienza con el valor de 0,
y x2 se inicia en la anchura del applet: 229. The first time that the images are displayed, one
copy will be shown at (0,0), filling the entire window, and the other will begin at (229,0),
one pixel off the right edge. La primera vez que las imágenes se muestran, una copia se
muestra en (0,0), llenar toda la ventana, y el otro comenzará a las (229,0), un píxel del
borde derecho.

In Lines 52-53 of the program, both and are reduced by 1. En las líneas 52 a 53 del
programa, tanto x1 y x2 se reducen en 1. When the method is called next, each image is
displayed one pixel to the left of its last position. Cuando el repaint () se llama al
método siguiente, se muestra cada imagen un pixel a la izquierda de su última posición.
Lines 54-56 make sure that neither of the images goes so far to the left that none of it is
displayed. Líneas 54-56 asegurarse de que ninguna de las imágenes va tan lejos a la
izquierda que nada de esto es que aparecen. If the image moves too far to the left, the x
coordinate is set to the width of the applet. Si la imagen se mueve demasiado a la izquierda,
la coordenada x se ajusta a la anchura del applet.

Summary Resumen
The applet is an example of producing an interesting visual effect with a few lines of
programming. El applet Pan es un ejemplo de producir un efecto visual interesante con
unas pocas líneas de programación. Most of the statements in the program are used to load
parameters, store images, and handle the display of nonmoving graphics and text. La
mayoría de los estados en el programa se utiliza para cargar los parámetros, almacenar las
imágenes, y manejar la pantalla de la actora de gráficos y texto. Less than a dozen lines
control the values of and , and these are all that's needed to move the two copies of the
background image and produce the animation. Menos de una docena de líneas de control de
los valores de x1 y x2, y estos son todos los que se necesita para mover las dos copias de la
imagen de fondo y producir la animación.

As you create your own programs and start looking at the programs that others make
available on the World Wide Web, you'll pick up more of these tricks. A medida que crea
sus propios programas y comenzar a mirar los programas que otros hacen disponibles en la
World Wide Web, usted va a retomar más de estos trucos. Many of them will probably be
used more for the grown-up version of show-and-tell--the home page--than any higher
purpose. Muchos de ellos probablemente se usa más para la versión adulta de mostrar y
decir - la página de inicio - que cualquier otro propósito más elevado.

However, you might find some practical uses for these programs in unexpected places. Sin
embargo, es posible encontrar algunos de los usos prácticos de estos programas en lugares
inesperados. Using some of the same logic that was needed for the applet, you could write
an applet that displays a small section of a large map and enables users to interactively pan
to other places on the map. El uso de algunos de la misma lógica que se necesitaba para el
subprograma Pan, podría escribir un applet que muestra una pequeña sección de un mapa
grande y permite a los usuarios para desplazarse de forma interactiva a otros lugares en el
mapa. It isn't an achievement on par with the polio vaccine or interleague play in Major
League Baseball, but a map applet of that kind could be useful to many people browsing
the World Wide Web. No es un logro a la par con la vacuna de la polio o el juego de
interligas en las Grandes Ligas, pero un applet de mapa de ese tipo podría ser útil para
navegar por muchas personas la World Wide Web. Because it works fully in conjunction
with Web pages, Java makes some types of information more accessible than they would be
otherwise. Porque funciona plenamente en relación con las páginas Web, Java hace que
algunos tipos de información más accesible de lo que serían de otra manera. And that's
something to get animated about. Y eso es algo para animación sobre.

Q&A Q & A
Q What is the update() method accomplishing in the Pan applet? Q ¿Qué es la
actualización () el cumplimiento de método en el applet Pan?

A This method is included in the applet to override its existing behavior. Un método Esto
está incluido en el subprograma para anular su comportamiento actual. The method
automatically is called each time the screen needs to be redisplayed, either due to a
statement or some other cause. El método update () se llama automáticamente cada vez
que la pantalla tiene que ser vuelve a mostrar, ya sea debido a un repintado () estado
de cuenta o alguna otra causa. Normally, clears the screen by filling it with the
background color, and then calls the method. Normalmente, update () borra la
pantalla, llenando con el color de fondo, y luego llama al método paint (). This screen-
clearing causes a large amount of flickering in an animation program, so is overridden to
prevent it from occurring. Esta pantalla de remoción de las causas de una gran cantidad de
parpadeo en un programa de animación, así que update () se reemplaza para evitar que
ocurra.

Q None of the graphics programs that I use has a feature for transparency in .GIF files. Q
Ninguno de los programas gráficos que uso tiene una característica de la transparencia
en los archivos. GIF. How is this established for an image such as samslogo.gif? ¿Cómo se
establece una imagen como samslogo.gif?

A Transparency was introduced with a version of the file format called . Un Transparencia
fue presentado con una versión de. GIF formato de archivo llamado 89a. In order to
use it, you must find a graphics program that can load, edit, and save files. Con el fin de
usarlo, usted debe encontrar un programa de gráficos que puede cargar, editar y
guardar. GIF 89a archivos. If you don't have one of these programs and you save a
file, you will wipe out its transparency information. Si usted no tiene uno de estos
programas y guardar un archivo. Archivo GIF, que acabará con su información de
transparencia.
Quiz Quiz
Don't pan past this section of the book without testing your know-how by answering the
following questions. No bandeja pasado esta sección del libro, sin pruebas de sus
habilidades al contestar las siguientes preguntas.

Questions Preguntas

1. Why are threads helpful in controlling an animated program in Java? 1. ¿Por qué son
útiles las discusiones en el control de un programa de animación en Java?

(a) They give other programs that are running more time to operate. (A) Le dan otros
programas que se ejecutan más tiempo para operar.
(b) You can use the method to pause between screen updates. (B) Usted puede utilizar el
método Thread.Sleep para hacer una pausa entre las actualizaciones de pantalla.
(c) Loop statements don't work with animation. (C) Las sentencias de bucle no funcionan
con la animación.

2. Why is a object sent to the method of an applet? 2. ¿Por qué es un objeto Graphics
enviado a la pintura () de un applet?

(a) This object contains the necessary information to display something on-screen or on a
component. (A) Este objeto contiene la información necesaria para mostrar algo en
pantalla o en un componente.
(b) The method was set up to take an argument. (B) El método fue creado para tener un
argumento.
(c) The object signifies that graphics will be used in the method. (C) El objeto significa que
los gráficos serán utilizados en el método.

3. What method of the class is used to convert a string into an integer value? 3. ¿Qué
método de la clase entero se utiliza para convertir una cadena en un valor entero?

(a) (A) getInt ()


(b) (B) la carga ()
(c) (C) parseInt ()

Answers Respuestas

1. b. 1. B. Threads have the built-in ability to start, stop, and pause--abilities that
correspond well with what an animation program needs to do as it runs. Las discusiones se
han incorporado en la capacidad para iniciar, detener y pausar - habilidades que se
corresponden bien con lo que un programa de animación tiene que hacer ya que se
ejecuta.

2. a. 2. A. The methods of the object must be used to display text, polygons, and image
files on-screen. Los métodos del objeto Graphics se debe utilizar para mostrar texto,
polígonos, y archivos de imagen en pantalla.
3. c. 3. C.

Activities Actividades
Unless you're ready to this hour's subject matter, do the following activities: A menos que
estés dispuesto a Pan en la materia esta hora, realizar las siguientes actividades:

 Add a parameter to the applet that causes the background image to move from left to
right instead of right to left. Agregar un parámetro para el subprograma Pan que hace que
la imagen de fondo para mover de izquierda a derecha en vez de derecha a izquierda.
 Using event-handling and listener classes, make it possible to switch the direction of the
animation by clicking the mouse on the applet window. Uso de control de eventos y clases
de oyente, sea posible cambiar la dirección de la animación Pan haciendo clic con el ratón
en la ventana del applet.

 24 horas
o Hacer que el conocimiento Sumar
 Una clase Cálculo
 Crear la interfaz
 Figura 24.1.
 Figura 24.2.
 Figura 24.3.
 Listado de 24.1. La primera mitad de MiniCalc.java.
 Responder a eventos de usuario
 Listado de 24.2. La última mitad del MiniCalc.java.
 Solución de problemas
 Probar el Programa
 Listado de 24.3. El texto completo de CalcApplet.java.
 Listado de 24.4. El texto completo de CalcApplet.html.
 Resumen
 Q&A
 Quiz
 Preguntas
 Respuestas
 Actividades

Hour 24 24 horas

Making Your Knowledge Add Up Hacer que el


conocimiento Sumar

Most of the programs you created during the first 20 hours of this book were short tutorials
intended to demonstrate a specific aspect of Java programming. La mayoría de los
programas que ha creado durante las primeras 20 horas de este libro se tutoriales cortos
destinados a demostrar un aspecto específico de la programación Java. These types of
programs can be useful when you're introduced to how a language works, but they also can
be instructive in developing more sophisticated programs. Este tipo de programas puede ser
útil cuando se está introducido en el funcionamiento de una lengua, pero también pueden
ser instructivos en el desarrollo de programas más sofisticados.

For the concluding hour of this 24-hour span, you'll create a Java class that works as a
simple calculator. Durante la hora final de este lapso de 24 horas, va a crear una clase Java
que funciona como una calculadora simple. This project gives you a chance to design a
graphical user interface, respond to user mouse clicks, and develop the calculator so that it
can be used in any Java applet or application. Este proyecto le da la oportunidad de diseñar
una interfaz gráfica de usuario, responder a los clics del ratón del usuario, y desarrollar la
calculadora para que pueda ser utilizado en cualquier applet o aplicación Java.

The following topics will be covered during this hour: Entre los temas que se tratarán
durante esta hora:

 Adding components to a window Adición de componentes a una ventana


 Arranging components with a layout manager Disposición de los componentes con un
controlador de distribución
 Putting one grid layout inside another Poner una cuadrícula de diseño dentro de otra
 Adding components to containers Adición de componentes a los contenedores
 Responding to action events En respuesta a eventos de acción
 Reading information from a text field Leyendo la información de un campo de texto
 Sending information to a text field Envío de información a un campo de texto
 Using your own classes in a Java program Utilizando sus propias clases en un programa
Java

A Calculating Class Una clase Cálculo


The project will be a simple calculator that can handle addition, subtraction, multiplication,
and division. El proyecto MiniCalc será una calculadora simple que puede manejar la
suma, resta, multiplicación y división. In addition to numeric buttons from 0 to 9, there will
be a clear button (C), a change sign key (+/-), and a decimal point key. Además de los
botones numéricos 0-9, habrá un botón de borrado (C), un cambio de signo (+/-), clave y
una tecla del punto decimal. Instead of creating the calculator as an applet, you will create it
as a class called that is a subclass of . En lugar de crear la calculadora como un applet, se
creará una clase llamada MiniCalc que es una subclase de la Subcomisión.

The advantage of making its own class is that you will be able to use it in other programs.
La ventaja de hacer MiniCalc su propia clase es que usted será capaz de utilizarlo en otros
programas. If you design the calculator as an applet, it will be difficult to use in other
programs without making major changes. Si el diseño de la calculadora como un applet,
será difícil de utilizar en otros programas sin hacer grandes cambios. Once you have the
class working the way that you want it to, using it in a new program is as easy as using any
other object. Una vez que usted tiene la clase MiniCalc de trabajo de la manera que usted
lo desea, su utilización en un nuevo programa es tan fácil como usar cualquier otro objeto.

The project can be broken down into the following five steps: El proyecto MiniCalc puede
dividirse en los siguientes cinco pasos:

1. Create the components that will make up the calculator interface. 1. Crear los
componentes que conforman la interfaz de la calculadora.

2. Put those components into containers and set them up to send out action events. 2.
Coloque los componentes en un recipiente y se pusieron a enviar eventos de acción.

3. Lay out those containers. 3. Coloque los recipientes.

4. Keep track of mouse clicks on the components. 4. Realizar un seguimiento de los clics
del ratón en los componentes.

5. Change the calculator display area based on which components were clicked. 5. Cambie
el área de pantalla de la calculadora a partir del cual los componentes se ha hecho clic.

Creating the Interface Crear la interfaz


The first thing to do is develop the user interface of the class. Lo primero que debe hacer es
desarrollar la interfaz de usuario de la clase MiniCalc. Figure 24.1 shows what the
calculator will look like when you're done. Figura 24.1 muestra lo que la calculadora se
parecerá cuando haya terminado. It's displayed at this point to give you a better feel for the
steps that you'll be taking to create it. Es que aparecen en este punto para darle una mejor
idea de las medidas que tiene intención de realizar para crearlo.

When you are trying to create an attractive user interface for a program, one of the best
layout managers to use is the class. Cuando usted está tratando de crear una atractiva
interfaz de usuario para un programa, uno de los mejores gestores de diseño a utilizar es la
clase GridLayout. This manager enables you to organize components into a grid. Este
gestor permite organizar los componentes en una rejilla. When you use , you decide how
many rows and columns the grid should have; each component in the grid is given the same
amount of space as the other components. Cuando se usa GridLayout, usted decide el
número de filas y columnas de la red deben tener, cada componente de la red se da la
misma cantidad de espacio que los otros componentes.

Figura 24.1. A calculator implemented as a Java class and displayed on an applet window.
Una calculadora implementa como una clase Java y que aparecen en una ventana del
applet.

The class uses to organize components into a grid with six rows and one column. La clase
GridLayout MiniCalc utiliza para organizar los componentes en una rejilla con seis filas y
una columna. Each of these components is a object. Cada uno de estos componentes es un
objeto del panel. Figure 24.2 shows this grid superimposed over a calculator so you can
see how it is arranged. La figura 24.2 muestra esta red superpuesta a una calculadora para
que pueda ver cómo se arregla. The objects have the names through . Los objetos del
panel tienen los nombres row1 través row6. When you add these objects with the
method, they automatically are given the same amount of space based on the layout
manager being used. Al agregar estos objetos con el Grupo método add (),
automáticamente se les da la misma cantidad de espacio basado en el controlador de
distribución que se utiliza.

Figura 24.2. Six objects arranged in horizontal rows. Seis objetos Panel se disponen en
filas horizontales.

These six objects will be subdivided into their own grids using their own objects. Estos
seis objetos Grupo se subdivide en sus propias redes utilizando sus propios objetos
GridLayout. Each will be organized as a grid four columns wide and one row tall. Cada
Grupo se organizará como una cuadrícula de cuatro columnas de ancho y una fila de altura.
When components are added to each , they will get the same amount of space within their
row. Cuando los componentes se añaden a cada Grupo, que tendrá la misma cantidad de
espacio dentro de sus filas. Figure 24.3 shows how the object is subdivided into a four-by-
one grid. Figura 24.3 muestra cómo el objeto row2 se subdivide en un por una rejilla de
cuatro. Note how each of the buttons has the same size because of the use of . Tenga en
cuenta cómo cada uno de los botones tiene el mismo tamaño, debido a la utilización de
GridLayout.

Figura 24.3. One of the rows subdivided into four vertical columns. Una de las filas
subdividido en cuatro columnas verticales.

Using objects is a good way to make part of a window follow one set of layout rules and
other parts work differently. El uso de objetos Panel es una buena manera de hacer parte de
una ventana, siga una serie de normas de diseño y otras partes funcionan de manera
diferente. If you had used only one class on this project, every component would have
exactly the same size--even the text field where answers are displayed. Si ha utilizado una
sola clase GridLayout en este proyecto, todos los componentes que tienen exactamente el
mismo tamaño - incluso el campo de texto donde las respuestas se muestran.

The first half of the class contains statements to create all of the user interface components
that will be used in the program. La primera mitad de la clase MiniCalc contiene
instrucciones para crear todos los componentes de la interfaz de usuario que se utilizará en
el programa. These statements are located right after the statement along with other
variables that are needed. Estas declaraciones se encuentra justo después de la instrucción
de clase, junto con otras variables que se necesitan. After all of the components have
been created, they will be added to the proper place. Después de todos los componentes han
sido creados, que se añadirá al lugar adecuado. The large objects shown as rows in Figure
24.1 will be added to the main window of itself. El gran panel de los objetos se muestran
como filas en la figura 24.1 se añadirá a la ventana principal de MiniCalc sí mismo. Every
other component will be added to one of these objects. Todos los demás componentes se
añadirá a uno de estos objetos Panel.

Create a new file in your word processor called . Crear un nuevo archivo en el procesador
de textos llamado MiniCalc.java. Enter Listing 24.1 and save the file. Introduzca Listado
24.1 y guardar el archivo.

Listing 24.1. Listado de 24.1. The first half of MiniCalc.java. La primera mitad de
MiniCalc.java.
1: import java.awt.*; 2: import java.awt.event.*; 3: 4:
public class MiniCalc extends Panel implements
ActionListener { 5: char operator = 0; 6: float storedValue
= 0; 7: boolean clearNext = false; 8: 9: TextField display
= new TextField(20); 10: Button key1 = new Button("1"); 11:
Button key2 = new Button("2"); 12: Button key3 = new
Button("3"); 13: Button key4 = new Button("4"); 14: Button
key5 = new Button("5"); 15: Button key6 = new Button("6");
16: Button key7 = new Button("7"); 17: Button key8 = new
Button("8"); 18: Button key9 = new Button("9"); 19: Button
key0 = new Button("0"); 20: Button add = new Button("+");
21: Button subtract = new Button("-"); 22: Button multiply
= new Button("*"); 23: Button divide = new Button("/"); 24:
Button equal = new Button("="); 25: Button decimal = new
Button("."); 26: Button plusminus = new Button("+/-"); 27:
Button clear = new Button("C"); 28: Canvas empty = new
Canvas(); 29: Panel row1 = new Panel(); 30: Panel row2 =
new Panel(); 31: Panel row3 = new Panel(); 32: Panel row4 =
new Panel(); 33: Panel row5 = new Panel(); 34: Panel row6 =
new Panel(); 35: 36: public MiniCalc() { 37: Font typeface
= new Font("Helvetica", Font.BOLD, 15); 38:
setFont(typeface); 39: setBackground(Color.gray); 40: 41:
GridLayout layout = new GridLayout(6, 1, 5, 5); 42:
this.setLayout(layout); 43: GridLayout grid = new
GridLayout(1, 4, 5, 5); 44: 45: row1.setLayout(grid); 46:
display.setBackground(Color.white); 47:
display.addActionListener(this); 48: row1.add(display); 49:
this.add(row1); 50: 51: row2.setLayout(grid); 52:
key7.addActionListener(this); 53: row2.add(key7); 54:
key8.addActionListener(this); 55: row2.add(key8); 56:
key9.addActionListener(this); 57: row2.add(key9); 58:
divide.addActionListener(this); 59: row2.add(divide); 60:
this.add(row2); 61: 62: row3.setLayout(grid); 63:
key4.addActionListener(this); 64: row3.add(key4); 65:
key5.addActionListener(this); 66: row3.add(key5); 67:
key6.addActionListener(this); 68: row3.add(key6); 69:
multiply.addActionListener(this); 70: row3.add(multiply);
71: this.add(row3); 72: 73: row4.setLayout(grid); 74:
key1.addActionListener(this); 75: row4.add(key1); 76:
key2.addActionListener(this); 77: row4.add(key2); 78:
key3.addActionListener(this); 79: row4.add(key3); 80:
subtract.addActionListener(this); 81: row4.add(subtract);
82: this.add(row4); 83: 84: row5.setLayout(grid); 85:
key0.addActionListener(this); 86: row5.add(key0); 87:
plusminus.addActionListener(this); 88: row5.add(plusminus);
89: decimal.addActionListener(this); 90: row5.add(decimal);
91: add.addActionListener(this); 92: row5.add(add); 93:
this.add(row5); 94: 95: row6.setLayout(grid); 96:
clear.addActionListener(this); 97: row6.add(clear); 98:
row6.add(empty); 99: row6.add(empty); 100:
equal.setEnabled(false); 101:
equal.addActionListener(this); 102: row6.add(equal); 103:
this.add(row6); 1: import java.awt .*; 2: java.awt.event
importación .*; 3: 4: public class MiniCalc extiende Grupo
implementa ActionListener {5: operador char = 0; 6: 7:
booleano clearNext flotador; storedValue 0 = = false; 8: 9:
TextField = new TextField pantalla (20), 10: El botón
clave1 = new Button ("1"); 11: Botón clave2 = new Button
("2"); 12: Botón Key3 = new Button ( "3"), 13: El botón
key4 = new Button ("4"); 14: Botón key5 = new Button ("5");
15: Botón key6 = new Button ("6"); 16: Botón key7 = new
Button ("7"); 17: Botón key8 = new Button ("8"); 18: Botón
key9 = new Button ("9"); 19: Botón Key0 = new Button ("0"),
20: El botón añadir = new ("+"); Botón 21: Botón de restar
= new botón ("-"); 22: Botón de multiplicar = new botón
("*"); 23: Botón de división = new ("/"); Botón 24: Botón
de igualdad = new ("="); Botón 25: decimal botón = new
("."); Botón 26: Plusminus botón = new botón ("+/-"); 27:
Botón claro = new Button ("C" ); 28: lienzo vacío = lienzo
nuevo (); 29: Panel de row1 = Grupo nuevo (); 30: Panel de
row2 = Grupo nuevo (); 31: Panel de row3 = Grupo nuevo ();
32: Panel de row4 = new Panel ( ); 33: Panel de row5 =
Grupo nuevo (); 34: Panel de row6 nuevo Panel = (); 35: 36:
MiniCalc público () {37: tipo de letra de fuente = new Font
("Helvetica", Font.Bold, 15); 38: setFont (tipo de letra);
39: setBackground (Color.gray); 40: 41: diseño GridLayout =
new GridLayout (6, 1, 5, 5); 42: this.setLayout (diseño);
43: red = new GridLayout GridLayout (1, 4, 5, 5); 44: 45:
row1.setLayout (red), 46: display.setBackground
(Color.white); 47: display.addActionListener (este); 48:
row1.add (pantalla) ; 49: this.add (row1); 50: 51:
row2.setLayout (red); 52: key7.addActionListener (este);
53: row2.add (key7); 54: key8.addActionListener (este); 55:
row2.add (key8); 56: key9.addActionListener (este); 57:
row2.add (key9); 58: divide.addActionListener (este); 59:
row2.add (dividir); 60: this.add (row2 ); 61: 62:
row3.setLayout (red); 63: key4.addActionListener (este);
64: row3.add (key4); 65: key5.addActionListener (este); 66:
row3.add (key5) 67; : key6.addActionListener (este); 68:
row3.add (key6); 69: multiply.addActionListener (este); 70:
row3.add (multiplicación); 71: this.add (row3); 72: 73:
row4. setLayout (red), 74: key1.addActionListener (este);
75: row4.add (clave1); 76: key2.addActionListener (este);
77: row4.add (clave2); 78: key3.addActionListener (este);
79: row4.add (Key3); 80: subtract.addActionListener (este);
81: row4.add (restar); 82: this.add (row4); 83: 84:
row5.setLayout (red); 85: Key0 . addActionListener (este);
86: row5.add (Key0); 87: plusminus.addActionListener
(este); 88: row5.add (Plusminus); 89:
decimal.addActionListener (este); 90: row5.add (decimal) ;
91: add.addActionListener (este); 92: row5.add (añadir);
93: this.add (row5); 94: 95: row6.setLayout (red); 96:
clear.addActionListener (este); 97: row6.add
(transparente); 98: row6.add (vacío); 99: row6.add (vacío);
100: equal.setEnabled (false); 101: equal.addActionListener
(este), 102: row6.add (igual ); 103: this.add (row6); 104:}

Lines 5-34 create several variables and numerous components--buttons, six panels, a text
field, and a canvas. Líneas 5-34 crear varias variables y numerosos componentes - botones,
paneles de seis, un campo de texto, y un lienzo. The constructor method in Lines 36-104
will be called whenever a program creates a object with a statement such as the following:
El método constructor MiniCalc () en las líneas 36-104 se llamará cada vez que un
programa crea un objeto MiniCalc con una declaración como la siguiente:

MiniCalc calculator = new MiniCalc(); calculadora MiniCalc


= new MiniCalc ();

The constructor method uses objects to define the way components will be arranged, first
for the entire window and then for each of the specific rows of the window. El método
constructor utiliza objetos GridLayout para definir los componentes de forma en que se
organizó, en primer lugar de la ventana MiniCalc todo y, a continuación de cada una de las
filas específicas de la ventana.

Before you add a component to a row, you must set it up to send out action events. Antes
de agregar un componente a una fila, se debe configurar para enviar eventos de acción.
These events enable the program to respond when a user interacts with the component--by
clicking a button, for example. Estos eventos que el programa pueda responder cuando un
usuario interactúa con el componente - haciendo clic en un botón, por ejemplo. You set up
these events by using the method of each component. Configurar estos eventos utilizando
el addActionListener () de cada componente.
The components are first added to each row, starting with . Los componentes se añaden por
primera vez para cada fila, comenzando con row1. When that's done, the entire row is
added to the window. Cuando haya terminado, toda la fila se agrega a la ventana
MiniCalc. This is all the code that's needed to create the user interface. Este es todo el
código que se necesita para crear la interfaz de usuario.

Responding to User Events Responder a eventos de usuario


To make the calculator calculate, you need to make the program respond to mouse clicks on
the buttons. Para hacer que la calculadora calcular, es necesario hacer que el programa
responde a los clics del ratón sobre los botones. Whenever a user clicks on a button that has
been set up as a listener to action events, the method automatically is called. Cada vez que
un usuario hace clic en un botón que se ha establecido como un oyente de eventos de
acción, el () método actionPerformed automáticamente se llama. Information about the
user's action is stored as an object, and the method responds to the action. Información
sobre el usuario de la acción se almacena como un objeto ActionEvent, y el
actionPerformed () método responde a la acción. All action events are received by the
method of itself. Todos los eventos de acción son recibidos por el () método
actionPerformed de MiniCalc sí mismo.

Return to your word processor and insert a blank line at the bottom of the file. Regreso a
su procesador de textos e insertar una línea en blanco en la parte inferior del archivo
MiniCalc.java. Continue by entering Listing 24.2, making sure to save the file when
you're done. Continuar introduciendo Listado de 24.2, asegurándose de guardar el archivo
cuando haya terminado.

Listing 24.2. Listado de 24.2. The last half of MiniCalc.java. La última mitad del
MiniCalc.java.
1: public void actionPerformed(ActionEvent event) { 2:
String keyHit = event.getActionCommand(); 3: if (keyHit ==
"+/-") { 4: float value = getValue(display.getText()); 5:
value *= -1; 6: clearDisplay(); 7: addToDisplay("" +
value); 8: } 9: else switch ( keyHit.charAt(0) ) { 10: case
`+': 11: case `-': 12: case `*': 13: case `/': 14:
equal.setEnabled(true); 15: add.setEnabled(false); 16:
subtract.setEnabled(false); 17: multiply.setEnabled(false);
18: divide.setEnabled(false); 19: storedValue =
getValue(display.getText()); 20: operator =
keyHit.charAt(0); 21: clearNext = true; 22: break; 23: case
`=': 24: equal.setEnabled(false); 25: add.setEnabled(true);
26: subtract.setEnabled(true); 27:
multiply.setEnabled(true); 28: divide.setEnabled(true); 29:
solveProblem(); 30: storedValue =
getValue(display.getText()); 31: operator = 0; 32:
clearNext = true; 33: break; 34: case `C': 35:
clearDisplay(); 36: operator = 0; 37: storedValue = (float)
0; 38: break; 39: default: 40: if (clearNext) { 41:
clearDisplay(); 42: clearNext = false; 43: } 44:
addToDisplay(keyHit); 45: } 46: } 47: 48: public void
solveProblem() { 49: float currentValue =
getValue(display.getText()); 50: switch (operator) { 51:
case `+': 52: storedValue += currentValue; 53: break; 54:
case `-': 55: storedValue -= currentValue; 56: break; 57:
case `*': 58: storedValue *= currentValue; 59: break; 60:
case `/': 61: if (currentValue != 0) 62: storedValue /=
currentValue; 63: else 64: storedValue = 0; 65: break;
66: } 67: clearDisplay(); 68: addToDisplay("" +
storedValue); 69: clearNext = true; 70: } 71: 72: public
void addToDisplay(String keyHit) { 73: String newText =
display.getText(); 74: if (keyHit == ".") { 75: if
(newText.indexOf(".") == -1) 76: newText += "."; 77: } else
78: newText += keyHit; 79: int newLength =
newText.length(); 80: display.setText(newText); 81: } 82:
83: public void clearDisplay() { 84: display.setText("");
85: } 86: 87: public float getValue(String argument) { 88:
if (argument.equals(".")) 89: argument = "0"; 90: Float f1
= Float.valueOf(argument); 91: return f1.floatValue();
92: } 1: public void actionPerformed (ActionEvent evento)
{2: keyHit String = event.getActionCommand (); 3: si (==
keyHit "+/-") {4: valor float = getValue (display.getText
()); 5 : valor *= -1; 6: clearDisplay (); 7: addToDisplay
("" + valor); 8:} 9: Interruptor más (keyHit.charAt (0))
{10: caso '+': 11: caso » - ': 12: caso' * ': 13: caso de
`/': 14: equal.setEnabled (true); 15: add.setEnabled
(false); 16: subtract.setEnabled (false); 17:
multiply.setEnabled ( false); 18: divide.setEnabled
(false); 19: storedValue = getValue (display.getText ());
20: operador = keyHit.charAt (0); 21: clearNext = true; 22:
descanso; 23: caso » = ': 24: equal.setEnabled (false); 25:
add.setEnabled (true); 26: subtract.setEnabled (true); 27:
multiply.setEnabled (true); 28: divide.setEnabled (true);
29: solveProblem (); 30: storedValue = getValue
(display.getText ()); 31: operador = 0; 32: clearNext =
true; 33: descanso; 34: caso "C": 35: clearDisplay (); 36:
operador = 0; 37: storedValue = (float) 0; 38: descanso;
39: por defecto: 40: if (clearNext) {41: clearDisplay ();
42: clearNext = false; 43:} 44: addToDisplay (keyHit);
45: } 46:} 47:: 49 públicos: 48 solveProblem vacío ()
{float CurrentValue = getValue (display.getText ()); 50:
switch (operador) {51: caso '+': 52: storedValue
CurrentValue + = 53; : break; 54: caso '-': 55: storedValue
-= CurrentValue; 56: descanso; 57: caso '*': 58:
storedValue *= CurrentValue; 59: descanso; 60: caso de `/
': 61: if ( CurrentValue: = 0) 62: storedValue = /
CurrentValue, 63 más 64: storedValue = 0; 65: descanso;
66:} 67: clearDisplay (); 68: addToDisplay ("" +
storedValue); 69: clearNext = true; 70:} 71: 72:
addToDisplay public void (keyHit String) {73: newText
String = display.getText (); 74: if (". keyHit ==") {75: if
(newText.indexOf (".") == -1) 76: newText + = "77".:} else
78: newText keyHit + = 79;: newLength int newText.length =
(); 80: display.setText (newText); 81:} 82: 83:
clearDisplay public void () {84: display.setText (""); 85:}
86: 87: getValue flotador público (argumento String) {88:
if (argument.equals (".")) 89: argumento = "0"; 90: Float
f1 = Float.valueOf (argumento); 91: f1.floatValue retorno
(); 92:} 93:}

The following statements from this part of the program might be unfamiliar to you: Las
siguientes declaraciones de esta parte del programa puede ser desconocido para usted:

 Line 2: This line calls the method of the object and stores the response in the variable .
Línea 2: Esta línea llama al getActionCommand () del objeto de evento y almacena la
respuesta en el keyHit variable de cadena. The value stored in this variable is the label
of the key that was clicked. El valor almacenado en esta variable es la etiqueta de la tecla
que se ha hecho clic.
 Line 9: This statement converts the value stored in to a single character before using it in
statements. Línea 9: Esta sentencia switch convierte el valor almacenado en keyHit a
un solo personaje antes de utilizarlo en caso de declaraciones. This conversion must be
done because can handle characters, but it cannot handle strings. Esta conversión se debe
hacer porque el caso puede manejar personajes, pero no puede manejar cadenas. The
method returns a single character at the position indicated by the argument. represents
the first character, the second, and so on. El charAt () devuelve un solo carácter en la
posición indicada por el argumento. 0 representa el primer carácter, 1 el segundo, y así
sucesivamente.
 Line 19: The variable keeps track of the first half of any operations. Línea 19: La variable
storedValue realiza un seguimiento de la primera mitad de todas las operaciones. For
example, if you're using the calculator to work out the equation 12 plus 10, would equal
12. Por ejemplo, si usted está utilizando la calculadora para calcular la ecuación 12 más 10,
storedValue sería igual a 12.
 Line 20: The variable, used here and many places elsewhere, stores the most recent
operator key that was pressed: +, -, *, or /. Línea 20: La variable del operador, que se
utiliza aquí y muchos otros lugares, las tiendas del operador principal más reciente que se
ha pulsado: +, - *,, o /. The variable has the value 0 when no operators have been pressed
or the current problem has been cleared out with the C or = keys. La variable tiene el valor
0 cuando no hay operadores que se haya pulsado o el problema actual se ha limpiado con
la C o las teclas =.
 Line 21: The Boolean variable indicates when the calculator display should be cleared out
after the next key is pressed. Línea 21: El clearNext variable booleana indica cuando la
pantalla de la calculadora debe ser limpiado después del día, se pulsa la tecla.
 Lines 74-76: These lines make sure that a user cannot enter more than one decimal point
on a number. Líneas 74-76: Estas líneas asegurarse de que un usuario no puede introducir
más de un punto decimal en un número.

Solving Problems Solución de problemas


Several methods have been created in the class to handle specific tasks. Varios métodos
han sido creados en la clase MiniCalc para manejar tareas específicas. The method in
Lines 48-70 is called whenever the calculator display should be updated with the answer to
a calculation. El solveProblem () en las líneas 48-70 se llama cada vez que la pantalla de
la calculadora debe estar actualizado con la respuesta a un cálculo. This occurs when the =
key is pressed. Esto ocurre cuando la tecla = es presionado. The method in Lines 72-81 is
used to add another digit to the number that is being shown in the calculator's display area.
El addToDisplay () en las líneas 72-81 se utiliza para añadir otro dígito del número que
se muestra en el área de visualización de la calculadora. The method in Lines 83-85 clears
out the calculator's display area so that the user can enter a new number. El clearDisplay
() en las líneas 83-85 borra la calculadora de visualización de la zona para que el usuario
puede introducir un nuevo número. The last special method is the method in Lines 87-92.
El método es la última especial getValue () en las líneas 87-92. This method returns a
value, as shown on Line 91. Este método devuelve un valor de coma flotante, como se
muestra en la línea 91. This method converts the text shown in the calculator's display
window into a floating-point number. Este método convierte el texto se muestra en la
ventana de la pantalla de la calculadora en un número de punto flotante.

Trying Out the Program Probar el Programa


Save and compile the class file. Guarde y compile el archivo de clase MiniCalc. Before
you can try it out, you need to create a object as a component in an applet and add it in the
same way any component would be added. Antes de probarlo, es necesario crear un objeto
MiniCalc como un componente en un applet y añade que de la misma manera habría
ningún componente adicional. Create a new file with your word processor and save it as .
Crear un nuevo archivo con su procesador de textos y guárdelo como CalcApplet.java.
Enter Listing 24.3 into the file. Introduzca Listado 24,3 en el archivo.

Listing 24.3. Listado de 24.3. The full text of CalcApplet.java. El texto completo de
CalcApplet.java.

1: import java.awt.*; 1: import java.awt .*;


2: 2:
3: public class CalcApplet extends java.applet.Applet {
3: public class CalcApplet extiende java.applet.Applet {
4: MiniCalc calc = new MiniCalc(); 4: calc MiniCalc nueva
MiniCalc = ();
5: 5:
6: public void init() { 6: public void init () {
7: setBackground(Color.gray); 7: setBackground
(Color.gray);
8: add(calc); 8: agregar (CALC);
9: } 9:}
10:}
As you can see, the applet doesn't need to do very much because the class does all of its
own work. Como puede ver, el applet no se necesita hacer mucho porque la clase MiniCalc
hace todo de su propio trabajo. Save and compile this file. Guardar y compilar este archivo.

To see the program on a Web page, create another file with the name . Para ver el
programa CalcApplet en una página Web, crear otro archivo con el nombre
CalcApplet.html. Enter Listing 24.4 into the file. Introduzca Listado 24,4 en el archivo.

Listing 24.4. Listado de 24.4. The full text of CalcApplet.html. El texto completo de
CalcApplet.html.
1: <applet code="CalcApplet.class" height=200 width=200>
1: <applet code="CalcApplet.class" height=200 width=200>
2: </ applet>

Use the tool or a Web browser that can handle Java, and take a look at the page. Utilice la
herramienta appletviewer o un navegador Web que puede manejar Java, y echar un
vistazo a la página CalcApplet.html.

Summary Resumen
Once you've gotten the class to work in conjunction with an applet, take a long look over
the program to determine what's being done at each point in the program. Una vez que haya
recibido la clase MiniCalc para trabajar en conjunto con un applet, hacer una profunda
reflexión sobre el programa para determinar qué se está haciendo en cada punto en el
programa. The project is a good example of how graphical programs can be written with a
small amount of programming in Java. El proyecto MiniCalc es un buen ejemplo de cómo
los programas de gráfica se puede escribir con una pequeña cantidad de la programación en
Java. In less than 200 lines, you can implement a working calculator that handles the basic
mathematic operations. En menos de 200 líneas, se puede implementar una calculadora de
trabajo que se encarga de las operaciones matemáticas básicas.

The purpose of Teach Yourself Java 1.1 Programming in 24 Hours is to make you
comfortable with the concepts of programming and confident in your ability to write your
own applets and applications. El propósito de Aprendiendo Java 1.1 de programación en 24
horas es hacer que usted se sienta cómodo con los conceptos de la programación y la
confianza en su capacidad para escribir sus propios applets y aplicaciones. Java has an
approach that is somewhat difficult to master. Java tiene un enfoque que es algo difícil de
dominar. (Feel free to scratch out the word "somewhat" in the previous sentence if it's a
gross misstatement of the truth.) (No dude en cero la palabra "algo" en la frase anterior si se
trata de una inexactitud grave de la verdad.)
If it's any consolation, as you build experience in Java, you're building experience that will
be increasingly relevant in the coming years. Si te sirve de consuelo, ya que adquirir
experiencia en Java, está la construcción de la experiencia que será cada vez más relevancia
en los próximos años. If you become knowledgeable in object-oriented programming and
distributed network computing, the program could be useful--there's no better afternoon for
a millionaire than projecting the rate of return on your no-load mutual funds using a Java
program you wrote! Si usted se convierte en conocimiento en programación orientada a
objetos y la red de computación distribuida, el programa MiniCalc podría ser útil - por la
tarde no hay mejor para un millonario de la proyección de la tasa de rendimiento de la
carga de fondos de inversión-, no utilizar un programa de Java que escribió!

You ought to read the appendixes to find out about this book's Web site, other Java books
from Sams.net, and other useful information. Usted debe leer el expediente de anexos a
conocer el sitio Web de este libro, otros libros de Java desde Sams.net, y otra información
útil. Even if you don't, there's one last bit of bad news to deliver. Incluso si no lo hace, hay
una última parte de una mala noticia para entregar. Your 24 hours are up. Sus 24 horas del
reloj.

At the conclusion of this hour, you are contractually obligated to learn no more about Java
programming. Al término de esta hora, que están obligados por contrato a aprender nada
más acerca de la programación Java. You cannot use Internet discussion groups such as to
talk to other people who share your skills. No se puede utilizar grupos de discusión de
Internet como comp.lang.java.misc hablar con otras personas que comparten sus
habilidades. You must not look for Java user groups in your area. Usted no debe mirar para
grupos de usuarios de Java en su área. You cannot search employment World Wide Web
sites such as for companies that seek Java programmers. No es posible buscar empleo
World Wide Web como http://www.careerpath.com para las empresas que buscan
programadores de Java. Under no circumstances should you send electronic mail to the
author of this book at with questions, comments, or criticisms in regard to the past 24
hours. Bajo ninguna circunstancia debe enviar correo electrónico al autor de este libro en
rogers@prefect.com con preguntas, comentarios o críticas en lo que respecta a las últimas
24 horas.

The only legally permissible way for you to continue building your skills as a Java
programmer is to read Teach Yourself Java 1.1 Programming in 21 Days or one of the other
excellent Java-related books from Sams.net Publishing. La única manera legalmente
permitida para que usted pueda seguir construyendo sus habilidades como programador de
Java es leer Aprendiendo Java 1.1 de programación en 21 días o uno de los otros excelentes
libros relacionados con Java de Sams.net publicación. If you are caught violating these
prohibitions and learning more about Java without spending another cent of your money,
there's really only one thing left to be said... Si son capturados en violación de estas
prohibiciones y aprender más acerca de Java sin tener que gastar un centavo de su dinero,
no hay realmente sólo queda una cosa por decir ...

I lied. Mentí. There's no current law in any jurisdiction that forces you to Teach Yourself
Everything only by reading our books. No hay ninguna ley vigente en cualquier
jurisdicción que le obliga a enseñar todo usted mismo sólo mediante la lectura de nuestros
libros. You are free to learn freely. Usted es libre de aprender libremente. My apologies...if
I sell enough copies of this book, my name is entered into a drawing with other top
Sams.net authors to win special prizes. Mis disculpas ... si vendo suficientes copias de este
libro, mi nombre es ingresado en un dibujo con otros autores Sams.net arriba para ganar
premios especiales.

My heart's set on a banana-yellow Schwinn Sting-Ray bicycle. Mi corazón está situado en


una banana amarilla bicicletas Schwinn Sting-Ray.

--Rogers Cadenhead - Rogers Cadenhead

Q&A Q & A
Q Does a layout manager have to be specified for a program? Q ¿Un controlador de
distribución tienen que ser especificados para un programa?

A If one is not used, components will be arranged on an applet window or other container
in the same way words are typed onto a page--left to right until there's no more room and
then down to the next line. A Si uno no se utiliza, los componentes se situarán en una
ventana del applet o en otros recipientes de la misma manera las palabras se escriben en
una página - de izquierda a derecha hasta que no hay más espacio y, después, a la
siguiente línea. This occurs because the default layout manager, , is used if no other
manager is specified. Esto se produce porque el controlador de distribución por defecto,
FlowLayout, se utiliza si no se especifica otro gerente.

Q The CalcApplet program looks different on my version of Netscape Navigator than it


does on the appletviewer tool. Q El programa CalcApplet se ve diferente en mi versión
de Netscape Navigator que lo hace en la herramienta appletviewer. The most noticeable
differences are the C and = buttons, which are thinner on Navigator. Las diferencias más
notables son la C y = botones, que son más delgadas en Navigator. Why is this? ¿Por qué
es esto?

A Because Java is a language that is presented on many different platforms, some


graphical elements will vary depending on the software or operating system being used.
Una Debido a que Java es un lenguaje que se presenta en muchas plataformas diferentes,
algunos elementos gráficos puede variar dependiendo del software o sistema operativo
que se utilice. Your programs should be presentable on any implementation of Java, but if
you're creating a complicated program that arranges numerous components and other
visual elements, it's worthwhile to test it on several different systems and Web browsers.
Sus programas deben estar presentable en cualquier aplicación de Java, pero si va a crear
un complicado programa que organiza numerosos componentes y otros elementos
visuales, vale la pena probarlo en diferentes sistemas y navegadores Web.

Quiz Quiz
To calculate your level of knowledge about this hour's subjects, answer the following
questions. Para calcular su nivel de conocimiento sobre temas de esta hora, conteste las
siguientes preguntas.

Questions Preguntas

1. What type of class do you use to specify how components will be arranged in a
program? 1. ¿Qué tipo de clase que utiliza para especificar cómo los componentes se
pueden organizar en un programa?

(a) (A) de arreglos


(b) (B) Compositor
(c) (C) LayoutManager

2. What type of method is used to set up all the variables and components that need to be
displayed with the class? 2. ¿Qué método se utiliza el tipo de establecer todas las
variables y los componentes que necesitan que se mostrará en la clase MiniCalc?

(a) an method (A) un método init ()


(b) a constructor method (B) un método constructor
(c) a destructor method (C) un método destructor

3. What type of variable is used to store calculator results? 3. ¿Qué tipo de variable se
utiliza para almacenar los resultados de la calculadora?

(a) (A) String


(b) (B) int
(c) (C) del flotador

Answers Respuestas

1. c. 1. C. You can use layout styles such as , , and . Puede utilizar los estilos de diseño,
como GridLayout, BorderLayout y GridBagLayout.

2. b. 2. B. Any method that is called with a statement during variable creation is a


constructor method. Cualquier método que se llama con una nueva declaración durante
la creación de variable es un método constructor. You can have more than one
constructor if the number and type of arguments used with each constructor are different.
Usted puede tener más de un constructor, si el número y tipo de argumentos utilizados
con cada constructor son diferentes.

3. c. 3. C. Because there's a decimal key on a calculator, you must use the variable type
instead of some other numeric type such as . Porque no hay una clave decimal en una
calculadora, debe utilizar el tipo de variable de tipo float en lugar de algún otro tipo
numérico como int.

Activities Actividades
If you'd like to teach yourself even more Java programming in hours 24 and beyond, do the
following activities: Si desea usted enseñar aún más la programación de Java en 24 horas y
fuera de ella, realizar las siguientes actividades:

 Add a square root button to the class that will display the square root of the currently
displayed number. Agregue un botón de raíz cuadrada de la clase MiniCalc que se
mostrará la raíz cuadrada del número que aparecen en la actualidad.
 Visit the Gamelan Web site at to see some other calculators that have been written using
Java. Visite el sitio Web Gamelan en http://www.gamelan.com para ver algunas otras
calculadoras que se han escrito utilizando Java. Look over any available source files and
compare them with the source file. Revise los archivos fuente disponible y compararlas
con el archivo de origen MiniCalc.

 Apéndice A
o A dónde ir desde aquí: Java Recursos
 Otros libros a tener en cuenta
 El sitio JavaSoft
 Otros Sitios Web en Java
 Los libros de Java Page
 Gamelanes Directorio de Java
 Applet de Java Calificación del Servicio
 JavaWorld Magazine
 Java Preguntas más frecuentes
 Java Grupos de noticias
 Oportunidades de Trabajo

Appendix A Apéndice A

Where to Go from Here: Java Resources A dónde ir


desde aquí: Java Recursos
Now that you have finished this book, you might be wondering where you can go to
improve your Java programming skills. Ahora que ha terminado este libro, puede que se
pregunte dónde puede ir para mejorar sus habilidades de programación Java. This appendix
lists some books, World Wide Web sites, Internet discussion groups, and other resources
you can use to expand your Java knowledge. Este apéndice enumera algunos de los libros,
los sitios Web, grupos de discusión en Internet y otros recursos que puede utilizar para
ampliar sus conocimientos de Java.

Other Books to Consider Otros libros a tener en cuenta


A worthwhile successor to this book is Teach Yourself Java 1.1 in 21 Days. Un sucesor que
vale la pena que este libro es Aprendiendo Java 1.1 en 21 Días. This book teaches Java to
people who have had an introduction to programming--either with another language, such
as Visual Basic, C, or C++, or a beginning Java book such as this one. Este libro enseña
Java para personas que han tenido una introducción a la programación - ya sea con otro
idioma, como Visual Basic, C o C + + o Java un comienzo libro como éste. Although some
of the material in Teach Yourself Java 1.1 in 21 Days will review what you have learned in
the past 24 hours of tutelage, the majority of the material will be new. Aunque algunos de
los materiales en Aprendiendo Java 1.1 en 21 días se revisa lo que han aprendido en las
últimas 24 horas de la tutela, la mayoría del material será nuevo. I highly recommended this
book as a follow-up to what you've learned here. Me recomienda este libro como un
seguimiento de lo que has aprendido aquí.

Sams.net Publishing is the leader in Java programming books, and there are numerous
books from Sams.net you should consider reading as you develop your skills. Sams.net
publicación es el líder en los libros de programación Java, y hay numerosos libros de
Sams.net usted debe considerar la lectura como a desarrollar sus habilidades. The following
list includes ISBN numbers, which will be needed at bookstores if they don't currently carry
the book you're looking for: La siguiente lista incluye los números de ISBN, que serán
necesarios en las librerías, si actualmente no llevar el libro que está buscando:

 Teach Yourself SunSoft Java WorkShop in 21 Days by Rogers Cadenhead, Laura Lemay, and
Charles Perkins . Enseñe a sí mismo SunSoft WorkShop de Java en 21 días por Rogers
Cadenhead, Lemay, Laura, Carlos y Perkins. ISBN: 1-57521-159-9. ISBN: 1-57521-159-9.
 Developing Intranet Applications with Java by Jerry Ablan, Rogers Cadenhead, and others .
Desarrollo de aplicaciones de Intranet con Java de Jerry Ablan, Rogers Cadenhead, entre
otros. ISBN: 1-57521-166-1. ISBN: 1-57521-166-1.
 Java Unleashed, 2nd Edition by Rogers Cadenhead, Michael Morrison, and others . Java
Unleashed, 2 ª edición de Rogers Cadenhead, Michael Morrison, entre otros. ISBN: 1-
57521-049-5. ISBN: 1-57521-049-5.
 Developing Professional Java Applets by KC Hopson and Stephen E. Ingram. ISBN: 1-57521-
083-5. Profesional applets de Java KC y Hopson Stephen Ingram. E.: Desarrollo ISBN 1-
57521-083-5.
 Tricks of the Java Programming Gurus by Glenn Vanderburg and others. ISBN: 1-57521-
102-5 Trucos de la programación de los gurús de Java por Glenn Vanderburg y otros:. ISBN
1-57521-102-5
 Java Developer's Guide by Jamie Jaworski. ISBN: 1-57521-069-X. la Guía para
desarrolladores de Java por Jamie Jaworski. ISBN 1-57521-069-X.
 Peter Norton's Guide to Java Programming by Peter Norton and William Stanek . Norton
Guía de Pedro para programación en Java por Peter Norton y William Stanek. ISBN: 1-
57521-088-6. ISBN: 1-57521-088-6.
 Creating Web Applets with Java by David Gulbransen and Ben Rawlings . Creación de
Applets Web con Java por David Ben Gulbransen y Rawlings. ISBN: 1-57521-070-3. ISBN: 1-
57521-070-3.
 Teach Yourself Internet Game Programming with Java in 21 Days by Michael Morrison .
Aprendiendo a Internet Juego de programación con Java en 21 días de Michael Morrison.
ISBN: 1-57521-148-3 ISBN: 1-57521-148-3
 Teach Yourself Java in Café in 21 Days by Daniel Joshi, Laura Lemay, and Charles Perkins .
Aprendiendo Java en el Café en 21 Días por Daniel Joshi, Lemay Laura, Carlos y Perkins.
ISBN: 1-57521-157-2. ISBN: 1-57521-157-2.

Several of these books, including the first edition of Teach Yourself Java in 21 Days, are
available in full on the World Wide Web at the Sams Publishing Developers' Resource
Center: Varios de estos libros, entre ellos la primera edición de Aprendiendo Java en 21
días, están disponibles en su totalidad en la World Wide Web en los recursos del Sams
publicación de los desarrolladores del Centro:

http://www.mcp.com/sams

The Resource Center includes the Macmillan Online Bookstore, links to author Web sites,
and weekly chats by Sams.net writers. El Centro de Recursos incluye la Macmillan Librería
en línea, enlaces a sitios Web de autor, y los chats semanales por escritores Sams.net. It's a
good place to see what's coming up from Sams and to ask questions of some experienced
veterans of Java programming and other Internet-related developments. Es un buen lugar
para ver lo que viene de Sams y hacer preguntas a algunos veteranos con experiencia de
programación Java y otros desarrollos relacionados con Internet.

The JavaSoft Site El sitio JavaSoft


As you learned during Hour 3, "Vacationing in Java," JavaSoft maintains an active Web
site at the following address: Como ha aprendido durante Hour 3, "De vacaciones en Java",
JavaSoft mantiene un sitio Web activo en la siguiente dirección:

http://java.sun.com

Because JavaSoft is the division of Sun responsible for the Java language, this site is the
first place to go when looking for Java-related information. Debido a JavaSoft es la división
responsable de Sun para el lenguaje Java, este sitio es el primer lugar para ir en la búsqueda
de información relacionados con Java. New versions of the Java Developer's Kit and other
programming resources are available from this site. Las nuevas versiones del Kit de
Desarrollo Java y otros recursos de programación están disponibles en este sitio.

The site is broken down into the following areas: El sitio se divide en las siguientes áreas:

 What Is Java? ¿Qué es Java? This area features articles about the language aimed at
people who are discovering the language. Esta zona cuenta con artículos sobre la lengua
dirigido a personas que están descubriendo la lengua. This is a good place for readers of
this book to check out because it introduces topics with beginners in mind. Este es un
buen lugar para los lectores de este libro de visita, ya que introduce los temas con los
principiantes en cuenta.
 What's New? ¿Qué hay de nuevo? This area contains announcements related to upcoming
product releases and Java-related events such as JavaOne, the yearly conference for Java
programmers. Esta área contiene anuncios relacionados con las próximas versiones de
productos y eventos relacionados con Java, como JavaOne, la conferencia anual de
programadores de Java. This area also contains JavaSoft press releases and schedules for
training sessions that are offered by the company. Esta zona también contiene versiones
JavaSoft prensa y horarios para las sesiones de capacitación que se ofrecen por la
empresa.
 For Developers: This area is a consolidated resource for all JavaSoft information of interest
to Java programmers, including complete documentation for the Java language in HTML
format. Para desarrolladores: Esta área es un recurso unificado para toda la información
JavaSoft de interés para los programadores de Java, incluida la documentación completa
para el lenguaje Java en formato HTML. You can find information on language
conferences, JavaSoft's for-a-fee programming support program, official Java books, and
other resources. Puede encontrar información sobre las conferencias del lenguaje, para-
una cuota-JavaSoft programa de apoyo a la programación, los libros oficiales de Java, y
otros recursos.
 Where Can I Read About...? ¿Dónde puedo leer acerca de ...? This area is a good place for
information that you're having trouble finding elsewhere. Esta zona es un buen lugar para
obtener información que usted está teniendo problemas para encontrar en otros lugares.
This heading includes a link to the list of Frequently Asked Questions (FAQs) about Java.
Esta partida incluye un enlace a la lista de Preguntas Frecuentes (FAQ) sobre Java. If you're
unfamiliar with FAQ lists, they provide concise answers to as many commonly requested
topics as possible. Si no está familiarizado con las listas de preguntas frecuentes, ofrecen
respuestas concisas a tantos temas solicitadas como sea posible. If you encounter a
stumbling block as you attempt to accomplish something with the language, visit the
following page to see all the topics that have their own FAQ listings: Si se encuentra con
un obstáculo en tu intento de lograr algo con el idioma, visite la siguiente página para ver
todos los temas que tienen sus propios listados de preguntas frecuentes:

http://www.javasoft.com/nav/read/faqindex.html

 How's Java Being Used? ¿Cómo de Java se utiliza? The area provides a description of what
JavaSoft calls its "success stories," which are some of the examples of Java being used on
the World Wide Web or in stand-alone programs. La zona ofrece una descripción de lo que
JavaSoft llama a sus "historias de éxito", que son algunos de los ejemplos de Java que se
utiliza en la World Wide Web o en programas independientes.
 Download: This area is a directory of all the things that can be downloaded from JavaSoft,
including the Developer's Kit, language documentation, and other files. Descarga: Esta
área es un directorio de todas las cosas que se pueden descargar de JavaSoft, incluyendo
el Kit de Desarrollo, la documentación del lenguaje, y otros archivos.
 Applets: This area is a showcase for Java programs running on the Web, including more
than two dozen offered by JavaSoft developers that can be readily adapted for use on your
own Web pages. Applets: Esta zona es un escaparate para los programas Java que se
ejecutan en la Web, incluyendo más de dos docenas ofrecido por los desarrolladores de
JavaSoft que se pueden adaptar fácilmente para su uso en sus propias páginas Web. There
also are links to several applet directories, including Gamelan at and the Java Applet
Rating Service (JARS) at . También hay enlaces a varios directorios applet, incluyendo
Gamelan en http://www.gamelan.com y el applet de Java Rating Service (JAR) en
http://www.jars.com .
 Do Business with JavaSoft: This area provides licensing and trademark guidelines for using
Java products. Hacer negocios con JavaSoft: Esta área ofrece las licencias y marcas de los
productos que utilizan Java.
 About JavaSoft: This area is a profile of JavaSoft with links to its employees and current
postings of employment opportunities at the company. Acerca de JavaSoft: Esta área es un
perfil de JavaSoft con enlaces a sus empleados y anuncios actuales de oportunidades de
empleo en la empresa.
 Java Store: This area is a catalog of official Java merchandise that can be ordered over the
Web, including denim shirts, coffee mugs, T-shirts, and caps. Java de la tienda: Esta área es
un catálogo de mercancía oficial de Java que se pueden pedir a través de Internet,
incluyendo las camisas de mezclilla, tazas, camisetas y gorras.

This site is continually updated with free resources of use to Java programmers. Este sitio
se actualiza constantemente con recursos libres de uso para los programadores de Java. One
thing you might want to take advantage of immediately is the Getting Started With Java
page at the following address: Una cosa que usted podría querer aprovecharse de inmediato
es la Guía de inicio de la página de Java en la siguiente dirección:

http://java.sun.com/starter.html

This page features a step-by-step introduction for new Java programmers. Esta página
contiene una introducción paso a paso para los nuevos programadores de Java. Although
much of the material will be a review after going through the preceding 24 hours, it's a
good chance to practice your skills and see more of what's offered on the JavaSoft site.
Aunque gran parte del material se realizará un examen después de pasar por las últimas 24
horas, es una buena oportunidad para practicar sus habilidades y ver más de lo que se
ofrece en el sitio JavaSoft.

Other Java Web Sites Otros Sitios Web en Java


Because so much of the Java phenomenon has been inspired by its use on Web pages, a
large number of Web sites focus on Java and Java programming. Debido a que gran parte
del fenómeno de Java ha sido inspirado por su uso en páginas Web, un gran número de
sitios web se centran en Java y Java.

The Java Books Page Los libros de Java Page

Those of us who write Java books like to think that you're forsaking all others by choosing
our work. Aquellos de nosotros que escriben libros de Java, como para pensar que usted
está renunciando a todas las demás por la elección de nuestro trabajo. However, anecdotal
studies (and the number of Java books on our shelves) indicate that you might benefit from
other books devoted to the language. Sin embargo, los estudios anecdóticos (y el número de
libros de Java en nuestros estantes) indican que podrían beneficiarse de otros libros
dedicados a la lengua.

Stephen Pietrowicz of the National Center for Supercomputing Applications maintains a


list of current and upcoming Java- and JavaScript-related books. Stephen Pietrowicz del
Centro Nacional para Aplicaciones de Supercomputación mantiene una lista de los libros de
Java y JavaScript relacionadas con actuales y futuros. You can find it at the following
address: Se puede encontrar en la siguiente dirección:

http://lightyear.ncsa.uiuc.edu/ ~ srp / java /


javabooks.html

Another rundown of Java-related books is presented by Elliotte Rusty Harold, the author of
one of the books described on the Web page. Otro resumen de los libros relacionados con
Java es presentado por Elliotte Rusty Harold, el autor de uno de los libros se describe en la
página Web. Harold's list, with reviews of many of the books, is available at the following
page: lista de Harold, con comentarios de muchos de los libros, está disponible en la página
siguiente:

http://sunsite.unc.edu/javafaq/books.html

Gamelans Java Directory Gamelanes Directorio de Java

Because Java is an object-oriented programming language, it is easy to use resources


created by other programmers in your own programs. Debido a que Java es un lenguaje de
programación orientado a objetos, es fácil de usar recursos creados por otros
programadores en sus propios programas. Before you start a Java project of any
significance, you should scan the World Wide Web for resources that you might be able to
use in your program. Antes de empezar un proyecto Java de cierta importancia, que debe
explorar el World Wide Web para los recursos que usted puede ser capaz de utilizar en su
programa.

The place to start is Gamelan, the Web site that catalogs Java programs, programming
resources, and other information. El lugar para comenzar es Gamelan, el sitio web que
cataloga los programas Java, los recursos de programación, y otra información. Visit the
following address: Visite la siguiente dirección:

http://www.gamelan.com

Gamelan is the most comprehensive directory of its kind on the Web, surpassing even
JavaSoft's own site in the depth of its coverage. Gamelan es el directorio más completo de
su tipo en la red, superando incluso a JavaSoft propio sitio en la profundidad de su
cobertura. It has become the first place that a Java programmer registers information about
a program when it is completed. Se ha convertido en el primer lugar que un programador de
Java registros de información sobre un programa cuando se haya completado. Gamelan
staff members update the site on a daily basis. miembros del personal Gamelan actualizar el
sitio a diario. Gamelan also highlights the best submissions to its directory at the following
page: Gamelan también pone de relieve las mejores propuestas a su directorio en la
siguiente página:

http://www.gamelan.com/special/picks.html

Java Applet Rating Service Applet de Java Calificación del Servicio

To access another directory that rates Java applets, direct your Web browser to the
following address: Para acceder a otro directorio que las tasas de applets de Java, dirija su
navegador a la siguiente dirección:

http://www.jars.com

The apple logo of the Java Applet Rating Service (JARS) can be seen on numerous Java
applets offered on Web pages. El logo de la manzana de la applet de Java Rating Service
(JAR) se puede ver en numerosos applets de Java que ofrece en las páginas Web. The
JARS site has been expanded recently to include news about the language and related
developments, reviews of Java development tools, and other useful information. El sitio
JARS se ha ampliado recientemente para incluir noticias sobre la evolución del idioma y
afines, la revisión de las herramientas de desarrollo Java, y otra información útil.

JavaWorld Magazine JavaWorld Magazine

One of the best magazines that has sprung up to serve the Java programming community is
also the cheapest. Una de las mejores revistas que ha surgido para servir a la comunidad de
programación Java es también el más barato. JavaWorld is available for free on the World
Wide Web at the following address: JavaWorld está disponible de forma gratuita en la
World Wide Web en la siguiente dirección:

http://www.javaworld.com

JavaWorld publishes frequent tutorial articles along with Java development news and other
features, which are updated monthly. JavaWorld publica con frecuencia artículos tutorial,
junto con noticias sobre el desarrollo de Java y otras características, que se actualizan
mensualmente. The Web-only format provides an advantage over some of its print
competitors such as Java Report in the area of how-to articles. El formato de la Web sólo
proporciona una ventaja sobre algunos de sus competidores de impresión, tales como
informes Java en el área de cómo-a los artículos. As an article is teaching a particular
concept or type of programming, JavaWorld can offer a Java applet that demonstrates the
lesson. En un artículo es la enseñanza de un concepto particular o el tipo de programación,
JavaWorld puede ofrecer un applet de Java que demuestra la lección.

Java Frequently Asked Questions Java Preguntas más frecuentes

As a complement to the Java FAQ lists that are available on the JavaSoft Web site, Java
programmers using Internet discussion groups have collaborated on their own list of
questions and answers. Como complemento a las listas de preguntas frecuentes de Java que
están disponibles en el sitio Web de JavaSoft, los programadores de Java utilizando grupos
de discusión en Internet han colaborado en su propia lista de preguntas y respuestas.

Elliotte Rusty Harold, one of the keepers of the Java books Web pages, also offers the
current Java FAQ list at the following address: Elliotte Rusty Harold, uno de los guardianes
de los libros de Java páginas Web, también ofrece la corriente de Java la lista de preguntas
frecuentes en la siguiente dirección:

http://sunsite.unc.edu/javafaq/javafaq.html

Another similar resource, titled the "Unofficial Obscure Java FAQ," was begun to answer
some less frequently asked questions. Otro recurso similar, llamado el "oscuro oficial de
Java Preguntas más frecuentes", se comenzó a responder a algunas preguntas menos
frecuentes. It's at the following Web page: Es en la siguiente página Web:

http://k2.scl.cwru.edu/ ~ flaco / java / java-faq.html

Java Newsgroups Java Grupos de noticias


One of the best resources for both novice and experienced Java programmers is Usenet, the
international network of discussion groups that is available to most Internet users. Uno de
los mejores recursos tanto para principiantes como experimentados programadores Java es
Usenet, la red internacional de grupos de discusión que está disponible para la mayoría de
usuarios de Internet. The following are descriptions of some of the several Java discussion
groups available on Usenet: Las siguientes son descripciones de algunos de los grupos de
discusión de varios de Java disponible en Usenet:

 : Although this group is designated as the Java discussion area for all subjects that don't
belong in one of the other groups, it gets more use than any of the others.
comp.lang.java.misc: Aunque este grupo ha sido designada como el área de
discusión de Java para todos los sujetos que no tienen cabida en uno de los otros grupos,
se hace un uso más que cualquiera de los otros. It replaced in mid-1996. Reemplazó
comp.lang.java a mediados de 1996. Any Java-related topic is suitable for discussion
here. Cualquier tema relacionado con Java es ideal para la discusión aquí.
 : This group is devoted to any Java discussions that are likely to inspire heated or
comparative debate. comp.lang.java.advocacy: Este grupo está dedicado a los
debates de Java que pueden inspirar o comparativa acalorado debate. If you want to
argue the merits of Java against another language, this is the place for it. Si desea discutir
los méritos de Java en contra de otro idioma, este es el lugar para ello. This group can be a
good place to consult if you want to see whether Java is the right choice for a project
you're working on. Este grupo puede ser un buen lugar para consultar si quieres ver si Java
es la elección adecuada para un proyecto que está trabajando.
 : This group posts announcements, advertisements, and press releases of interest to the
Java development community. comp.lang.java.announce: Este grupo de puestos de
anuncios, anuncios y comunicados de prensa de interés para la comunidad de desarrollo
Java. It is moderated, so all postings must be submitted for approval before they are
posted to the group. Es moderado, por lo que todas las ofertas deberán presentarse para
su aprobación antes de ser enviados al grupo.
 : This group discusses the Java language's Application Programming Interface, the full
library of class programs that comes with the Java Developer's Kit and other
implementations of the language. comp.lang.java.api: Este grupo discute el lenguaje
Java Application Programming Interface, la biblioteca completa de los programas de clase
que viene con Java Developer Kit y otras puestas en práctica de la lengua.
 : This group contains questions and answers related to Java programming, which makes it
another good place for new programmers to frequent. comp.lang.java.programmer:
Este grupo contiene preguntas y respuestas relacionadas con la programación Java, lo que
hace que sea otro buen lugar para los nuevos programadores a frecuentar.
 : This discussion group is devoted to security issues related to Java, especially in regard to
running Java programs and other executable content on the World Wide Web.
comp.lang.java.security: Este grupo de discusión se dedica a temas de seguridad
relacionados con Java, especialmente en lo que respecta a la ejecución de los programas
de Java y ejecutables de otros contenidos en la World Wide Web.
 : This group provides a place to discuss installation problems related to Java programming
tools and similar issues. comp.lang.java.setup: Este grupo proporciona un lugar para
discutir los problemas de instalación relacionados con herramientas de programación Java
y cuestiones similares.
 : The most advanced of the Java discussion groups, this group is devoted to discussing the
implementation of the language, issues with porting it to new machines, the specifics of
the Java Virtual Machine, and similar subjects. comp.lang.java.tech: El más avanzado
de los grupos de discusión de Java, este grupo está dedicado a discutir la implementación
del lenguaje, problemas con el traslado a las nuevas máquinas, los detalles de la máquina
virtual de Java, y temas similares.

Job Opportunities Oportunidades de Trabajo


If you're one of those folks who is learning Java as part of your plan to become a captain of
industry, you should check out some of the Java-related job openings that become
available. Si usted es uno de esa gente que está aprendiendo Java como parte de su plan
para convertirse en un magnate de la industria, usted debe comprobar algunas de las ofertas
de trabajo relacionados con Java que estén disponibles. Several of the resources listed in
this appendix have a section devoted to job opportunities. Varios de los recursos
enumerados en este apéndice tienen una sección dedicada a las oportunidades de empleo.

If you might be interested in joining JavaSoft itself, visit the following Web page: Si usted
pudiera estar interesado en formar parte de JavaSoft sí mismo, visite la siguiente página
Web:

http://www.javasoft.com/aboutJavaSoft/jobs/index.html
JavaWorld offers a Career Opportunities page that often has several openings for Java
developers: JavaWorld ofrece una página de Oportunidades que a menudo tiene varias
aberturas para los desarrolladores de Java:

http://www.javaworld.com/javaworld/common/jw-jobop.html

One tactic that can make Java employers aware of your skills is to register yourself as a
resource for the Gamelan directory. Una de las tácticas que pueden hacer los empleadores
de Java consciente de sus habilidades es que se registre como un recurso para el directorio
Gamelan. Gamelan will add you to its site, and this listing might result in e-mail about
Java-related job assignments. Gamelan se agrega a su sitio, y esta oferta puede dar lugar a
correo electrónico sobre las asignaciones de trabajo relacionados con Java. To find out
about registering yourself, head to the following address in the Add a Resource section of
Gamelan: Para obtener información sobre el registro de sí mismo, vaya a la siguiente
dirección en la sección Agregar una Gamelan de recursos:

http://www.gamelan.com/submit/submit_person.shtml

Although this Web page isn't specifically a Java employment resource, the World Wide
Web site Career Path enables you to search the job classifieds of more than two dozen US
newspapers. A pesar de esta página web no es específicamente un empleo de recursos de
Java, el sitio Web de Formación Camino le permite buscar en los clasificados de empleo de
más de dos docenas de periódicos de EE.UU.. You have to register to use the site, but it's
free, and there are more than 100,000 classifieds that you can search using keywords such
as Java or Internet. Usted tiene que registrarse para usar el sitio, pero es gratis, y hay más
de 100.000 anuncios clasificados que se puede buscar mediante palabras clave como Java o
Internet. Go to the following address: Ir a la siguiente dirección:

http://www.careerpath.com

 Apéndice B
o Herramientas de programación Java
 Elección de desarrollo de software
 Interfaz gráfica de las herramientas de diseño
 Escribir programas Java portátil totalmente
 Experiencia en el uso IDEs Otros
 El uso de un IDE para más de un idioma
 Tener sentido del IDE
 Rogue Wave JFactory
 Figura B.1.
 Requisitos del sistema
 Información general
 Precios e información adicional
 Symantec Café
 Figura B.2.
 Requisitos del sistema
 Información general
 Precios e información adicional
 SunSoft WorkShop Java
 Figura B.3.
 Requisitos del sistema
 Información general
 Precios e información adicional
 SourceCraft NetCraft
 Figura B.4.
 Requisitos del sistema
 Información general
 Precios e información adicional
 Pro-C Wingen para Java
 Figura B.5.
 Requisitos del sistema
 Información general
 Precios e información adicional
 Otras ofertas
 Borland C + + 5.0 con Java Mejoras
 Metrowerks CodeWarrior
 Kalimantan
 Natural Asador de Inteligencia
 Microsoft Visual J + +
 Resumen

Appendix B Apéndice B

Java Programming Tools Herramientas de


programación Java

When the Java programming language was introduced more than a year ago, the Java
Developer's Kit was the only development tool that programmers could use. Cuando el
lenguaje de programación Java se introdujo hace más de un año, el Kit de Desarrollo Java
fue la herramienta de desarrollo única que los programadores pueden utilizar. The Kit
enables you to write, compile, and debug Java programs, but it is primitive compared to the
tools available for programmers using Visual Basic, Borland Delphi, and other languages.
El kit le permite escribir, compilar y depurar programas en Java, pero es primitivo en
comparación con las herramientas disponibles para los programadores que utilizan Visual
Basic, Borland Delphi, y otros idiomas.

With many languages, programs can be developed with a suite of tools called an integrated
development environment (also known as an IDE). Con muchos idiomas, los programas
pueden ser desarrollados con un conjunto de herramientas llamadas un entorno de
desarrollo integrado (también conocido como IDE). An integrated development
environment combines several development tools into a single package. Un entorno de
desarrollo integrado combina varias herramientas de desarrollo en un solo paquete. This
package usually contains a program text editor, a compiler, a debugger, and other tools.
Este paquete contiene normalmente un editor de texto del programa, un compilador, un
depurador, y otras herramientas. These tools complement each other as you go through the
process of creating programs. Estas herramientas se complementan entre sí a medida que
avanza el proceso de creación de programas. Most professional IDEs use drag-and-drop,
multiple windows, and other graphical features. La mayoría de entornos de desarrollo
profesional de utilizar arrastrar y soltar, varias ventanas, y otras características gráficas. If
they work well, designing a program should be faster and more efficient than using a more
rudimentary tool such as the Java Developer's Kit. Si trabajan bien, el diseño de un
programa debe ser más rápido y más eficiente que el uso de una herramienta más
rudimentaria como el Kit de Desarrollo Java. Programs also ought to be easier to debug.
Los programas también deben ser más fáciles de depurar.

Many IDEs use rapid application development, also known as RAD, in their approach to
programming. Muchos IDE para desarrollo rápido de aplicaciones, también conocido como
RAD, en su enfoque de la programación. RAD is a strategy to speed up program
development by using tools such as an interface designer. RAD es una estrategia para
acelerar el desarrollo de programas utilizando herramientas tales como un diseñador de
interfaz. Product advertisements that promise the capability to "create Java programs
without writing a line of code" are referring to a RAD feature. anuncios de productos que
prometen la capacidad de "crear programas de Java sin necesidad de escribir una línea de
código" se refiere a una característica RAD. Most Java programming environments to date
use RAD tools primarily in the design of a graphical user interface. La mayoría de entornos
de programación Java hasta la fecha el uso de herramientas RAD principalmente en el
diseño de una interfaz gráfica de usuario. Some of these IDEs connect interface design
directly to programming so that you can create a clickable button, for example, and
immediately write statements to handle the button. Algunos de estos entornos de desarrollo
conectar directamente al diseño de la interfaz de programación para que pueda crear un
botón que se pulse, por ejemplo, e inmediatamente escribir instrucciones para manejar el
botón.

More than 40 Java development environments have been released in beta or final form.
Más de 40 entornos de desarrollo Java se han lanzado en forma beta o final. This appendix
focuses on some of the more commonly used environments so that you can decide whether
they match your programming needs. Este apéndice se centra en algunos de los entornos
más utilizados, para que pueda decidir si se ajustan a sus necesidades de programación.
You'll be introduced to each IDE with details about the systems it can run on and things to
consider when evaluating the development product. Se le presentó a cada IDE con detalles
sobre los sistemas que pueden funcionar con y cosas a considerar al evaluar el desarrollo de
productos. This appendix also has capsule descriptions of some other tools, such as
Microsoft Visual J++. Este apéndice también tiene descripciones cápsula de algunas otras
herramientas, como Microsoft Visual J + +.

The Gamelan Web directory of Java resources maintains a page with links to IDE Web
sites and related information. El directorio Web de recursos Gamelan de Java mantiene una
página con enlaces a sitios web de IDE e información relacionada. This page is available by
choosing Programming in Java | Development Tools | IDEs from the main Gamelan page at
the following address: Esta página está disponible mediante la elección de programación en
Java | Herramientas de desarrollo | IDE desde la página principal Gamelan en la siguiente
dirección:

http://www.gamelan.com

You can attempt to go there directly at the following URL: Usted puede tratar de ir
directamente a la siguiente dirección URL:

http://www.gamelan.com/pages/Gamelan.programming.tool.ide.html

The following development environments are described in this appendix: Los entornos de
desarrollo siguientes se describen en este apéndice:

 Rogue Wave JFactory Rogue Wave JFactory


 Symantec Café Symantec Café
 SunSoft Java WorkShop SunSoft WorkShop Java
 SourceCraft NetCraft SourceCraft NetCraft
 Pro-C WinGEN for Java Pro-C Wingen para Java

Choosing Development Software Elección de desarrollo de software


As you decide whether to choose an IDE and which one you might choose, there are some
questions that are helpful to ask about what you need when programming. En cuanto a
decidir si debe elegir un IDE y que se puede elegir, hay algunas preguntas que son útiles
para preguntar acerca de lo que usted necesita programación cuando. Issues related to the
Java language can make a difference in your choice. Las cuestiones relacionadas con el
lenguaje Java puede hacer una diferencia en su elección. Ask yourself each of these
questions: Pregúntate a ti mismo cada una de estas preguntas:

 Is graphical interface design important in your programs? ¿Es el diseño de interfaz gráfica
importante en sus programas?
 How important is it for your programs to run on more than one type of computer system,
instead of being specific to a Microsoft Windows machine, an Apple Macintosh, or other
system? ¿Qué tan importante es para sus programas se ejecuten en más de un tipo de
sistema informático, en lugar de ser específicos para una máquina de Microsoft Windows,
Apple Macintosh, u otro sistema?
 Have you used IDE tools before? ¿Usted ha utilizado las herramientas IDE antes?
 Will you be using other programming languages in addition to Java? ¿Va a usar otros
lenguajes de programación, además de Java?

Graphical Interface Design Tools Interfaz gráfica de las herramientas de diseño

Thanks to Microsoft Windows and Apple Macintosh machines, windowing systems are the
way most users want to operate their computers. Gracias a Microsoft Windows y máquinas
Apple Macintosh, sistemas de ventanas son la forma más usuarios quieren operar sus
computadoras. Users want their software to use the mouse and offer common windowing
features, such as resizable windows. Los usuarios quieren que su software para utilizar el
ratón y ofrecen características comunes de ventanas, como las ventanas de tamaño variable.
These expectations make user interface design important to consider when you're
developing a program. Estas expectativas de hacer el diseño de interfaz de usuario
importante a considerar cuando se está desarrollando un programa. If your software uses a
command-line environment in the tradition of the Java Developer's Kit or MS-DOS, your
program will be less attractive to people who use it. Si el software utiliza un entorno de
línea de comandos en la tradición del Kit de Desarrollo Java o MS-DOS, el programa será
menos atractivo para las personas que lo utilizan.

In the same vein, interface design is important to consider when selecting an IDE. En la
misma línea, diseño de la interfaz es importante tener en cuenta al seleccionar un IDE. The
available Java IDEs take different approaches to interface design and the other features that
should be available as you design an interface. La disposición IDE Java tienen enfoques
diferentes a la interfaz de diseño y otras características que deben estar disponibles al
diseñar una interfaz. Some tools focus almost entirely on interface development, such as
Rogue Wave's JFactory. Algunas herramientas se centran casi exclusivamente en el
desarrollo de la interfaz, como JFactory Rogue Wave. Many of these interface development
tools can automatically create Java code that handles user events. Muchas de estas
herramientas de desarrollo de interfaz puede crear automáticamente el código Java que se
encarga de los eventos de usuario. Visual Basic programmers will be familiar with this
feature, because that language's IDE enables quick interface design and programming.
Programadores de Visual Basic estarán familiarizados con esta característica, porque IDE
que el lenguaje de diseño de la interfaz permite rápida y programación.

Most of the interface builders function similarly to drawing programs. La mayoría de los
constructores de interfaz de la función de manera similar a los programas de dibujo. User
interface elements are arranged in a palette and can be dropped directly onto a workspace.
elementos de la interfaz de usuario están dispuestos en una paleta y se puede caer
directamente sobre un área de trabajo. Most of the components come from the Java
Abstract Windowing Toolkit, or AWT. La mayoría de los componentes proceden de la Java
Abstract Windowing Toolkit, o AWT. Java WorkShop and other IDEs add a layer between
the AWT and your programs that is supposed to make windowing and interface
programming easier. Java WorkShop y otros IDE agregar una capa entre el AWT y los
programas que se supone que debe hacer la programación de ventanas y una interfaz más
fácil. For some programmers, this might not be an attractive feature, because they would
prefer to do the same kind of AWT programming that was described in this book. Para
algunos programadores, esto podría no ser una característica atractiva, ya que prefiere hacer
el mismo tipo de programación AWT que se describe en este libro. Other programmers
might like to use these new interface features and avoid AWT programming. Otros
programadores les gustaría utilizar estas funciones la nueva interfaz de programación y
evitar AWT.

Writing Fully Portable Java Programs Escribir programas Java portátil totalmente

A feature to look for as you evaluate the different IDEs is adherence to Java's promise of
platform independence. Una característica a buscar como a evaluar los diferentes entornos
de desarrollo es la adhesión a la promesa de Java de la independencia de la plataforma.
Some of the development tools are no different than using the Java Developer's Kit--they
produce programs that are fully usable on all Java implementations. Algunas de las
herramientas de desarrollo no son diferentes de utilizar el Kit de Desarrollo Java - que
producen los programas que son completamente utilizables en todas las implementaciones
de Java. In fact, many of these IDEs, such as SourceCraft NetCraft, work in conjunction
with the JDK, running tools like behind the scenes. De hecho, muchos de estos entornos de
desarrollo, tales como SourceCraft Netcraft, trabajar en conjunto con el JDK, ejecutando
herramientas como javac detrás de las escenas. Java WorkShop, Symantec Café, and other
development tools come with their own specialized versions of the JDK. Java WorkShop,
el Café de Symantec, y otras herramientas de desarrollo cuentan con sus propias versiones
especializadas del JDK.

Almost all IDEs aim to help you to write portable, platform-independent programs. Casi
todos los entornos de desarrollo tienen como objetivo ayudar a escribir programas
portables, independientes de la plataforma. A notable exception is Microsoft Visual J++,
which offers features that are specific to Microsoft Windows systems and cannot be
handled by other platforms. Una notable excepción es Microsoft Visual J + +, que ofrece
características que son específicas para los sistemas Microsoft Windows y no pueden ser
manejados por otras plataformas. A Java program designed with Visual J++ can be
developed to run on all types of computer systems if it does not use any of the special
Windows-specific features. Un programa de Java diseñado con Visual J + + puede ser
desarrollado para funcionar en todo tipo de sistemas informáticos si no utiliza ninguna de
las particularidades específicas de Windows.
Many Java programmers believe that all development environments should produce
platform-independent programs because this capability is essential to the continuing
success of the language. Muchos programadores de Java creen que todos los entornos de
desarrollo debe producir programas independientes de la plataforma, porque esta capacidad
es esencial para el éxito continuo de la lengua. This belief is the subject of contentious
discussion on the Internet and elsewhere. Esta creencia es objeto de discusión contenciosa
en Internet y en otros lugares. Although platform-independent programs are an important
part of Java, most IDEs are not completely independent themselves, even when written
using Java. Aunque los programas independientes de la plataforma son una parte
importante de Java, la mayoría de entornos de desarrollo no son completamente
independientes de sí mismos, aun cuando está escrito en Java. These development tools are
available only for specific platforms, primarily because they use native code, which
consists of parts of Java programs that are written using other languages such as C++ or C.
Estas herramientas de desarrollo sólo están disponibles para plataformas específicas,
principalmente debido a que utilizan código nativo, que se compone de partes de los
programas de Java que se escriben con otros lenguajes como C + + o C.

Experience Using Other IDEs Experiencia en el uso IDEs Otros

As you look over the sales pitches for each IDE, one thing that doesn't get enough attention
is that many of these tools require a lot of skill and experience to use successfully. Al
revisar los argumentos de venta para cada IDE, una cosa que no recibe suficiente atención
es que muchas de estas herramientas requieren de mucha habilidad y experiencia para
utilizar con éxito. It can be difficult for an IDE to improve your programming if you can't
figure out how the IDE works. Puede ser difícil para un entorno de desarrollo para mejorar
su programación si no se puede entender cómo funciona el IDE.

IDEs are often the most complicated software you will use. IDEs son a menudo el software
más complicado que va a utilizar. They can include multiple-document windows, numerous
configuration options, and other sophisticated features. Pueden incluir varias ventanas de
documento, numerosas opciones de configuración, y otras características avanzadas.
Novice programmers can become confused with many IDEs because of the complexity,
especially if they are still learning how to use a new programming language. programadores
novatos pueden confundirse con IDEs muchos debido a la complejidad, sobre todo si aún
están aprendiendo cómo usar un nuevo lenguaje de programación. For this reason, the IDE
you choose should be suited to your experience level as a programmer and as an IDE user.
Por esta razón, el IDE que elija deberá ser adecuado a su nivel de experiencia como
programador y como usuario de IDE.

Several Java IDEs are highly suitable for novices. Varios IDEs de Java son muy adecuados
para los principiantes. Perhaps the best example of an easy-to-understand interface is
SunSoft Java WorkShop, which uses a browser interface that should be well-known to
anyone who surfs the World Wide Web. Tal vez el mejor ejemplo de una forma fácil de
entender interfaz es SunSoft Java WorkShop, que utiliza una interfaz de navegador que
debe ser bien conocida para cualquiera que se encuentre navegando por la World Wide
Web. The downside to the easier-to-use IDEs is that they might require more work to get
something done than an IDE that has more functions at the programmer's fingertips. La
desventaja de los IDEs más fácil de usar, es que pueden requerir más trabajo que hacer algo
de una IDE que tiene más funciones al alcance del programador.

Using an IDE for More than One Language El uso de un IDE para más de un idioma

If you are using more than one language as you program, another thing to consider about an
IDE is whether you can use it with multiple languages. Si usted está usando más de un
idioma a medida que el programa, otra cosa a considerar sobre un IDE es si se puede usar
con varios idiomas. The Borland 5.0 C++ IDE, MetroWerks CodeWarrior, and other tools
can handle Java and other languages or work identically to other IDEs from the company.
El Borland C + + 5.0 IDE CodeWarrior MetroWerks, y otras herramientas puede manejar
Java y otros lenguajes o funcionan de forma idéntica a los otros IDE de la compañía.

One advantage to using an IDE that works with multiple languages is that you don't have to
learn a different IDE when using a different language. Una ventaja de usar un IDE que
funciona con múltiples idiomas es que usted no tiene que aprender un IDE diferente cuando
se utiliza un lenguaje diferente. (Of course, the IDE isn't any easier to learn the first time
around.) Another plus to using a multilanguage tool is that you can write Java statements
and non-Java native methods with the same tool. (Por supuesto, el IDE no es más fácil de
aprender la primera vez.) Otra ventaja de usar una herramienta en varios idiomas es que
usted puede escribir sentencias Java y métodos nativos no-Java con la misma herramienta.
The Borland 5.0 Java environment is an example of this type of IDE; it can compile C and
C++ code and Java statements. El entorno Java de Borland 5.0 es un ejemplo de este tipo de
IDE, se puede compilar en C y C + + y Java instrucciones de código.

Making Sense of IDEs Tener sentido del IDE

An IDE should make you a better programmer and make it easier or more enjoyable for you
to develop programs. Una IDE debe hacer usted un mejor programador y hacer más fácil o
más agradable para usted para desarrollar programas. As you evaluate each of the products
described in the following sections, you can determine which of the features of a specific
IDE you might need. Al evaluar cada uno de los productos descritos en las secciones
siguientes, puede determinar cuál de las características de un IDE que usted pueda
necesitar. Because so many development tools are available for Java, you should be able to
find one that suits your skills and personal preferences. Debido a que las herramientas de
desarrollo para muchas están disponibles para Java, debe ser capaz de encontrar uno que se
adapte a sus habilidades y preferencias personales. Of course, you can always use the Java
Developer's Kit that you learned about during this book and enhance it by using custom
interface builders, your preferred word processor, and other software. Por supuesto,
siempre puede usar el Kit de Desarrollo Java que aprendieron durante este libro y mejorarla
mediante el uso de constructores de encargo de la interfaz, el procesador de textos
preferido, y otro software.

Caution: If you download trial copies of several different IDEs, as was done for this appendix, you
might run into difficulties because of how each IDE configures your system. Precaución: Si
descargar copias de prueba de varios entornos de desarrollo diferentes, como se hizo en este
apéndice, que podría encontrarse con dificultades debido a la forma en que cada IDE configura el
sistema. Many Java development tools use environment variables such as and , and these
variables could be set up incorrectly if another IDE has already configured them. Muchas
herramientas de desarrollo Java utilizan variables de entorno como CLASSPATH y JAVAHOME, y
estas variables se podría establecer incorrectamente si otro IDE ya los ha configurado. Before
installing a test version of an IDE, you should uninstall any other Java IDEs that are present on your
system. Antes de instalar una versión de prueba de un IDE, debe desinstalar cualquier otro IDE
Java que están presentes en su sistema.

Rogue Wave JFactory Rogue Wave JFactory


Rogue Wave JFactory is an interface builder instead of an IDE, in contrast to other IDEs
that are available for Java programming. Rogue Wave JFactory es un constructor de
interfaz en lugar de un IDE, en contraste con otros IDE que están disponibles para la
programación Java. It delivers some programming capabilities along with interface design
features, enabling interface actions to be handled within JFactory. Ofrece algunas
capacidades de programación junto con las características del diseño de la interfaz, que
permite acciones de la interfaz que se maneja dentro de JFactory. It also can compile and
test programs during development, so it's similar enough to a full IDE to be worth
consideration. También puede compilar y probar los programas durante el desarrollo, por lo
que es bastante similar a un IDE completo para ser digno de consideración. Though you can
use JFactory with any editor and Java compiler, JFactory provides a word processor and
can use the JDK compiler. Aunque puede utilizar JFactory con cualquier editor y
compilador de Java, JFactory ofrece un procesador de texto y puede utilizar el compilador
JDK. Figure B.1 provides a look at the JFactory environment. Figura B.1 proporciona un
vistazo a el medio ambiente JFactory.

Figura B.1. Rogue Wave JFactory at work. Rogue Wave JFactory en el trabajo.

System Requirements Requisitos del sistema


Versions of JFactory are available for the following platforms: Las versiones de JFactory
están disponibles para las siguientes plataformas:

 Microsoft Windows 95 and Windows NT systems running a 486 or better with 16M of
memory, 25M of hard disk space, and the Java Developer's Kit. Microsoft Windows 95 y
Windows NT que ejecuta un 486 o superior con 16M de memoria, 25 millones de espacio
en disco duro, y el Kit de Desarrollo Java.
 SPARC Solaris 2.4 or 2.5 running UNIX with 25M of hard disk space, an applet browser,
JDK, and X11R5. SPARC Solaris 2.4 o 2.5 corriendo UNIX con 25 millones de espacio en
disco duro, un navegador de applet, JDK, y X11R5. You must have enough memory to run
X11R5, the JDK compiler, and an applet browser at the same time. Debe tener suficiente
memoria para ejecutar X11R5, el compilador JDK, y un navegador de applet en el mismo
tiempo.
 HP-UX 10.01 systems with 25M of hard disk space, an applet browser, JDK, and X11R5. HP-
UX 10.01 con 25 millones de sistemas de espacio en disco duro, un navegador de applet,
JDK, y X11R5. The memory requirements are the same as for Solaris systems. Los
requisitos de memoria son las mismas que para los sistemas Solaris.
 IBM OS/2 Warp 3.0 systems with 25M of hard disk space, 4M of memory not used by
OS/2, a two-button mouse or pointing device, and JDK build os2-19960412. IBM OS / 2
Warp 3.0 con los sistemas de 25M de espacio en disco duro, 4 M de la memoria no
utilizada por el OS / 2, un ratón de dos botones o dispositivo de puntero, y JDK construir
os2-19960412.

Overview Información general

JFactory, which is based on a multiplatform C++ programming tool from Rogue Wave, has
numerous features that help you to design applications rapidly. JFactory, que se basa en un
C + + multiplataforma herramienta de programación de Rogue Wave, tiene numerosas
características que le ayudan a diseñar aplicaciones rápidamente. Because Rogue Wave has
a lot of experience with similar tools, JFactory is different from many Java IDEs that are
still in a beta stage of development or are new products. Debido a Rogue Wave tiene mucha
experiencia con herramientas similares, JFactory es diferente de muchos IDEs de Java que
se encuentran todavía en una fase beta de desarrollo o nuevos productos. The strength of
JFactory is the visual, drag-and-drop editor for interface creation, which is superior to most
other visual development tools currently available for the Java language. La fuerza de
JFactory es el editor visual, arrastrar y soltar para la creación de la interfaz, que es superior
a la mayoría de las herramientas de desarrollo visuales disponibles para el lenguaje Java.

As you develop an interface with JFactory, you can test it at any time. A medida que
desarrolla una interfaz con JFactory, puede probarlo en cualquier momento. Another useful
feature is the way that custom components can be added to a program toolbar along with
AWT components such as text fields, text labels, and radio buttons. Otra característica útil
es la forma en que los componentes personalizados se pueden agregar a una barra de
herramientas del programa junto con los componentes AWT, como campos de texto,
etiquetas de texto y botones de radio. JFactory automatically creates a lot of the Java
statements that are needed to offer interface components in a program. JFactory crea
automáticamente una gran cantidad de los estados de Java que son necesarios para ofrecer
componentes de la interfaz de un programa. If you need to do some of your own
programming to customize the interface, you can do it in a way so that you can change the
interface later without overwriting the customized portions of your program. Si lo que
necesita hacer algo de su propia programación para personalizar la interfaz, usted puede
hacerlo de una manera, para que pueda cambiar la interfaz más tarde sin sobrescribir las
partes a medida de su programa.

With JFactory, you can use the mouse or the keyboard to place a component. Con JFactory,
puede utilizar el ratón o el teclado para colocar un componente. You can set up the height,
width, and x and y coordinates of a component from a properties dialog box. Usted puede
configurar la altura, anchura, y coordenadas x e y de un componente de un cuadro de
diálogo Propiedades. This capability makes it easier to align components correctly. Esta
capacidad hace que sea más fácil para alinear los componentes correctamente. When you
create a window, menu, or dialog box, you can save it in an object library for use with other
programs. Cuando se crea una ventana, un menú o cuadro de diálogo, se puede guardar en
una biblioteca de objetos para su uso con otros programas.

JFactory is not a full-fledged IDE, so it does not include its own compiler, debugger, or
other tools. JFactory no es un IDE de pleno derecho, por lo que no incluye su propio
compilador, depurador, u otras herramientas. However, the software's visual editor might
make up for the loss of some other IDE functionality. Sin embargo, el editor visual del
software podría compensar la pérdida de algunos otros funcionalidad IDE. Unless the
absence of sophisticated tools such as a class browser and integrated debugger slows down
your programming, JFactory could be an excellent choice. A menos que la ausencia de
herramientas sofisticadas, como un navegador de clases y el depurador integrado ralentiza
su programación, JFactory podría ser una excelente opción.

Pricing and Additional Information Precios e información adicional

JFactory retails for $195; a multiplatform package that includes the Microsoft Windows,
UNIX, and OS/2 versions is available for $390. JFactory un costo de $ 195, un paquete
multiplataforma que incluye Microsoft Windows, UNIX, y las versiones de OS / 2 está
disponible por $ 390. For more details and the opportunity to download a demo version or
to purchase JFactory online, visit the home page for JFactory at the following URL: Para
obtener más detalles y la oportunidad de descargar una versión demo o comprar en línea
JFactory, visite la página de inicio para JFactory en la siguiente URL:

http://www.roguewave.com/products/jfactory/jfactory.html
The e-mail address for comments and questions regarding JFactory is . La dirección de
correo electrónico para comentarios y preguntas sobre JFactory es
support@roguewave.com.

Symantec Café Symantec Café


Symantec Café, the first development environment other than the JDK that became widely
available for Java programming, is called an integrated development and debugging
environment (IDDE) by Symantec. Symantec Café, el entorno de desarrollo de primera que
no sea el JDK que se convirtió en ampliamente disponible para la programación Java, que
se llama un entorno de desarrollo integrado y la depuración (Idde) por Symantec. (Although
other IDEs are missing the extra D in their acronyms, most of them contain debuggers as
well.) Café is a stand-alone product based on Symantec's C++ environment. (Aunque otros
IDE falta el extra D en sus siglas, la mayoría de ellos contienen depuradores también.) Café
es un producto independiente basado en C + + de Symantec medio ambiente. Figure B.2
shows an example of Café at work. La figura B.2 muestra un ejemplo de Café en el trabajo.

Figura B.2. A screen capture of Symantec Café. Una captura de pantalla de Symantec
Café.

System Requirements Requisitos del sistema

Symantec has released versions of Café for the Microsoft Windows 95, Windows NT 3.5x,
and Macintosh systems. Symantec ha lanzado versiones de Café para el Microsoft
Windows 95, Windows NT 3.5, y los sistemas de Macintosh. Windows users must have at
least an Intel 386 processor and 8M memory, but a 486 or better and 16M memory are
recommended. Los usuarios de Windows deben tener al menos un procesador Intel 386 y la
memoria de los 8M, pero un 486 o superior y memoria de 16M recomendadas. You need at
least a VGA monitor, but Symantec recommends that you use an SVGA monitor if one is
available. Necesita al menos un monitor VGA, pero Symantec recomienda que utilice un
monitor SVGA si hay alguno disponible. The software and all its sample files and Help
files require 60M of disk space and a CD-ROM drive. El software y todos sus archivos de
ejemplo y archivos de ayuda requieren 60 millones de espacio en disco y una unidad de
CD-ROM. Macintosh owners need a Power Macintosh, 68030, or 68040 Macintosh and
16M memory. propietarios de Macintosh necesitan un Power Macintosh, 68030, 68040 o
Macintosh y 16M de memoria. The full installation of the software requires 30M of disk
space. La instalación completa del software requiere de 30 millones de espacio en disco.

Café incorporates the JDK into its release with a full implementation of the Java class
libraries and source code samples. Café incorpora el JDK en su estreno con la aplicación
plena de las bibliotecas de clases Java y muestras de código fuente. You do not have to
have the JDK before installing Café. Usted no tiene que tener antes de instalar el JDK Café.
In fact, you should uninstall the JDK if you already have it on your system before
implementing Café to avoid configuration conflicts between the two. De hecho, debe
desinstalar el JDK si ya lo tiene en su sistema antes de la aplicación de Café para evitar
conflictos de configuración entre los dos.

Overview Información general

Café is more robust than some other IDEs, and it has been documented more fully than
some other IDEs in books such as Teach Yourself Java in Café in 21 Days, available now
from Sams.net Publishing. Café es más robusto que algunos otros IDE, y se ha
documentado con más detalle de lo que algunos otros IDE en libros como Teach Yourself
Java en el Café en 21 días, a partir de ahora Sams.net publicación. The main features of
Café are described in the following list: Las principales características de Café se describen
en la siguiente lista:

 Café offers an excellent text editor that uses color to highlight different elements of a Java
program. Café ofrece un excelente editor de texto que utiliza el color para resaltar los
diferentes elementos de un programa Java.
 To assist the design of a class hierarchy, Café has a class editor for navigating through
classes and editing class methods. Para ayudar al diseño de una jerarquía de clases, Café
tiene un editor de clase para navegar a través de clases y métodos de edición de clase. It
also has a hierarchy editor for viewing and changing class relationships. También tiene un
editor de jerarquía para ver y cambiar las relaciones de clase. You can see changes in your
programs that would involve the class hierarchy as the program is being written. Usted
puede ver los cambios en los programas que implican la jerarquía de clases como el
programa que se está escribiendo. You also can change a program from within the class
editor by selecting a function or method within a class in order to display its source code in
a window. También puede cambiar un programa desde el editor de clases mediante la
selección de una función o método en una clase con el fin de mostrar su código fuente en
una ventana.
 The AppExpress tool speeds up the process of creating the beginning framework of a Java
program. La herramienta AppExpress acelera el proceso de creación del marco de inicio de
un programa Java. Other Express Agents--Café's term for wizards--make it easier to do
things within the IDE. Otros Agentes Express - Café plazo para asistentes - que sea más
fácil hacer las cosas dentro del IDE.
 In the program editor, Java syntax is highlighted, which makes it easier to find errors such
as typos and other problems. En el editor de programas, la sintaxis de Java se pone de
relieve, lo que hace más fácil encontrar errores como errores tipográficos y otros
problemas. The editor uses standard Windows cut, copy, and paste commands. El editor
utiliza el estándar de Windows cortar, copiar y pegar comandos.
 You can design a graphical user interface for your Java programs in a visual, drag-and-drop
manner with Café Studio. Usted puede diseñar una interfaz gráfica de usuario para los
programas Java de una manera visual, arrastrar y soltar con Café Studio. It enables
programmers to develop the dialog boxes and other visual components visually, and it
creates statements to handle these components automatically. Permite a los
programadores a desarrollar los cuadros de diálogo y otros componentes visuales visual, y
crea estados de manejar estos componentes de forma automática. There also is a menu
editor with an active window that lets you test the menus you create. También es un
editor de menú con una ventana activa que permite probar los menús que cree.
 With Café Studio, you can design a form and dictate exactly how it looks. Con Café Studio,
puede diseñar un formulario y dictar exactamente cómo se ve. With the Abstract
Windowing Toolkit, a graphical user interface might change depending on the computer
system the Java program is running on, similar to the way HTML pages can be modified for
presentation on the many different platforms that can access the World Wide Web. Con el
kit de herramientas Resumen de ventanas, una interfaz gráfica de usuario puede cambiar
en función del sistema informático del programa Java se ejecuta, de forma similar a las
páginas HTML puede ser modificado para su presentación en las plataformas diferentes
que pueden acceder a la World Wide Web. Programmers can use Café Studio to choose
one of these AWT layout managers or to dictate the exact position and size of all interface
elements. Los programadores pueden utilizar Café Studio para elegir uno de estos
controladores de distribución del AWT o para dictar la posición y el tamaño exactos de
todos los elementos de la interfaz.
 Café offers the choice of using the JDK compiler or a Café compiler, which has been
optimized to work faster. Café ofrece la opción de utilizar el compilador JDK o un
compilador de Café, que ha sido optimizado para trabajar más rápido.
 With the Café debugging tool, there are different ways to halt the execution of code. Con
la herramienta de depuración Café, hay diferentes maneras de detener la ejecución de
código. These include a way to insert a one-time breakpoint that stops the running of a
program at a specific line. Estos incluyen una forma de insertar un punto de interrupción
una vez que se detiene el funcionamiento de un programa en una línea específica. The
debugger also enables you to control multi-threaded programs. El depurador también
permite controlar los programas multi-hilo. During debugging, you can use a watch view to
see the value of variables. Durante la depuración, puede utilizar una vista de seguimiento
para ver el valor de las variables.
 Symantec Café is highly customizable; all toolbars and palettes can be resized and placed
where you want them. Symantec Café es altamente personalizable, barras de
herramientas y todas las paletas pueden cambiar de tamaño y se coloca donde quieras.
 More than four dozen sample Java programs are included with Windows versions of Café,
and more than 90 are included with the Macintosh version. Más de cuatro docenas de
ejemplo los programas de Java se incluyen con las versiones de Windows de Café, y más
de 90 se incluyen con la versión para Macintosh. Many of these programs are duplicates of
the sample applets Sun offers with the JDK or on its Web site at . Muchos de estos
programas son duplicados de los applets de ejemplo Sun ofrece con el JDK o en su sitio
Web en http://java.sun.com .

Pricing and Additional Information Precios e información adicional

The most recent retail price for Café is $129.95 for Windows users. El precio de venta más
reciente para el Café es $ 129.95 para los usuarios de Windows. A comparable price is
being offered to Macintosh owners. Un precio similar se ofrece a los propietarios de
Macintosh. You can purchase Café from Symantec's Web site, as well as from retail and
mail-order outlets. Usted puede comprar café en el sitio Web de Symantec, así como en
puntos de venta por correspondencia y la venta al por menor.

Some folks might not have to buy Café at all! Algunas personas podrían no tener para
comprar café en absoluto! Customers who bought Symantec C++ between December 1,
1995, and March 1, 1996, are entitled to a free upgrade to Café. Los clientes que compraron
Symantec C + + del 1 de diciembre de 1995, y 1 de marzo de 1996, tienen derecho a una
actualización gratuita al Café.

The home page for Symantec Café is the following URL: La página web de Symantec Café
es el siguiente URL:

http://cafe.symantec.com/

The customer service number for the company is (800) 441-7234, and its e-mail address for
Java-related comments and questions is . El número de servicio al cliente para la empresa
es (800) 441-7234, y su dirección de correo electrónico para comentarios relacionados con
Java y preguntas javainfo@symantec.com.

SunSoft Java WorkShop SunSoft WorkShop Java


SunSoft Java WorkShop, the development tool offered by the language's home team, is an
IDE written almost entirely in Java. SunSoft Java WorkShop, la herramienta de desarrollo
ofrecidas por el equipo de origen de la lengua, es un IDE escrito casi en su totalidad en
Java. Its development was used at Sun to help improve the Java language by tackling a
large-scale software project using Java, but it also is a useful tool for Java programmers to
consider. Su desarrollo se utilizó en Sun para ayudar a mejorar el lenguaje Java, abordando
un proyecto de software a gran escala utilizando Java, pero también es una herramienta útil
para los programadores de Java a considerar. Figure B.3 shows an example of Java
WorkShop being used to develop a program. Figura B.3 muestra un ejemplo de Java
WorkShop está utilizando para desarrollar un programa.

Figura B.3. Java WorkShop in use. Java WorkShop en uso.

System Requirements Requisitos del sistema

Versions of Java WorkShop are available for the following systems: Microsoft Windows
95, Windows NT 3.5.1, SPARC Solaris (2.4 or later), and Intel x86 Solaris systems.
Versiones de Java WorkShop están disponibles para los siguientes sistemas: Microsoft
Windows 95, Windows NT 3.5.1, Solaris SPARC (2.4 o posterior), y los sistemas Intel x86
Solaris. Microsoft Windows 95 and NT systems must be running a 90MHz Pentium or
better with 16M of memory and 45M of hard disk space. Microsoft Windows 95 y NT debe
estar en ejecución un Pentium 90MHz o mejor con 16 millones de 45M de memoria y de
espacio en disco duro. Solaris systems must have 32M of memory, 45M of disk space, and
an OSF/Motif 1.2.3-compliant windowing system. sistemas Solaris deben tener 32M de
memoria, 45M de espacio en disco, y un OSF / Motif sistema de ventanas 1.2.3 compatible.
The recommended display resolution to use with Java WorkShop is 800 by 600 pixels. La
resolución de pantalla recomendada para su uso con Java WorkShop es de 800 por 600
píxeles.
Java WorkShop comes with its own modified version of the JDK, so you cannot use it in
conjunction with an existing installation of the Kit. Java WorkShop viene con su propia
versión modificada del JDK, por lo que no se puede utilizar en combinación con una
instalación existente del kit. Like Café, Java WorkShop requires that any existing JDK
copies be uninstalled before you can install and run WorkShop correctly. Al igual que Café,
Java WorkShop requiere que cualquier copia existente JDK ser desinstalado antes de poder
instalar y ejecutar Taller correctamente.

Overview Información general

Java WorkShop, one of the most approachable IDEs for a novice programmer, uses a Web
interface to offer a program text editor, class browser, debugger, project management
system, and Visual Java. Java WorkShop, uno de los IDEs más accesible para un
programador novato, utiliza una interfaz Web para ofrecer un editor de texto del programa,
navegador de clases, depurador, el sistema de gestión de proyectos, y Java, Visual. That last
tool provides a way to visually design a graphical interface. Esa última herramienta
proporciona una manera de diseñar visualmente una interfaz gráfica. WorkShop is fully
detailed in Teach Yourself SunSoft Java WorkShop in 21 Days, available now from
Sams.net Publishing. Taller se describen en detalle en Teach Yourself SunSoft Java
WorkShop en 21 días, a partir de ahora Sams.net publicación.

The most striking difference between Java WorkShop and other IDEs is its interface. La
diferencia más notable entre Java WorkShop y otros IDE es su interfaz. Java WorkShop
looks more like a Web browser than a programming development environment, because it
is a Web browser. Java WorkShop se parece más a un navegador Web de un entorno de
desarrollo de programación, ya que es un navegador Web. Java WorkShop's browser
interface is easier to use for programmers who are unfamiliar with more complex IDEs, but
the browser interface can be frustrating for developers who are comfortable with these
tools. interfaz Java WorkShop del navegador es más fácil de usar para los programadores
que no están familiarizados con entornos de desarrollo más complejo, pero la interfaz del
navegador puede ser frustrante para los desarrolladores que se sienten cómodos con estas
herramientas. WorkShop has a source browser for viewing variables, a class hierarchy, and
public methods. Taller tiene un navegador de código para las variables de visión, una
jerarquía de clases y métodos públicos. The browser creates HTML pages in the same
format as HTML documentation generated by the utility included with the JDK. El
navegador crea páginas HTML con el mismo formato de documentación HTML generado
por la utilidad javadoc incluido en el JDK.

The WorkShop program text editor lacks some of the cut-and-paste functionality of other,
more established editors. El programa del Taller editor de texto carece de algunas de las
funciones de cortar y pegar de otros editores, más establecidos. It works with WorkShop's
debugger so that compile errors create links directly into the editor for fixing. Funciona con
depurador WorkShop para que los errores de compilación crear vínculos directamente en el
editor para la fijación. The WorkShop debugger provides breakpoints and other methods of
debugging. El depurador WorkShop proporciona puntos de interrupción y otros métodos de
depuración.

Visual Java, like Café Studio, provides a way to graphically design an interface. Visual
Java, como el Café de estudio, proporciona una manera de diseñar una interfaz gráfica.
Programmers can develop dialog boxes and other visual elements and automatically create
handlers to respond to events generated by these components. Los programadores pueden
desarrollar cuadros de diálogo y otros elementos visuales y crear automáticamente los
controladores para responder a eventos generados por estos componentes.

The WorkShop environment is not customizable in the way Café is, but the Web interface
makes it easy to integrate other tools and programs into WorkShop. El ambiente del taller
no es personalizable en el Café manera es, pero la interfaz Web hace que sea fácil de
integrar otras herramientas y programas en el taller. Basically, the program is a group of
Web pages with Java programs featured on them. Básicamente, el programa es un conjunto
de páginas Web con programas Java que figuran en ellos. You can go to a different page
from within Java WorkShop as easily as you visit a URL in a Web browser. Usted puede ir
a una página diferente dentro de Java WorkShop tan fácilmente como usted visita una URL
en un explorador Web. This structure makes it possible for a programmer to create original
Java development tools that can be linked to WorkShop pages, an unusual feature. Esta
estructura permite a un programador para crear originales herramientas de desarrollo Java
que se pueden vincular a las páginas WorkShop, una característica inusual. This
arrangement is unorthodox in comparison to development environments that are cohesive,
unchangeable files. Esta disposición es poco ortodoxo en comparación con los entornos de
desarrollo que son archivos de cohesión, inmutable. However, it is compatible with the
approach to the Java language in general--small, self-contained programs that can reach out
to other programs over the Internet or other means. Sin embargo, es compatible con el
enfoque en el lenguaje Java en general - pequeño, los programas de auto-contenida que
puede llegar a otros programas a través de Internet u otros medios.

Pricing and Additional Information Precios e información adicional

SunSoft Java WorkShop currently sells over the World Wide Web for a retail price of
$84.99. SunSoft Java WorkShop actualmente vende más de la World Wide Web por un
precio al por menor de $ 84.99. The software can be downloaded for a free 30-day
evaluation. El software se puede descargar para una evaluación gratuita de 30 días. For
more details, visit the following URL: Para obtener más información, visite la siguiente
URL:
http://www.sun.com/sunsoft/Developer-
products/java/index.html

The customer service number to use for the company is (800) 786-7638 (SUN-SOFT) in
the United States or (512) 434-1511 elsewhere. El número de servicio al cliente a utilizar
para la empresa es (800) 786-7638 (SUN-SOFT) en los Estados Unidos o al (512) 434
hasta 1511 en otros lugares. The company's e-mail address for comments and questions is .
empresa de e-mail de comentarios y preguntas sunsoft@selectnet.com.

SourceCraft NetCraft SourceCraft NetCraft


SourceCraft, the developer of the ObjectCraft development environment, is making its Java
IDE, NetCraft, available at no cost if you comply with the terms and conditions for use.
SourceCraft, el desarrollador del entorno de desarrollo ObjectCraft, está haciendo su Java
IDE, Netcraft, disponible sin costo alguno siempre y cuando cumpla con los términos y
condiciones de uso. This makes NetCraft attractive because of the cost, but the IDE still
must be useful to you or you will pay in other ways due to lost efficiency. Esto hace que
NetCraft atractivo debido a su costo, pero el IDE todavía debe ser útil para usted o usted
tendrá que pagar de otra manera debido a la pérdida de eficiencia. Figure B.4 provides a
screen shot of the NetCraft environment. Figura B.4 proporciona una captura de pantalla
del medio ambiente Netcraft.

Figura B.4. NetCraft at work. NetCraft en el trabajo.

System Requirements Requisitos del sistema

Versions of NetCraft are available for Microsoft Windows 95 and Windows NT 3.5.1
systems running a 486 or better with 8M of memory. Las versiones de NetCraft están
disponibles para Microsoft Windows 95 y Windows NT 3.5.1 ejecutando un 486 o superior
con 8 millones de la memoria. NetCraft comes bundled with the current version of the JDK;
SourceCraft also makes NetCraft available for download without the JDK if you already
have the JDK installed. NetCraft viene incluido con la versión actual del JDK, SourceCraft
también hace NetCraft disponible para su descarga sin JDK si ya tiene instalado el JDK.

Overview Información general

SourceCraft NetCraft does not offer as many features as other IDEs, but it is a comparable
replacement for the JDK. SourceCraft NetCraft no ofrece tantas características como otros
IDE, pero es un reemplazo comparable para el JDK. It creates Java programs that are
usable across Java implementations for all systems. La creación de programas Java que se
pueden utilizar en las implementaciones de Java para todos los sistemas. NetCraft has an
editor, class inspector, user interface designer, and compiler. NetCraft dispone de un editor,
el inspector de la clase, diseñador de interfaz de usuario, y el compilador.
You can use NetCraft for any type of Java applet or application. Usted puede utilizar
NetCraft para cualquier tipo de applet de Java o de la aplicación. You can use the Package
Inspector, part of NetCraft's system for organizing projects, to browse class methods. Puede
usar el Inspector de paquete, que forma parte del sistema de NetCraft para organizar
proyectos, para buscar métodos de la clase. The Class Inspector can show you the position
of a class in the hierarchy, its methods, and its variables. El Inspector de clase se puede
mostrar la posición de una clase en la jerarquía, sus métodos y sus variables. You can view
the source code of the method and how it is used in a program when you are looking at a
method with this tool. Usted puede ver el código fuente del método y la forma en que se
utiliza en un programa cuando usted está buscando en un método con esta herramienta.

Like Café and Java WorkShop, NetCraft includes a way to visually create a graphical user
interface. Al igual que Café y Taller de Java, NetCraft incluye una forma de crear
visualmente una interfaz gráfica de usuario. The UI Builder generates Java code that uses
the Abstract Windowing Toolkit, so the program does not rely on any new classes
introduced with the development environment. El Generador de la interfaz de usuario
genera código Java que utiliza el kit de herramientas de ventana de Resumen, por lo que el
programa no se basa en las clases novedades introducidas con el entorno de desarrollo.
When you create an interface component, NetCraft generates Java statements for that
component, complete with a comment line where the action event handling statements for
that component are placed. Cuando se crea un componente de la interfaz, NetCraft genera
estados de Java para ese componente, con una línea de comentario TODO en caso de
instrucciones de control de ese componente se colocan la acción. The approach is simpler
than some of the alternatives, so a programmer familiar with the AWT should be
comfortable with it. El enfoque es más simple que algunas de las alternativas, por lo que un
programador familiarizado con el AWT debe ser cómodo con él.

NetCraft's program editor uses cut-and-paste commands and is similar to other small word
processors. editor de Netcraft programa utiliza comandos de cortar y pegar y es similar a
otros procesadores de texto pequeño. Though the components in the currently available
release have the odd habit of moving around a little after they are clicked, a nice feature of
the builder is the capability to set a component's height and width coordinates by entering
numbers into text fields. Aunque los componentes de la versión actualmente disponible
tiene el extraño hábito de moverse un poco después de hacer clic sobre ellos, una buena
característica del constructor es la capacidad para establecer la altura de un componente y la
anchura de las coordenadas mediante la introducción de números en los campos de texto.
This feature enables you to easily align wandering components with each other. Esta
característica le permite alinear fácilmente vagando componentes entre sí.

The NetCraft environment is simpler to use than other IDEs, but this simplicity might be a
problem when you need to create programs that have numerous windows and interactive
components. El entorno de Netcraft es simple de usar que otros IDE, pero esta simplicidad
puede ser un problema cuando se necesita para crear programas que tienen numerosas
ventanas y componentes interactivos. Some of the tools that can make complex software
more manageable to design are not available in NetCraft. Algunas de las herramientas que
puede hacer el software más complejo de manejar para el diseño no están disponibles en
Netcraft. NetCraft appears to be a good substitute for JDK users who want to use a
graphical interface as they write simple programs and applets. NetCraft parece ser un buen
sustituto para los usuarios de JDK que se quiere utilizar una interfaz gráfica, ya que escribir
programas simples y applets. Because it is free, this IDE can be a good place for novices to
start when they're deciding which IDE to use. Debido a que es gratuito, este IDE puede ser
un buen lugar para los principiantes comenzar cuando están decidiendo que IDE utilizar.

Pricing and Additional Information Precios e información adicional

For more details and the opportunity to download NetCraft at no cost, visit the home page
for NetCraft at the following URL: Para obtener más detalles y la oportunidad de descargar
NetCraft sin costo, visite la página de inicio para NetCraft en la siguiente URL:

http://www.sourcecraft.com:4800/about/netcraft/

The customer service number for the company is (617) 221-5665; the company's e-mail
address for comments and questions is . El número de servicio al cliente para la empresa es
(617) 221-5665; empresa de e-mail de comentarios y preguntas edc@sourcecraft.com.

Pro-C WinGEN for Java Pro-C Wingen para Java


Pro-C WinGEN for Java is an IDE designed for people who do not write programs. Pro-C
Wingen para Java es un IDE diseñado para personas que no escriben programas. The focus
is on automatically generating code so that HTML designers and other programming
novices can develop Java programs. La atención se centra en la generación automática de
código para que los diseñadores de HTML y otros novatos de programación puede
desarrollar programas en Java. You can develop the graphical interface of an applet or
application using drag-and-drop and introduce elements such as animation without writing
a single Java statement. Usted puede desarrollar la interfaz gráfica de un applet o aplicación
con sólo arrastrar y soltar "e introducir elementos tales como la animación sin escribir una
sola declaración de Java. The IDE calls the JDK from within WinGEN to run and compile
programs. El IDE pide el JDK desde Wingen para compilar y ejecutar programas. Figure
B.5 shows the WinGEN environment. Figura B.5 muestra el entorno Wingen.

Figura B.5. WinGEN for Java in use. Wingen para Java en uso.

System Requirements Requisitos del sistema


Versions of WinGEN are available for Microsoft Windows 95 and Windows NT 3.5.1
systems running a 486 or better with 8M of memory and 10M of hard disk space. Las
versiones de Wingen están disponibles para Microsoft Windows 95 y Windows NT 3.5.1
ejecutando un 486 o superior con 8 millones de la memoria y 10M de espacio en disco
duro. To unpack WinGEN Lite, the evaluation edition of the software, you must have a
program that can unpack ZIP files into long file names. Para descomprimir Wingen Lite, la
versión de evaluación del software, debe tener un programa que puede descomprimir
archivos ZIP en nombres de archivo largos. (For users of Windows systems, the Windows
95 operating system introduced file names longer than eight characters and a three-
character extension.) If you use a ZIP unpack program that does not support long file
names, files will not be named correctly, and the setup will fail. (Para los usuarios de
sistemas Windows, el sistema operativo Windows 95 introdujo los nombres de archivo de
más de ocho caracteres y una extensión de tres caracteres.) Si utiliza un programa
descomprimir ZIP que no admite nombres largos de archivo, los archivos no se llamará
correctamente, y la instalación fallará. WinGEN includes the current version of the JDK,
which must be installed before WinGEN is installed so that the IDE will function. Wingen
incluye la versión actual del JDK, que debe estar instalado antes de Wingen está instalado
de manera que el IDE funcionará.

Overview Información general

WinGEN supports the JDK rather than replacing it and can run the Kit's compiler and
interpreter from within the IDE. Wingen apoya el JDK en lugar de reemplazarlo y se puede
ejecutar el compilador de Kit e intérprete desde el IDE. Because of WinGEN's focus on
beginners, WinGEN emphasizes a point-and-click approach to graphical user interface
creation. Debido a centrarse Wingen en principiantes, Wingen hace hincapié en un enfoque
de apuntar y hacer clic para crear la interfaz gráfica de usuario. You can create many user
events through WinGEN without any programming. Usted puede crear muchos eventos de
usuario a través de Wingen sin necesidad de programación.

The arrangement of WinGEN's user interface should be familiar to programmers who have
used other GUI design tools, especially for those who have used Visual Basic. La
disposición de la interfaz de usuario Wingen debe ser familiar para los programadores que
han utilizado otras herramientas de diseño de interfaz gráfica de usuario, especialmente
para aquellos que han utilizado Visual Basic. The current WinGEN version can be difficult
to use when aligning components, but laying out text fields, labels, and other things is
easier than it can be with other programming tools. La versión actual Wingen puede ser
difícil de utilizar al alinear los componentes, pero por el que se centran en campos de texto,
etiquetas y otras cosas es más fácil de lo que puede con las herramientas de programación.
The IDE takes a resource-centric view of development. El IDE tiene una visión centrada en
los recursos de desarrollo. What this means is that you start with the menus and dialog
boxes and then create programming functions rather than using programming to create
those components. Lo que esto significa es que usted comienza con los menús y cuadros de
diálogo y luego crear las funciones de programación en lugar de utilizar la programación
para crear los componentes. One thing that WinGEN does not offer is the capability to
preview a program's interface before any Java statements have been generated. Una cosa
que Wingen no ofrece es la capacidad de vista previa de la interfaz de un programa antes de
cualquier declaración de Java se han generado.

A system called CodeHooks enables you to add Java statements that handle circumstances
WinGEN can't handle. Un sistema llamado CodeHooks le permite añadir sentencias Java
que se encargan de las circunstancias Wingen no puede manejar. These hooks, which
accomplish specific tasks like a special event handler, are separated from the statements
that WinGEN automatically generates. Estos ganchos, que cumplen tareas específicas,
como un controlador de eventos especiales, se separan de las declaraciones que Wingen
genera automáticamente. This separation of statements enables programmers to change the
GUI and use CodeHooks without reentering anything. Esta separación de los estados
permite a los programadores para cambiar la interfaz gráfica de usuario y CodeHooks uso
sin volver a escribir nada.

WinGEN can be useful for the programming of simple applets and applications or as a tool
for Java novices. Wingen puede ser útil para la programación de applets y aplicaciones
simples o como una herramienta para los principiantes de Java. Though it lacks a debugger,
source browser, and other IDE features, later versions of the software might implement
some of these tools. A pesar de que carece de un depurador, explorador de código fuente, y
otras características del IDE, las versiones posteriores del software podría poner en práctica
algunas de estas herramientas.

Pricing and Additional Information Precios e información adicional

You can purchase WinGEN online for $79.95. Usted puede comprar Wingen en línea por $
79.95. For more details, the opportunity to download WinGEN Lite at no cost, or to
purchase the full version online, visit the home page for WinGEN at the following URL:
Para más detalles, la oportunidad de descargar Wingen Lite sin costo alguno, o para
comprar la versión completa en línea, visite la página de inicio para Wingen en la siguiente
URL:

http://www.pro-c.com/products/wfj/java.html

The phone number at Pro-C for inquiries related to the software is (813) 227-7762; the
company's e-mail address for comments and questions regarding WinGEN is . El número
de teléfono en el Pro-C para las investigaciones relacionadas con el software (813) 227-
7762; empresa de e-mail de comentarios y preguntas sobre Wingen es support@pro-
c.com.

Other Offerings Otras ofertas


The following products for Java development are profiled to provide a more complete
picture of the programming tools that are available. Los siguientes productos para el
desarrollo de Java se perfilan para ofrecer una imagen más completa de las herramientas de
programación que están disponibles.

Borland C++ 5.0 with Java Enhancements Borland C + + 5.0 con Java Mejoras

Borland C++ 5.0 with Java Enhancements is a C++ development environment that has been
extended to include Java programming tools. Borland C + + 5.0 con mejoras de Java es un
C + + entorno de desarrollo que se ha ampliado para incluir las herramientas de
programación Java. The advantages of this approach are multilanguage development within
the same environment for native method use, the capability to program in three languages
(C, C++, and Java) without learning three IDEs, and the use of software that has become
robust from several years of use by the C and C++ development community. The home
page for Borland's Internet development tools is as follows:

http://www.borland.com/internet/ .

MetroWerks CodeWarrior

CodeWarrior is one of several IDEs that are available for Apple Macintosh or Microsoft
Windows Java development. CodeWarrior is a multilanguage development environment
with an introductory version called Discover Programming with Java that is intended for
novices. You can use CodeWarrior to develop programs in C, C++, ObjectPascal, and Java.
One interesting feature of this development environment is that you can compile Windows
versions of a Java program using a Macintosh and vice versa. The main page for
MetroWerks is the following URL:

http://www.metrowerks.com

Kalimantan Kalimantan

Before being christened Kalimantan, this IDE was one of several Java-related products that
staked a claim to the name Espresso. Antes de ser bautizado como Kalimantan, este IDE
fue uno de varios productos relacionados con Java que plantear una reivindicación al
nombre Espresso. The developers have been kind enough to offer links to the other
Espressos, so the Kalimantan Web page is a good place to sort out any Espresso confusion
you may have.

Kalimantan is another cross-platform IDE. It has been tested for use with Solaris 2.4 and
up, as well as Windows 95 systems. Kalimantan's current beta release includes only an
inspector to look at the values of internal variables and a debugger, but it is bundled with
the teikade suite of utilities from PFU Limited. This suite includes a class browser that is
familiar to those who have used class browsers with the Smalltalk programming language.
The home page for Kalimantan is the following URL:

http://www.real-time.com/java/kalimantan/index.html

Natural Intelligence Roaster

Roaster was made available to developers in January 1996, making it the first Java IDE for
the Macintosh. The Roaster Professional Edition includes a visual interface builder, the
ability to compile programs that can be targeted for Macintosh or Microsoft Windows
systems, and an extended class library. The Sams.net book Teach Yourself Java for the
Macintosh in 21 Days was written for the Roaster environment. Details on Roaster are
available from the following URL:

http://www.natural.com/pages/products/roaster/index.html

Microsoft Visual J++

Microsoft Visual J++ is Microsoft's machine-proprietary answer to Java development. It


features extensions to the Java class library that are specific to Microsoft's operating system
and integrates Java with the component object model (COM) through Microsoft ActiveX.
Visual J++ is integrated with the Internet Explorer browser that implemented Java with its
3.0 release. The home page for Visual J++ is the following URL:

http://www.microsoft.com/visualj/

Summary Resumen
The integrated development environment that you choose depends on many factors: your
programming experience, the tasks you must accomplish, and personal preference. El
entorno de desarrollo integrado que usted elija depende de muchos factores: su experiencia
en programación, las tareas que debe realizar, y las preferencias personales. Java Usenet
newsgroups such as and are a way to get a range of user opinions on the IDEs you are
considering. Java grupos de noticias Usenet, como comp.lang.java.misc y
comp.lang.java.programmer son una manera de conseguir una amplia gama de opiniones
sobre el IDE que está considerando. Many IDE developers also participate in these forums,
including Symantec representatives and the developers of Java WorkShop. Muchos
desarrolladores de IDE también participan en estos foros, incluidos los representantes de
Symantec y los desarrolladores de Java WorkShop.

Most Java IDEs that are not in final release can be downloaded over the World Wide Web.
La mayoría de los IDEs de Java que no están en la versión final puede ser descargado en la
World Wide Web. It can be troublesome to download and install these trial versions,
especially if you must first uninstall something else, but the approaches taken in each IDE
are worth examining in detail. Puede ser un problema para descargar e instalar las versiones
de prueba, especialmente si usted primero debe desinstalar otra cosa, pero los enfoques
adoptados en cada IDE Vale la pena examinar en detalle. Of course, if you have grown
comfortable with the Java Developer's Kit from your use of it during this book, no one says
you have to use one of the more complex IDEs. Por supuesto, si usted ha crecido a gusto
con el Kit de Desarrollo Java de su uso de ella durante este libro, nadie dice lo que tienes
que usar uno de los IDEs más complejo.

Potrebbero piacerti anche