Sunteți pe pagina 1din 61

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES

UNIDADES TECNOLOGICAS DE SANTANDER


DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PROGRAMACION VISUAL CON


JAVA E IDE NETBEANS

UNIDADES TECNOLOGICAS DE SANTADER.

TECNOLOGIA EN TELECOMUNICACIONES
NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

TABLA DE CONTENIDO
Graphics

Comando principales de Graphics

PRACTICA 1. Creacin de Crculos con Graphics utilizando Beans

15

PRACTICA 2. Manejo de Grficos, utilizando Beans

24

PRACTICA 3. Creacin de Lneas y Figuras. Utilizando JPanel.

30

PRACTICA 4. Creacin de Arcos. Utilizando JPanel.

35

PRACTICA 5. Dibujo de polgonos. Utilizando JPanel.

40

PRACTICA 6. Dibujo de figuras de Java2D. Utilizando JPanel.

45

PRACTICA 7. Dibujo de figuras dibujar con rutas generales. Utilizando JPanel.

50

PRACTICA 8. Movimientos de figuras. Utilizando JPanel.

55

NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Graphics
La clase Graphics:
Casi todas las componentes y contenedores de Swing tienen un mtodo paint(g)
asociado que sirve para dibujarlos en pantalla. Java invoca este mtodo
automticamente cuando tiene que mostrar, de forma estndar, la componente o
contenedor en cuestin (esto es, sus bordes, su ttulo, si lo tiene, etc.)
El mtodo paint(g) se redefine cuando se quiere que estos elementos tengan un
aspecto particular, por ejemplo, cuando se quiere dibujar algo especfico sobre ellos.
El mtodo paint(g) es de la forma
public void paint(Graphics g) {
...
}
Donde g es un objeto de la clase abstracta Graphics. Todo contenedor o componente
que se pueda dibujar en pantalla tiene asociado un objeto g de esta clase, con la
informacin sobre el rea de la pantalla que el
contenedor o la componente cubre. Adems, el objeto g dispone de mtodos para
hacer grficos (dibujar crculos, rectngulos, lneas, etc.)
La clase Graphics se importa de awt:
import java.awt.*;
Cuando el mtodo paint(g) se ejecuta es porque ha sido invocado por otros mtodos,
nunca invocado por
nosotros, y el parmetro que usa corresponde a un objeto de la clase Graphics asociado
al contenedor o
componente que estemos manejando.
Cuando se redefine el mtodo paint(g), siempre se comienza con una invocacin
super.paint(g) al mtodo de la superclase, asegurando as que se dibuja la parte
estndar del contenedor o componente que estemos manejando.
Por ejemplo, vamos a dibujar una cara en un marco. Un marco es un elemento de la
clase JFrame y para dibujar en l procedemos as:

NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

public void paint (Graphics g){


super.paint(g);
//Dibujo el contorno de la cara
g.setColor(Color.BLACK);
g.fillOval(105, 70, 100, 100);
//Dibujo de los ojos
g.setColor(Color.GREEN);
g.fillOval(125, 100, 10, 10);
g.fillOval(175, 100, 10, 10);
//Dibujo de la nariz
g.drawLine(150, 100, 150, 130);
//Dibujo de la boca
g.drawArc(118, 120, 75, 30, 180, 180);
}
Para entender lo que ha hecho el mtodo anterior hay que saber que:

El sistema de coordenadas de un contenedor tiene su origen en su esquina


superior izquierda.
Las abscisas se incrementan hacia la derecha y las ordenadas hacia abajo.
Cada punto es un pxel.
En general, el dibujo de una figura (rectngulo, elipse, rectngulo redondo, etc.)
se realiza dando las coordenadas de la esquina superior izquierda de
un rectngulo imaginario que la contiene.

Algunos mtodos de la clase Graphics para dibujar figuras son:

drawLine(x1,y1,x2,y2): dibuja una lnea recta desde el punto (x1,y1) al punto


(x2,y2)
fillRect(x,y,ancho,alto): rellena el rectngulo que tiene su esquina superior
izquierda en (x,y) y el ancho y largo dados
drawOval(x,y,ancho,alto): dibuja una elipse contenida en un rectngulo
imaginario cuya esquina superior izquierda est en (x,y) y tiene el ancho y largo
dados
fillOval(x,y,ancho,alto): rellena la elipse especificada
pordrawOval(x,y,ancho,largo)

NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

drawArc(x,y,ancho,alto, inicioAngulo,barridoAngulo): dibuja parte de una elipse


dentro de un rectngulo imaginario cuya esquina superior izquierda est en (x,y),
tiene el largo y ancho dados, empieza a dibujar en el ngulo inicioAngulo y hace
un barrido de barridoAngulo
setColor(Color.red): cambia la tinta del objeto g y la pone de color rojo. La
clase Color se importa de awt:
import java.awt.*;

Dibujar sobre Paneles

Cuando se actualiza un componente, se borra su aspecto actual y seinvoca


paint(g). El borrado previo puede producir parpadeo (flickering) ,por lo que a
veces el mtodo paint(g) evita hacerlo.
Sin embargo, la actualizacin puede necesitar hacer el borrado previo(para
actualizar el fondo del componente, por ejemplo). En estos casos se invoca el
mtodo paintComponent(g) de la clase JComponent, que permite hacer un
barrido previo, pero usando la tcnica del doble buffer para eliminar el parpadeo.
En casos como los anteriores lo que se hace es redefinir el
mtodo paintComponent(g) en lugar del mtodo paint(g).

Por ejemplo, para dibujar la cara que pintamos antes, pero sobre un (j)panel en lugar
de sobre un marco, hacemos lo siguiente:

Se declara la clase PanelCara que extiende la clase JPanel, como clase (privada)
de la clase MarcoCara que habamos creado antes
Se redefine el mtodo paintComponent(g) usando las mismas instrucciones que
antes, pero llamando inicialmente a super.paintComponent(g)
public void paintComponent(Graphics g) {
super.paintComponent(g);...}

Cuando el contenido de un marco o panel cambia, el mtodo repaint() se encarga


de actualizar el contenedor y mostrarlo por pantalla, invocando implcitamente el
mtodo paint(g) o paintComponent(g).
Por ejemplo, para aadir un botn al marco que mostraba una cara sonriente de forma
que, cuando se pulse, la cara cambie a una cara eenojada, basta hacer lo siguiente:

Se aade a contentPane el botn cuyo efecto cambiar la sonrisa de la cara


Se aade un atributo booleano al marco que indica si la cara sonre o no
private boolean sonrie=true;

NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Dentro del actionPerformed del boton codeamos lo siguiente:


sonrie=!sonrie;
repaint();

El mtodo paintComponent(g) para pintar el panel se redefine por el siguiente:


public void paintComponent(Graphics g) {
super.paintComponent(g);
//Dibujo de la cara igual que antes, salvo la boca
...
//Dibujo de la boca
if (sonrie) g.drawArc(118, 125, 75, 30, 180, 180);
else g.drawArc(118, 125, 75, 30, 180, -180);
}

Dibujar texto
La clase Graphics permite dibujar texto, como alternativa al texto mostrado en los
componentes JLabel, JTextField y JTextArea. El mtodo que permite graficar texto sobre
el JFrame es:

drawString(String str, int x, int y);

Clase Color

La clase java.awt.Color encapsula colores utilizando el formato RGB (Red, Green, Blue).
Las componentes de cada color primario en el color resultante se expresan con nmeros
enteros entre 0 y 255, siendo 0 la intensidad mnima de ese color y 255 la mxima. En
la clase Color existen constantes para colores predeterminados de uso frecuente: black,
white, green, blue, red, yellow, magenta, cyan, orange, pink, gray, darkGray, lightGray.

NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Presentacin de imgenes
Java permite incorporar imgenes de tipo GIF y JPEG definidas en ficheros. Se dispone
para ello de la clase java.awt.Image. Para cargar una imagen hay que indicar la
localizacin del archivo y cargarlo mediante el mtodo getImage(). Este mtodo existe
en las clases java.awt.Toolkit.
Entonces, para cargar una imagen hay que comenzar creando un objeto (o una
referencia) Image y llamar al mtodo getImage() (de Toolkit); Una vez cargada la
imagen, hay que representarla, para lo cual se redefine el mtodo paint() para llamar al
mtodo drawImage() de la clase Graphics. Los objetos Graphics pueden mostrar
imgenes a travs del mtodo: drawImage(). Dicho mtodo admite varias formas,
aunque casi siempre hay que incluir el nombre del objeto imagen creado.
Clase Image
Una imagen es un objeto grfico rectangular compuesto por pixels coloreados. Cada
pixel en una imagen describe un color de una particular localizacin de la imagen.
A continuacin, algunos mtodos de la clase Image:
La clase Graphics provee el mtodo drawImage() para dibujar imagenes; este mtodo
admite varias formas:
- drawImage (Image i, int x, int y, ImageObserver o)
- drawImage (Image i,int x,int y,int width,int height,ImageObserver o)
Un ejemplo del metodo paint(Graphics G) para traer una imagen de la carpeta raiz es el
siguiente:
public void paint (Graphics g)
{
super.paint(g);
Toolkit t = Toolkit.getDefaultToolkit ();
Image imagen = t.getImage ("imagen1.jpg");
g.drawImage (imagen, 0, 0, this);
}
NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Comando principales de Graphics


1. public abstract void clearRect(int x, int y, int width, int height)
Clears the specified rectangle by filling it with the background color of the current
drawing surface. This operation does not use the current paint mode.
Beginning with Java 1.1, the background color of offscreen images may be system
dependent. Applications should use setColor followed by fillRect to ensure that an
offscreen image is cleared to a specific color.
Parameters:
x - the x coordinate of the rectangle to clear.
y - the y coordinate of the rectangle to clear.
width - the width of the rectangle to clear.
height - the height of the rectangle to clear.

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


Intersects the current clip with the specified rectangle. The resulting clipping area is the
intersection of the current clipping area and the specified rectangle. If there is no
current clipping area, either because the clip has never been set, or the clip has been
cleared using setClip(null), the specified rectangle becomes the new clip. This method
sets the user clip, which is independent of the clipping associated with device bounds
and window visibility. This method can only be used to make the current clip smaller. To
set the current clip larger, use any of the setClip methods. Rendering operations have
no effect outside of the clipping area.
Parameters:
x - the x coordinate of the rectangle to intersect the clip with
y - the y coordinate of the rectangle to intersect the clip with
width - the width of the rectangle to intersect the clip with
height - the height of the rectangle to intersect the clip with

3. public abstract void copyArea(int x, int y, int width, int height, int dx, int dy)
Copies an area of the component by a distance specified by dx and dy. From the point
specified by x and y, this method copies downwards and to the right. To copy an area of
NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

the component to the left or upwards, specify a negative value for dx or dy. If a portion
of the source rectangle lies outside the bounds of the component, or is obscured by
another window or component, copyArea will be unable to copy the associated pixels.
The area that is omitted can be refreshed by calling the component's paint method.
Parameters:
x - the x coordinate of the source rectangle.
y - the y coordinate of the source rectangle.
width - the width of the source rectangle.
height - the height of the source rectangle.
dx - the horizontal distance to copy the pixels.
dy - the vertical distance to copy the pixels.

4. public void draw3DRect(int x, int y, int width, int height, boolean raised)
Draws a 3-D highlighted outline of the specified rectangle. The edges of the rectangle
are highlighted so that they appear to be beveled and lit from the upper left corner.
The colors used for the highlighting effect are determined based on the current color.
The resulting rectangle covers an area that is width + 1 pixels wide by height + 1 pixels
tall.
Parameters:
x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.
raised - a boolean that determines whether the rectangle appears to be raised above
the surface or sunk into the surface.

5. public abstract void drawArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Draws the outline of a circular or elliptical arc covering the specified rectangle.
The resulting arc begins at startAngle and extends for arcAngle degrees, using the
current color. Angles are interpreted such that 0 degrees is at the 3 o'clock position. A
positive value indicates a counter-clockwise rotation while a negative value indicates a
clockwise rotation.
NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

The center of the arc is the center of the rectangle whose origin is (x, y) and whose size
is specified by the width and height arguments.
The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.
The angles are specified relative to the non-square extents of the bounding rectangle
such that 45 degrees always falls on the line from the center of the ellipse to the upper
right corner of the bounding rectangle. As a result, if the bounding rectangle is
noticeably longer in one axis than the other, the angles to the start and end of the arc
segment will be skewed farther along the longer axis of the bounds.
Parameters:
x - the x coordinate of the upper-left corner of the arc to be drawn.
y - the y coordinate of the upper-left corner of the arc to be drawn.
width - the width of the arc to be drawn.
height - the height of the arc to be drawn.
startAngle - the beginning angle.
arcAngle - the angular extent of the arc, relative to the start angle.

6. public abstract boolean drawImage(Image img, int x, int y, ImageObserver


observer)
Draws as much of the specified image as is currently available. The image is drawn with
its top-left corner at (x, y) in this graphics context's coordinate space. Transparent
pixels in the image do not affect whatever pixels are already there.
This method returns immediately in all cases, even if the complete image has not yet
been loaded, and it has not been dithered and converted for the current output device.
If the image has completely loaded and its pixels are no longer being changed, then
drawImage returns true. Otherwise, drawImage returns false and as more of the image
becomes available or it is time to draw another frame of animation, the process that
loads the image notifies the specified image observer.
Parameters:
img - the specified image to be drawn. This method does nothing if img is null.
x - the x coordinate.
y - the y coordinate.
observer - object to be notified as more of the image is converted.
Returns:
false if the image pixels are still changing; true otherwise.
NETBEANS

PROGRAMACION VISUAL

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

7. public abstract void drawLine(int x1, int y1, int x2, int y2)
Draws a line, using the current color, between the points (x1, y1) and (x2, y2) in this
graphics context's coordinate system.
Parameters:
x1
y1
x2
y2

the
the
the
the

first point's x coordinate.


first point's y coordinate.
second point's x coordinate.
second point's y coordinate.

8. public abstract void drawOval(int x, int y, int width, int height)


Draws the outline of an oval. The result is a circle or ellipse that fits within the rectangle
specified by the x, y, width, and height arguments.
The oval covers an area that is width + 1 pixels wide and height + 1 pixels tall.
Parameters:
x - the x coordinate of the upper left corner of the oval to be drawn.
y - the y coordinate of the upper left corner of the oval to be drawn.
width - the width of the oval to be drawn.
height - the height of the oval to be drawn.

9. public abstract void drawPolyline(int[] xPoints, int[] yPoints, int nPoints)


Draws a sequence of connected lines defined by arrays of x and y coordinates. Each pair
of (x, y) coordinates defines a point. The figure is not closed if the first point differs
from the last point.
Parameters:
xPoints - an array of x points
yPoints - an array of y points
nPoints - the total number of points

NETBEANS

PROGRAMACION VISUAL

10

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

10. public void drawRect(int x, int y, int width, int height)


Draws the outline of the specified rectangle. The left and right edges of the rectangle
are at x and x + width. The top and bottom edges are at y and y + height. The
rectangle is drawn using the graphics context's current color.
Parameters:
x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.

11. public abstract void drawRoundRect(int x, int y, int width, int height, int arcWidth,
int arcHeight)
Draws an outlined round-cornered rectangle using this graphics context's current color.
The left and right edges of the rectangle are at x and x + width, respectively. The top
and bottom edges of the rectangle are at y and y + height.
Parameters:
x - the x coordinate of the rectangle to be drawn.
y - the y coordinate of the rectangle to be drawn.
width - the width of the rectangle to be drawn.
height - the height of the rectangle to be drawn.
arcWidth - the horizontal diameter of the arc at the four corners.
arcHeight - the vertical diameter of the arc at the four corners.

12. public abstract void drawString(String str, int x, int y)


Draws the text given by the specified string, using this graphics context's current font
and color. The baseline of the leftmost character is at position (x, y) in this graphics
context's coordinate system.
Parameters:
str - the string to be drawn.
x - the x coordinate.
y - the y coordinate

NETBEANS

PROGRAMACION VISUAL

11

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

13. public void fill3DRect(int x, int y, int width, int height, boolean raised)
Paints a 3-D highlighted rectangle filled with the current color. The edges of the
rectangle will be highlighted so that it appears as if the edges were beveled and lit from
the upper left corner. The colors used for the highlighting effect will be determined from
the current color.
Parameters:
x - the x coordinate of the rectangle to be filled.
y - the y coordinate of the rectangle to be filled.
width - the width of the rectangle to be filled.
height - the height of the rectangle to be filled.
raised - a boolean value that determines whether the rectangle appears to be raised
above the surface or etched into the surface.

14. public abstract void fillArc(int x, int y, int width, int height, int startAngle, int
arcAngle)
Fills a circular or elliptical arc covering the specified rectangle.
The resulting arc begins at startAngle and extends for arcAngle degrees. Angles are
interpreted such that 0 degrees is at the 3 o'clock position. A positive value indicates a
counter-clockwise rotation while a negative value indicates a clockwise rotation.
The center of the arc is the center of the rectangle whose origin is (x, y) and whose size
is specified by the width and height arguments.
The resulting arc covers an area width + 1 pixels wide by height + 1 pixels tall.
The angles are specified relative to the non-square extents of the bounding rectangle
such that 45 degrees always falls on the line from the center of the ellipse to the upper
right corner of the bounding rectangle. As a result, if the bounding rectangle is
noticeably longer in one axis than the other, the angles to the start and end of the arc
segment will be skewed farther along the longer axis of the bounds.
Parameters:
x - the x coordinate of the upper-left corner of the arc to be filled.
y - the y coordinate of the upper-left corner of the arc to be filled.
width - the width of the arc to be filled.
height - the height of the arc to be filled.
NETBEANS

PROGRAMACION VISUAL

12

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

startAngle - the beginning angle.


arcAngle - the angular extent of the arc, relative to the start angle.

15. public abstract void fillOval(int x, int y, int width, int height)
Fills an oval bounded by the specified rectangle with the current color.
Parameters:
x - the x coordinate of the upper left corner of the oval to be filled.
y - the y coordinate of the upper left corner of the oval to be filled.
width - the width of the oval to be filled.
height - the height of the oval to be filled.

16. public abstract void fillPolygon(int[] xPoints, int[] yPoints, int nPoints)
Fills a closed polygon defined by arrays of x and y coordinates.
This method draws the polygon defined by nPoint line segments, where the first nPoint 1 line segments are line segments from (xPoints[i - 1], yPoints[i - 1]) to
(xPoints[i], yPoints[i]), for 1 i nPoints. The figure is automatically closed by drawing
a line connecting the final point to the first point, if those points are different.
The area inside the polygon is defined using an even-odd fill rule, also known as the
alternating rule.
Parameters:
xPoints - a an array of x coordinates.
yPoints - a an array of y coordinates.
nPoints - a the total number of points.

17. public abstract void fillRoundRect(int x, int y, int width, int height, int arcWidth, int
arcHeight)
Fills the specified rounded corner rectangle with the current color. The left and right
edges of the rectangle are at x and x + width - 1, respectively. The top and bottom
edges of the rectangle are at y and y + height - 1.
Parameters:
NETBEANS

PROGRAMACION VISUAL

13

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

x - the x coordinate of the rectangle to be filled.


y - the y coordinate of the rectangle to be filled.
width - the width of the rectangle to be filled.
height - the height of the rectangle to be filled.
arcWidth - the horizontal diameter of the arc at the four corners.
arcHeight - the vertical diameter of the arc at the four corners.

18. public abstract void setColor(Color c)


Sets this graphics context's current color to the specified color. All subsequent graphics
operations using this graphics context use this specified color.
Parameters:
c - the new rendering color.

19. public abstract void setFont(Font font)


Sets this graphics context's font to the specified font. All subsequent text operations
using this graphics context use this font. A null argument is silently ignored.
Parameters:
font - the font.

NETBEANS

PROGRAMACION VISUAL

14

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 1. Creacin de Crculos con


Graphics utilizando Beans
Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras Sesion7. Agrega un JFrame
llamado MainFrame. Debers tener una estructura de proyecto similar a la que se ve en
la siguiente fotografa:

Paso 2:
Crea la siguiente interfaz grfica:

El control de la parte de abajo se llama JTextArea y es un JTextField que puede tener


ms de un rengln. Al agregar un JTextArea automaticamente se agrega un JScrollPane
que son las barritas de los lados con las que podemos bajar el texto. En el Navigator
podemos ver que el JTextArea est dentro de un JScrollPane. Una vez que tengamos
todos los controles debemos ponerles los siguientes nombres (recuerda que puedes
utilizar F2 para que sea ms fcil cambiarles el nombre):

NETBEANS

PROGRAMACION VISUAL

15

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Recuerda que para que el JFrame se muestre debes poner la lnea setVisible(true);
dentro del constructor de la clase, despus de la llamada al mtodo initComponents().
Una vez que hayas creado la ventana recuerda agregar la lnea new MainFrame() dentro
del mtodo main() de la clase Main.
Paso 4:
Nuestro programa va a calcular el rea de un anillo, que se calcula mediante restando el
rea del circulo interno del rea del circulo externo. Para poder hacer esto nuestro
programa debe calcular el rea del crculo interno y del crculo externo utilizando el
radio. Como esa operacin es repetitiva vamos a ponerla en un mtodo por separado.
El mtodo va a llamarse calculateArea(), va a recibir el radio (tipo double) y debe
regresar un valor tipo double que representa el rea. En cdigo podramos verlo como el
siguiente mtodo:

Paso 5:
Ahora s, vamos a crear el mtodo actionPerformed() de btnCalculate. En el modo de
diseo haz click derecho sobre el botn y selecciona Events -> Action ->
actionPerformed. Dentro del cdigo debemos obtener los valores de los radios, podemos
utilizar el siguiente cdigo para lograrlo:

NETBEANS

PROGRAMACION VISUAL

16

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Paso 6:
Una vez que tengamos los datos debemos validar que el radio interior sea menor o igual
que el radio exterior. Esto podemos lograrlo mediante un if, y slo si son vlidos
debemos de calcular las reas y restarlas. El resultado final vamos a mostrarlo en el
JTextArea de la parte inferior. En cdigo podramos verlo como lo siguiente:

Prueba que todo funcione correctamente en tu aplicacin compilando el programa y


corrindolo. Hasta este momento debe poder calcular el rea de un anillo y mostrarla en
el JTextArea que pusimos para mostrar resultados, tambin debe poder validar errores.
Paso 7:
Aunque nuestro programa ya cumple con su objetivo muchas veces eso no es suficiente
para nuestros clientes que la mayora de las veces quieren algo un poco ms vistoso. En
este momento es en el que podemos utilizar Graphics para dar un valor agregado a
nuestros programas. Como vimos en el autoestudio podemos utilizar la clase Graphics
para pintar sobre un componente, por lo que no podemos pintar sobre un JFrame
(tcnicamente s se puede pero no se debe hacer por la implementacin de Java del
JFrame).
Este componente puede ser cualquier componente de Swing, aunque regularmente se
utiliza un JLabel o un JComponent por ser muy sencillos y ligeros. Por lo tanto para
poder pintar debemos crear un componente nuevo que se comporte como JComponent,
pero que se dibuje de manera diferente. Para poder hacer esto debemos hacer click
derecho sobre el paquete sesion7 y seleccionar New -> BeanForm.

NETBEANS

PROGRAMACION VISUAL

17

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Si no se encuentra BeanForm en el men debemos seleccionar New -> File/Folder y


dentro de ese men seleccionar BeanForm como se ve en la imagen:

Nuestro Bean va a llamarse RingBean y su superclase debe ser javax.swing.JComponent


como se ve en las siguientes fotografas:

NETBEANS

PROGRAMACION VISUAL

18

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Paso 8:
Al terminar aparecer un error de que no puede pintar la forma porque no es un
JavaBean. Esto es porque todava no hemos programado cmo debe de pintarse el
JComponent y NetBeans todava no lo puede dibujar. Haz click en source y vete al
cdigo. Pon el cursor en algn lugar en blanco fuera de un mtodo, pero dentro de la
clase y presionar Ctrl+Space para que aparezca el dilogo de autocompletar. Ah debes
escribir paintComponent y se seleccionar la entrada que se ve en la fotografa:

Es muy importante que sea paintComponent (sin la s) y que a la derecha diga override.
Una vez que lo hayas encontrado presiona enter y se construir automticamente el
mtodo paintComponent() que tiene un parmetro de tipo Graphics con el que podemos
dibujar sobre el componente. Presiona Alt+Shift+F para resolver las dependencias
(Graphics todava no estaba incluido en los imports) y dentro de ese mtodo pon el
siguiente cdigo:

La palabra clave this se refiere a este componente. Una vez que creamos la instancia y
lo ponemos en la ventana this.getWidth() debe devolvernos el ancho de ese
NETBEANS

PROGRAMACION VISUAL

19

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

componente dentro de la ventana. Obtenemos el ancho y el alto del componente para


garantizar que todava estamos dibujando dentro de l.
De acuerdo a tu autoestudio para qu crees que funciona el cdigo
anterior?
Compila tu programa para revisar que no haya ningn error y para garantizar que el
Bean ha sido construido. Ahora debemos agregar nuestro RingBean a la paleta de
NetBeans para poder ponerlo en la ventana que hicimos anteriormente. Podemos lograr
eso haciendo click derecho sobre el Bean en el explorador de proyectos, seleccionando
Tools -> Add to Palette.

En la pantalla que aparece seleccionamos la carpeta de Beans y regresamos a


MainFrame en modo de diseo. Podemos ver que en la paleta dentro de la seccin de
Beans ha aparecido nuestro Bean, as que ahora podemos agregarlo a la ventana.

Agrega el componente a la ventana. Si en el tiempo de diseo parece que tu Bean


todava no tiene forma no te preocupes, lo que pasa es que NetBeans no vuelve a leer
los Beans sino hasta volver a empezar. Esto es un error en el que estn trabajando los
programadores de NetBeans, pero no afecta tu proyecto. Despus de agregar el
RingBean cambile el nombre a ring de la misma manera que lo haras con otros
componentes. Compila y corre el programa y podrs ver una ventana similar a la
siguiente (dependiendo del lugar en que pusiste tu control):
NETBEANS

PROGRAMACION VISUAL

20

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Nuestro control ya est dibujando un rectngulo, pero ahora lo que queremos hacer es
que dibuje los anillos interior y exterior. Para poder hacer esto es necesario modificar
RingBean. Primero vamos a crear un par de variables que guarden los valores de los
radios, despus debemos crear un mtodo que reciba los radios que se deben dibujar y
despus manden dibujar utilizando estos datos. Copia el siguiente cdigo dentro de
RingBean:

En este cdigo vamos a ver varias cosas interesantes. Primero que nada fjate que las
variables tienen el modificador private para que otros objetos no puedan acceder a sus
variables ms ntimas. Esto es por algo llamado encapsulacin que vamos a ver mucho
ms a profundiad al tocar el tema de programacin orientada a objetos. Adems es
importante notar que las variables son de tipo int, porque Graphics no puede manejar
los tipos de dato double. En el mtodo setRadius() podemos ver que utilizamos la
palabra clave this para referirnos a la variable del objeto, a diferencia de la variable
pasada como parmetro, esto tambin es un comportamiento que analizaremos ms
detalladamente al ver programacin orientada a objetos. En pocas palabras:
this.innerRadius == innerRadius de la clase
innerRadius == innerRadius el parmetro
Por ltimo podemos ver el mtodo repaint() que le dice al componente que ha sucedido
algo que amerita que vuelva a pintarse. Este mtodo se encarga de revisar qu fue lo
que sucedi y llamar los mtodos adecuados para volver a dibujar el componente.
Una vez que hemos echo esto debemos modificar el mtodo paintComponent() para
que utilice estos valores y dibuje dos crculos en lugar del rectngulo que dibuja
actualmente. Podemos lograr esto mediante el siguiente cdigo:
NETBEANS

PROGRAMACION VISUAL

21

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Este mtodo puede parecer un poco complicado. Podemos ver que primero calculamos
el centro del componente (dividiendo el ancho entre dos y el largo entre dos). Una vez
que hemos echo eso vamos a poner el punto inicial en el centro menos el radio (con
esto estamos garantizando que el centro del crculo est a la mitad de la ventana
porque el crculo mide dos veces el radio) y por ltimo estoy poniendo el ancho y alto
como el doble del radio. Podemos verlo grficamente:

Por ltimo slo debemos mandar llamar el mtodo setRadius() dentro del
actionPerformed del botn btnCalculate. Podemos hacerlo de la siguiente manera:

Adems de los mtodos drawX (como drawRect(), drawOval()), la clase Graphics


tambin tiene mtodos fillX (como fillRect() y fillOval()). Estos mtodos dibujan una
figura que est rellena de color.
Para poder cambiar el color del pincel que utilizamos para pintar sobre el bean puedes
utilizar el mtodo setColor() de la clase Graphics (es decir, lo utilizas
g.setColor(Color.GREEN), revisa el men de autocompletar de NetBeans para saber
algunos otros colores que puedes utilizar).

NETBEANS

PROGRAMACION VISUAL

22

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

NETBEANS

PROGRAMACION VISUAL

23

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 2. Manejo de Grficos, utilizando


Beans
Instrucciones
Paso 1:
Descarga el esqueleto manejo de grficos que vamos a utilizar en esta sesin y abre el
proyecto en NetBeans. Ahora compila y corre la aplicacin. Aparecer una pantalla gris
con tres divisiones (que tienen controles aunque no estn pintados). Al terminar la
aplicacin tendremos una interfaz grfica similar a la siguiente:

En esta aplicacin vamos a utilizar Graphics y lo que hemos aprendido de ciclos para
crear estas tres figuras. Primero empecemos con el tablero de ajedrez. Como podemos
ver el tablero de ajedrez es una figura muy sencilla compuesta de 64 cuadros ordenados
en una cuadrcula de 8 x 8.
Vamos a analizar un poco ms a fondo cmo vamos a hacer esto:

NETBEANS

PROGRAMACION VISUAL

24

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Nuestro tablero est formado por cuadros de 25 pixeles cada uno. Eso significa que la
esquina superior izquierda (el origen) de el quinto cuadro de la primera fila sera (4 x
25, 0) es decir (100, 0), el sexto cuadro estara en (5 x 25, 0) o (125, 0). Aqui podemos
ver un patrn que es muy improtante porque es la base con la que vamos a crear
nuestro ciclo. Veamos qu sucede para el quinto cuadro de la sexta fila (4 x 25, 5 x 25)
o (100, 125). Como podemos ver todas las posiciones estn en base a ((columna - 1) x
25, (fila - 1) x 25). Para evitar estar restando a las columnas y las filas podemos utilizar
un ndice que empiece de cero en lugar de uno.
Lo siguiente que debemos determinar es cules son los lmites de nuestro ciclo.
Podramos hacer un ciclo que cuente hasta el 64 y que utilice una divisin y su mdulo
para obtener el nmero de fila y columna respectivamente. Podemos verlo con el
siguiente cdigo:

NETBEANS

PROGRAMACION VISUAL

25

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

NOTA: Es muy importante que no olvides agregar el incremento hasta el final


(square++). En caso de que lo hagas, tu programa se va a congelar y va a comenzar a
utilizar muchsimos recursos para pintar. Peor an, podra ser que NetBeans intentara
dibujar el componente y se quedara atorado por siempre en el ciclo, por lo que tendras
que cerrar la aplicacin y perderas tu trabajo.
En caso de que corras un programa que tenga un ciclo sin fin puedes utilizar la ventana
de runtime como se ve en la imagen (la ventana runtime est junto a la ventana de
Projects y en caso de que no se vea puedes utilizar Window -> Runtime o Ctrl+5 para
que aparezca):

Fjate en el if. Lo que estamos haciendo es ver qu color haba en la celda anterior y
pintar la nueva celda con un color diferente. Esto nos sirve para hacer los cuadros
blancos y negros alternados. Ahora compila y corre el programa y vers la siguiente
imagen

Esto sucede porque los cuadros no siempre deben cambiar de color (como lo estamos
haciendo en nuestro programa) sino que al cambiar de fila utilizan el mismo color que
antes (si el ltimo de la fila anterior era negro el primero de la fila actual tambin es
negro). Podemos revisar con un if si estamos cambiando de fila (cuando col es igual a
cero, significa que estamos en una fila nueva). El if puede ser como el siguiente:

NETBEANS

PROGRAMACION VISUAL

26

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Vuelve a probar tu programa y ahora deber dibujar el tablero de manera correcta (en
realidad casi correcta, el tablero tiene un cuadrado negro en la esquina inferior derecha
y debera ser blanco, puedes cambiar el color con el que empezamos a pintar para
corregir esto). Como puedes ver, puedes utilizar el mdulo y la divisin como
operaciones complementarias al utilizar ciclos, aunque este enfoque no es muy utilizado.
Ms adelante veremos una manera un poco ms sencilla de lograr esto mismo. Una vez
que hayas probado tu programa contina con el ejercicio del gusano

Aqui hay varias cosas importantes que tomar en cuenta. Primero que nada, las partes
del cuerpo van a estar alternando su posicin vertical entre 0 y 5. Puedes observar que
todas las partes del cuerpo nones van a estar arriba, mientras que las pares van a estar
abajo, podemos utilizar un if que revise si la parte del cuerpo es non o par y la ponga en
la posicin en y que le corresponde. Tambin podemos ver que la cabeza es diferente
de las dems partes del cuerpo, por lo que debemos pintarla por separado y fuera de un
ciclo. Por ltimo debemos definir cmo va a ser el ciclo que utilicemos para pintar todas
las partes del cuerpo.
La primera parte despus de la cabeza (primera parte del cuerpo) va a estar en la
posicin 1 x 10, la segunda parte va a estar en la posicin 2 x 10, la tercera parte va a
estar en la posicin 3 x 10. Ah est el patrn que necesitamos para empezar a pintar.
NETBEANS

PROGRAMACION VISUAL

27

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Tomando esto en cuenta podemos utilizar un ciclo que empiece desde 1 (fjate que la
primera parte tiene un 1, a diferencia del problema anterior porque aqu la cabeza es
diferente).
Tomando en cuenta estas consideraciones podemos programar el siguiente cdigo:

NOTA: Recuerda que es muy importante aumentar el acumulador con la lnea pieces++.
Fjate en cmo vamos a dibujar 40 piezas empezando el contador (pieces) en 1 y
repitiendo el ciclo mientras que pieces sea menor o igual a cuarenta. Tambin fjate que
utilizamos una variable y que representa la posicin en y en que vamos a dibujar y el if
se va a encargar de cambiarla de 0 a 5 y viceversa segn sea necesario.
Compila y corre tu cdigo asegurndote de que se dibuje el gusano correctamente. Por
ltimo vamos a dibujar el camin.

En teora es muy similar al gusano, slo que ahora en lugar de tener un nmero fijo de
piezas del cuerpo tenemos un nmero variable que se encuentra guardado en la
variable boxes. Otro detalle importante es que las cajas van separadas unas de otras,
por lo que tendremos que poner un poco de separacin.
NETBEANS

PROGRAMACION VISUAL

28

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Como podemos ver el mtodo es practicamente igual que el anterior, pero cambiamos
un poco la manera de dibujar los controles. Compila tu aplicacin y correla para probar
que funcione adecuadamente. Cambia el nmero de cajas que tiene el camin utilizando
la caja de texto (introduce el nmero y presiona enter).
Comprime tu carpeta de trabajo y mndala por correo.

NETBEANS

PROGRAMACION VISUAL

29

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 3. Creacin de Lneas y Figuras. Utilizando


JPanel.
Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras graficoslineas.

Agrega un paquete llamado pgraficolineas.

NETBEANS

PROGRAMACION VISUAL

30

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado Fgraficolineas.

Adicionar un JPanelForm con el nombre PGraficoLineas.

NETBEANS

PROGRAMACION VISUAL

31

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo de PGraficoLineas y adicionamos el cdigo del paint en donde
realizamos el pintado de nuestras figuras

public void getLineas (int cantidad){


lineas=cantidad;
repaint();
}
@Override
public void paint(Graphics g) {
super.paint(g); //To change body of generated methods, choose Tools | Templates.
// Dibuja n lineas con origen 5,5 a 350,5
for (int i=1;i<=lineas;i++){
g.setColor( Color.RED );
g.drawLine( 5, 5*i, 100, 5*i );
}
// Dibuja un cuadrado relleno de color azul y de contorno rojo
g.setColor( Color.RED );
g.drawRect( 150, 40, 90, 55 );
g.setColor( Color.BLUE );
g.fillRect( 150, 40, 90, 55 );
NETBEANS

PROGRAMACION VISUAL

32

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

// Dibuja un cuadrado redondenado de color Verde y de contorno cyan


g.setColor( Color.CYAN );
g.fillRoundRect( 290, 40, 90, 55, 20, 20 );
g.setColor( Color.GREEN );
g.drawRoundRect( 290, 40, 90, 55, 20, 20 );
// Dibuja un cuadrado en 3D de color amarrillo y de contorno rosa
g.setColor( Color.YELLOW );
g.fill3DRect( 150, 100, 90, 55, false );
g.setColor( Color.PINK );
g.draw3DRect( 150, 100, 90, 55, true );
// Dibuja un ovalo de color magenta y de contorno cyan
g.setColor( Color.MAGENTA );
g.drawOval( 290, 100, 90, 55 );
g.fillOval( 290, 100, 90, 55 );
}

Paso 3:
Seleccionamos el Frame Fgraficolineas y arrastramos el panel que acabamos de crear,
hacia el frame, quedando de la siguiente forma:

NETBEANS

PROGRAMACION VISUAL

33

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Ajustamos el panel al tamao en donde nos muestren las figuras.


Paso 4:
Ejecutamos el programa y nos dara lo siguiente:

NETBEANS

PROGRAMACION VISUAL

34

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 4. Creacin de Arcos. Utilizando JPanel.


Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras graficosarco.

Agrega un paquete llamado pgrafiarco.

NETBEANS

PROGRAMACION VISUAL

35

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado FGraficoArcos.

Adicionar un JPanelForm con el nombre PGraficoArcos.

NETBEANS

PROGRAMACION VISUAL

36

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo de PGraficoLineas y adicionamos el cdigo del paint en donde
realizamos el pintado de nuestras figuras

// dibujar rectngulos y arcos


public void paint( Graphics g )
{
super.paint( g ); // llamar al mtodo paint de la superclase
// empezar en 0 y extenderse hasta 360 grados
g.setColor( Color.YELLOW );
g.drawRect( 15, 35, 80, 80 );
g.setColor( Color.RED );
g.drawArc( 15, 35, 80, 80, 0, 360 );
// empezar en 0 y extenderse hasta 110 grados
g.setColor( Color.YELLOW );
g.drawRect( 100, 35, 80, 80 );
g.setColor( Color.RED );
g.drawArc( 100, 35, 80, 80, 0, 110 );
// empezar en 0 y extenderse hasta -270 grados
g.setColor( Color.YELLOW );
g.drawRect( 185, 35, 80, 80 );
g.setColor( Color.RED );
g.drawArc( 185, 35, 80, 80, 0, -270 );

NETBEANS

PROGRAMACION VISUAL

37

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

// empezar en 0 y extenderse hasta 360 grados


g.fillArc( 15, 120, 80, 40, 0, 360 );
// empezar en 0 y extenderse hasta -90 grados
g.fillArc( 100, 120, 80, 40, 270, -90 );
// empezar en 0 y extenderse hasta -270 grados
g.fillArc( 185, 120, 80, 40, 0, -270 );
} // fin del mtodo paint

Paso 3:
Compilamos el programa, sleccionamos el Frame y arrastramos el panel que acabamos
de crear, hacia el frame, quedando de la siguiente forma:

NETBEANS

PROGRAMACION VISUAL

38

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Ajustamos el panel al tamao en donde nos muestren las figuras.


Paso 4:
Ejecutamos el programa y nos dara lo siguiente:

Realizamos cambios en los colores de los arcos.

NETBEANS

PROGRAMACION VISUAL

39

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 5. Dibujo de polgonos. Utilizando JPanel.


Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras graficospoligono.

Agrega un paquete llamado pgraficopoligono.

NETBEANS

PROGRAMACION VISUAL

40

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado FGraficoPoligonos.

Adicionar un JPanelForm con el nombre PGraficoPoligono.

NETBEANS

PROGRAMACION VISUAL

41

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo de PGraficoPoligono y adicionamos el cdigo del paint en donde
realizamos el pintado de nuestras figuras

// dibujar polgonos y polilneas


public void paint( Graphics g )
{
super.paint( g ); // llamar al mtodo paint de la superclase
int valoresX[] = { 20, 40, 50, 30, 20, 15 };
int valoresY[] = { 50, 50, 60, 80, 80, 60 };
Polygon poligono1 = new Polygon( valoresX, valoresY, 6 );
g.drawPolygon( poligono1 );
int valoresX2[] = { 70, 90, 100, 80, 70, 65, 60 };
int valoresY2[] = { 100, 100, 110, 110, 130, 110, 90 };
g.drawPolyline( valoresX2, valoresY2, 7 );
int valoresX3[] = { 120, 140, 150, 190 };
int valoresY3[] = { 40, 70, 80, 60 };
g.fillPolygon( valoresX3, valoresY3, 4);
NETBEANS

PROGRAMACION VISUAL

42

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Polygon poligono2 = new Polygon();


poligono2.addPoint( 165, 135 );
poligono2.addPoint( 175, 150 );
poligono2.addPoint( 270, 200 );
poligono2.addPoint( 200, 220 );
poligono2.addPoint( 130, 180 );
g.fillPolygon( poligono2 );
} // fin del mtodo paint

Paso 3:
Compilamos el programa, seleccionamos el Frame y arrastramos el panel que acabamos
de crear, hacia el frame, quedando de la siguiente forma:

Ajustamos el panel al tamao en donde nos muestren las figuras.


NETBEANS

PROGRAMACION VISUAL

43

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Paso 4:
Ejecutamos el programa y nos dara lo siguiente:

Realizamos cambios en los colores de los poligonos.

NETBEANS

PROGRAMACION VISUAL

44

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 6. Dibujo de figuras de Java2D. Utilizando


JPanel.
Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras graficosfiguras2D.

Agrega un paquete llamado pgraficosfiguras2D.

NETBEANS

PROGRAMACION VISUAL

45

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado Fpgraficosfiguras2D.

Adicionar un JPanelForm con el nombre Pgraficosfiguras2D.

NETBEANS

PROGRAMACION VISUAL

46

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo del panel y adicionamos el cdigo del paint en donde realizamos el
pintado de nuestras figuras
// dibujar figuras con la API Java2D
public void paint( Graphics g )
{
super.paint( g ); // llamar al mtodo paint de la superclase
Graphics2D g2d = ( Graphics2D ) g; // convertir g a Graphics2D
// dibujar elipse 2D rellena con un gradiente azul-amarillo
g2d.setPaint( new GradientPaint( 5, 30, Color.BLUE, 35, 100, Color.YELLOW, true ) );
g2d.fill( new Ellipse2D.Double( 5, 30, 65, 100 ) );
// dibujar rectngulo 2D en rojo
g2d.setPaint( Color.RED );
g2d.setStroke( new BasicStroke( 10.0f ) );
g2d.draw( new Rectangle2D.Double( 80, 30, 65, 100 ) );
// dibujar rectngulo 2D redondeado con fondo tamponado
BufferedImage buffImage = new BufferedImage( 10, 10,BufferedImage.TYPE_INT_RGB );
Graphics2D gg = buffImage.createGraphics();
gg.setColor( Color.YELLOW ); // dibujar en amarillo
gg.fillRect( 0, 0, 10, 10 ); // dibujar un rectngulo relleno
gg.setColor( Color.BLACK ); // dibujar en negro
gg.drawRect( 1, 1, 6, 6 ); // dibujar un rectngulo
gg.setColor( Color.BLUE ); // dibujar en azul
gg.fillRect( 1, 1, 3, 3 ); // dibujar un rectngulo relleno
gg.setColor( Color.RED ); // dibujar en rojo

NETBEANS

PROGRAMACION VISUAL

47

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO
gg.fillRect( 4, 4, 3, 3 ); // dibujar un rectngulo relleno
// pintar buffImage en el objeto JFrame
g2d.setPaint( new TexturePaint( buffImage, new Rectangle( 10, 10 ) ) );
g2d.fill( new RoundRectangle2D.Double( 155, 30, 75, 100, 50, 50 ) );
// dibujar arco 2D en forma de pastel, en color blanco
g2d.setPaint( Color.WHITE );
g2d.setStroke( new BasicStroke( 6.0f ) );
g2d.draw( new Arc2D.Double( 240, 30, 75, 100, 0, 270, Arc2D.PIE ) );
// dibujar lneas 2D en verde y amarillo
g2d.setPaint( Color.GREEN );
g2d.draw( new Line2D.Double( 395, 30, 320, 150 ) );
float guiones[] = { 10 };
g2d.setPaint( Color.YELLOW );
g2d.setStroke( new BasicStroke( 4, BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND, 10, guiones, 0 ) );
g2d.draw( new Line2D.Double( 320, 30, 395, 150 ) );
} // fin del mtodo paint

Los errores que aparecen son por la falta de importar las librerias, por lo cual damos clic
sobre los bombillos rojos e importamos las librerias.
Paso 3:
Compilamos el programa, seleccionamos el Frame y arrastramos el panel que acabamos
de crear, hacia el frame, quedando de la siguiente forma:

NETBEANS

PROGRAMACION VISUAL

48

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Ajustamos el panel al tamao en donde nos muestren las figuras.


Paso 4:
Ejecutamos el programa y nos dara lo siguiente:

NETBEANS

PROGRAMACION VISUAL

49

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 7. Dibujo de figuras dibujar con rutas


generales. Utilizando JPanel.
Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras graficosfiguras.

Agrega un paquete llamado pgraficosfiguras.

NETBEANS

PROGRAMACION VISUAL

50

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado Fpgraficosfiguras.

Adicionar un JPanelForm con el nombre Pgraficosfiguras.

NETBEANS

PROGRAMACION VISUAL

51

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo del panel y adicionamos el cdigo del paint en donde realizamos el
pintado de nuestras figuras
// dibujar rutas generales
public void paint( Graphics g )
{
super.paint( g ); // llamar al mtodo paint de la superclase
int puntosX[] = { 55, 67, 109, 73, 83, 55, 27, 37, 1, 43 };
int puntosY[] = { 0, 36, 36, 54, 96, 72, 96, 54, 36, 36 };
Graphics2D g2d = ( Graphics2D ) g;
GeneralPath estrella = new GeneralPath(); // crear objeto GeneralPath
// establecer la coordenada inicial de la ruta general
estrella.moveTo( puntosX[ 0 ], puntosY[ 0 ] );
// crear la estrella--esto no la dibuja
for ( int cuenta = 1; cuenta < puntosX.length; cuenta++ )
estrella.lineTo( puntosX[ cuenta ], puntosY[ cuenta ] );
estrella.closePath(); // cerrar la figura
g2d.translate( 200, 200 ); // trasladar el origen a (200, 200)
// girar alrededor del origen y dibujar estrellas en colores aleatorios
for ( int cuenta = 1; cuenta <= 20; cuenta++ ) {
g2d.rotate( Math.PI / 10.0 ); // girar el sistema de coordenadas
// establecer color de dibujo al azar
g2d.setColor( new Color( ( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ),( int ) ( Math.random() * 256 ) ) );

NETBEANS

PROGRAMACION VISUAL

52

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO
g2d.fill( estrella ); // dibujar estrella rellena
}
} // fin del mtodo paint

Los errores que aparecen son por la falta de importar las librerias, por lo cual damos clic
sobre los bombillos rojos e importamos las librerias.
Paso 3:
Compilamos el programa, seleccionamos el Frame y arrastramos el panel que acabamos
de crear, hacia el frame, quedando de la siguiente forma:

Ajustamos el panel al tamao en donde nos muestren las figuras.


NETBEANS

PROGRAMACION VISUAL

53

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Paso 4:
Ejecutamos el programa y nos dara lo siguiente:

NETBEANS

PROGRAMACION VISUAL

54

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

PRACTICA 8. Movimientos de figuras. Utilizando


JPanel.
Instrucciones
Paso 1:
Corre NetBeans y crea un nuevo proyecto al que llamaras moverfiguras.

Agrega un paquete llamado pmoverfiguras.

NETBEANS

PROGRAMACION VISUAL

55

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Agrega un JFrame llamado Fpmoverfiguras.

Adicionar un JPanelForm con el nombre PMoverfiguras.

NETBEANS

PROGRAMACION VISUAL

56

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Debers tener una estructura de proyecto similar a la que se ve en la siguiente


fotografa:

Paso 2:
Vamos al cdigo del panel y adicionamos el cdigo del paint en donde realizamos el
pintado de nuestras figuras
//Definimos variables globales para la ubicacin del baln
int Posx=0, Posy=0;
// dibujar fondo y balon
public void paint( Graphics g )
{
super.paint( g ); // llamar al mtodo paint de la superclase
// Crear un fondo amarrillo
g.setColor( Color.YELLOW );
g.fillRect( 0,0,getWidth(),getHeight());
if (Posx<0){
Posx=0;
}
if (Posy<0){
Posy=0;
}
if (Posx>getWidth()-10){
Posx=getWidth()-10;
}
if (Posy>getHeight()-10){
Posy=getHeight()-10;
}
// Crear un circulo de color rojo
g.setColor( Color.RED );
g.fillArc(Posx, Posy, 10, 10, 0, 360 );

NETBEANS

PROGRAMACION VISUAL

57

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO
} // fin del mtodo paint

Paso 3:
Compilamos el programa, sleccionamos el Frame y arrastramos el panel que acabamos
de crear, hacia el frame, quedando de la siguiente forma:

NETBEANS

PROGRAMACION VISUAL

58

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Ajustamos el panel al tamao en donde nos muestren las figuras. Debemos adicionar
cinco (5) botones, cuatro(4) para el movimiento y uno(1) para salir.

Paso 4:
Realizamos la programacin en cada botn de movimiento:
private void BArribaActionPerformed(java.awt.event.ActionEvent evt) {
pMoverfiguras1.Posy-=10;
pMoverfiguras1.repaint();
// TODO add your handling code here:
}
private void BDerechaActionPerformed(java.awt.event.ActionEvent evt) {
pMoverfiguras1.Posx+=10;
pMoverfiguras1.repaint();// TODO add your handling code here:
}
private void BIzquierdaActionPerformed(java.awt.event.ActionEvent evt) {
pMoverfiguras1.Posx-=10;
pMoverfiguras1.repaint();// TODO add your handling code here:
}
private void BAbajoActionPerformed(java.awt.event.ActionEvent evt) {
pMoverfiguras1.Posy+=10;
pMoverfiguras1.repaint();// TODO add your handling code here:
}
private void BSalirActionPerformed(java.awt.event.ActionEvent evt) {
dispose();
// TODO add your handling code here:
}

NETBEANS

PROGRAMACION VISUAL

59

TECNOLOGA EN SISTEMAS DE TELECOMUNICACIONES


UNIDADES TECNOLOGICAS DE SANTANDER
DOCENTE: ROGERIO ORLANDO BELTRAN CASTRO

Paso 5:
Ejecutamos el programa y nos dara lo siguiente:

Al dar clic en los botones (Arriba, Izquierda, Abajo y Derecha) el baln rojo se mueve.

NETBEANS

PROGRAMACION VISUAL

60

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