Sie sind auf Seite 1von 16

Generated by Foxit PDF Creator © Foxit Software

http://www.foxitsoftware.com For evaluation only.

TRABAJO DE HIPERMEDIALES
OBJETIVOS.

• Análisis de un programa básico de JAVA.


MARCO TEÓRICO.

En este apartado analizaremos los contenidos básicos que debe llegar a tener
nuestro programa, como son:

1. ACCESO A UN MÉTODO.

2. PASO DE ARGUMENTOS A UN MÉTODO.

3. SENTENCIA RETURN.

Estos son los principales aspectos que deberá tener nuestro programa, a
continuación pasaremos a verlos cada uno de ellos.

Los métodos son funciones que pueden ser llamadas dentro de la clase o por
otras clases. La implementación de un método consta de dos partes, una
declaración y un cuerpo. La declaración en Java de un método se puede
expresar esquemáticamente como:

tipoRetorno nombreMetodo( [lista_de_argumentos] ) {


cuerpoMetodo
}

como por ejemplo:

String setCadena(String mensaje){


cadena=mensaje;
}
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

En C++, el método puede declararse dentro de la definición de la clase,


aunque también puede colocarse la definición completa del método fuera de
la clase, convirtiéndose en una función inline. En Java, la definición completa
del método debe estar dentro de la definición de la clase y no se permite la
posibilidad de métodos inline, por lo tanto, Java no proporciona al
programador distinciones entre métodos normales y métodos inline.

Los métodos pueden tener numerosos atributos a la hora de declararlos,


incluyendo el control de acceso, si es estático o no estático, etc. La sintaxis
utilizada para hacer que un método sea estático y su interpretación, es
semejante en Java y en C++. Sin embargo, la sintaxis utilizada para establecer
el control de acceso y su interpretación, es muy diferente en Java y en C++.

Control de Acceso

Se puede decir que el control de acceso que se indique determina la forma


en que otros objetos van a pode instanciar objetos de la clase. En la siguiente
descripción, se indica cómo se trata el control de acceso cuando se tienen
entre manos a los constructores:

private

Ninguna otra clase puede instanciar objetos de la clase. La clase puede


contener métodos públicos, y estos métodos pueden construir un objeto y
devolverlo, pero nadie más puede hacerlo.

protected

Solamente las subclases de la clase pueden crear instancias de ella.

public

Cualquier otra clase puede crear instancias de la clase.


Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

package

Nadie desde fuera del paquete puede construir una instancia de la clase. Esto
es útil si se quiere tener acceso a las clases del paquete para crear instancias
de la clase, pero que nadie más pueda hacerlo, con lo cual se restringe quien
puede crear instancias de la clase.

En Java y en C++, una instancia de una clase, un objeto, contiene todas las
variables y métodos de instancia de la clase y de todas sus superclases. Sin
embargo, los dos lenguajes soportan la posibilidad de sobreescribir un
método declarado en una superclase, indicando el mismo nombre y misma
lista de argumentos; aunque los procedimientos para llevar a cabo esto son
totalmente diferentes en Java y en C++.

Como aclaración a terminología que se empleo, quiero indicar que cuando se


dice sobrecargar métodos, quiere decir que Java requiere que los dos
métodos tengan el mismo nombre, devuelvan el mismo tipo, pero tienen una
diferente lista de argumentos.

Paso de argumentos

• El paso de tipos simples a los métodos es siempre por valor.

• Los objetos se pasan siempre por referencia.

class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

System.out.println("a y b antes de la llamada:"+a+" "+b);


ob.meth(a, b);
System.out.println("a y b despues de la llamada:"+a+" "+b);
}
}

Con este pequeño ejemplo quiero demostrar a lo que se refiere con "Paso de
argumentos", en donde nos explican que este paso
puede ser de tipo simple, y que siempre será por valor, en el ejemplo hemos
creado un método "meth" que recibe dos valores de tipo
entero (int) y son "i" y "j", y a los cuales se les multiplica y divide por 2
respectivamente.

Para poder llamar al método solo debemos crear un objeto tipo "Test" dado
que a esta clase pertenece el método "meth", y como
podemos apreciar se le llama haciendo la siguiente sentencia:

ob.meth(a,b);

donde a y b son dos objetos tipo entero (int) y que concuerdan con los
argumentos que requiere el método para trabajar, si mandamos un
tipo diferente de objetos el método nos dará un mensaje de error.

Sentencia return

La sentencia de salto es la sentencia return, que puede usar para salir del
método en curso y retornar a la sentencia dentro de la cual se realizó la
llamada.

Para devolver un valor, simplemente se debe poner el valor (o una expresión


que calcule el valor) a continuación de la palabra return. El valor devuelto por
return debe coincidir con el tipo declarado como valor de retorno del
método.
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

Cuando un método se declara como void no es necesario usar la forma de


return . Esto se hace para no ejecutar todo el código del programa:

Ejemplo:

int contador;

boolean condicion;

int devuelveContadorIncrementado(){

return ++contador;

En el ejemplo se crea un método "devuelveContadorIncrementado" de tipo


entero "int" en donde se incrementa
en uno el valor de la variable contador que también es tipo entero, y con la
sentencia "return" devuelve dicho
valor.

En los métodos tipo void no se debe insertar la sentencia return.

PROGRAMA
El programa que desarrollamos esta realizado en la herramientas NETBEANS
6.5.1 la cual utiliza como lenguaje base JAVA, esta nos da también una mejor
interface para el usuario, a continuación dejamos el código fuente de nuestro
programa, el programa tiene como fuente el JFrame.
* Rectangulo.java

package rectangulo;

import java.awt.Color;

import java.awt.Graphics;

public class Rectangulo extends javax.swing.JFrame {


Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

public double base;

public double altura;

public double area;

public double perimetro;

/** Creates new form Rectangulo */

public Rectangulo() {

initComponents();

base=0;

altura=0;

area=0;

perimetro=0;

/** This method is called from within the constructor to

* initialize the form.

* WARNING: Do NOT modify this code. The content of this method is

* always regenerated by the Form Editor.

*/

@SuppressWarnings("unchecked")

// <editor-fold defaultstate="collapsed" desc="Generated Code">

private void initComponents() {

jLabel1 = new javax.swing.JLabel();

calcularbt = new javax.swing.JButton();

basetxt = new javax.swing.JTextField();

alturatxt = new javax.swing.JTextField();

jLabel2 = new javax.swing.JLabel();


Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

jLabel3 = new javax.swing.JLabel();

areatxt = new javax.swing.JTextField();

jLabel4 = new javax.swing.JLabel();

pertxt = new javax.swing.JTextField();

jLabel5 = new javax.swing.JLabel();

setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

jLabel1.setFont(new java.awt.Font("Angsana New", 2, 24)); // NOI18N

jLabel1.setText("RECTÁNGULO");

calcularbt.setText("Calcular Área y Perímetro");

calcularbt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

calcularbtActionPerformed(evt);

});

basetxt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

basetxtActionPerformed(evt);

});

basetxt.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent evt) {

basetxtKeyReleased(evt);

});

alturatxt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {


Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

alturatxtActionPerformed(evt);

});

alturatxt.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent evt) {

alturatxtKeyReleased(evt);

});

jLabel2.setFont(new java.awt.Font("Angsana New", 2, 24)); // NOI18N

jLabel2.setText("BASE");

jLabel3.setFont(new java.awt.Font("Angsana New", 2, 24)); // NOI18N

jLabel3.setText("ALTURA");

areatxt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

areatxtActionPerformed(evt);

});

areatxt.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent evt) {

areatxtKeyReleased(evt);

});

jLabel4.setFont(new java.awt.Font("Angsana New", 2, 24)); // NOI18N

jLabel4.setText("ÁREA");

pertxt.addActionListener(new java.awt.event.ActionListener() {

public void actionPerformed(java.awt.event.ActionEvent evt) {

pertxtActionPerformed(evt);
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

});

pertxt.addKeyListener(new java.awt.event.KeyAdapter() {

public void keyReleased(java.awt.event.KeyEvent evt) {

pertxtKeyReleased(evt);

});

jLabel5.setFont(new java.awt.Font("Angsana New", 2, 24)); // NOI18N

jLabel5.setText("PERÍMETRO");

javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());

getContentPane().setLayout(layout);

layout.setHorizontalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(236, 236, 236)

.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 114,


javax.swing.GroupLayout.PREFERRED_SIZE))

.addGroup(layout.createSequentialGroup()

.addGap(217, 217, 217)

.addComponent(calcularbt))

.addGroup(layout.createSequentialGroup()

.addGap(115, 115, 115)

.addComponent(basetxt, javax.swing.GroupLayout.PREFERRED_SIZE, 72,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jLabel2)
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

.addGap(88, 88, 88)

.addComponent(alturatxt, javax.swing.GroupLayout.PREFERRED_SIZE, 87,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jLabel3))

.addGroup(layout.createSequentialGroup()

.addGap(106, 106, 106)

.addComponent(areatxt, javax.swing.GroupLayout.PREFERRED_SIZE, 72,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)

.addComponent(jLabel4)

.addGap(88, 88, 88)

.addComponent(pertxt, javax.swing.GroupLayout.PREFERRED_SIZE, 87,


javax.swing.GroupLayout.PREFERRED_SIZE)

.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)

.addComponent(jLabel5)))

.addContainerGap(156, Short.MAX_VALUE))

);

layout.setVerticalGroup(

layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)

.addGroup(layout.createSequentialGroup()

.addGap(29, 29, 29)

.addComponent(jLabel1)

.addGap(22, 22, 22)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(basetxt, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel2)
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

.addComponent(alturatxt, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel3))

.addGap(35, 35, 35)

.addComponent(calcularbt)

.addGap(411, 411, 411)

.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)

.addComponent(areatxt, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel4)

.addComponent(pertxt, javax.swing.GroupLayout.PREFERRED_SIZE,
javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)

.addComponent(jLabel5))

.addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))

);

pack();

}// </editor-fold>

private void basetxtKeyReleased(java.awt.event.KeyEvent evt) {

// TODO add your handling code here:

String aux=basetxt.getText().trim();

if(aux.length()>0){

for(int i=0;i<aux.length();i++){

char let=aux.charAt(i);

if(Character.isLetter(let)){

jLabel2.setText("error");

calcularbt.setEnabled(false);
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

else{

jLabel2.setText("BASE");

calcularbt.setEnabled(true);

private void basetxtActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void alturatxtActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void alturatxtKeyReleased(java.awt.event.KeyEvent evt) {

// TODO add your handling code here:

String aux=alturatxt.getText().trim();

if(aux.length()>0){

for(int i=0;i<aux.length();i++){

char let=aux.charAt(i);

if(Character.isLetter(let)){

jLabel3.setText("error");
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

calcularbt.setEnabled(false);

else{

jLabel3.setText("ALTURA");

calcularbt.setEnabled(true);

private void calcularbtActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

String aux=basetxt.getText().trim();

base=Double.parseDouble(aux);

aux=alturatxt.getText().trim();

altura=Double.parseDouble(aux);

area=base*altura;

perimetro=(base*2)+(altura*2);

areatxt.setText(area+"");

pertxt.setText(perimetro+"");

Graphics g = getGraphics();

//g.fillRect(10, 10, (int)base, (int)altura);

paint(g);
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

public void paint(Graphics g){

super.paint(g);

g.setColor(Color.BLUE);

g.fillRect(150, 250, (int)base, (int)altura);

private void areatxtActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void areatxtKeyReleased(java.awt.event.KeyEvent evt) {

// TODO add your handling code here:

private void pertxtActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:

private void pertxtKeyReleased(java.awt.event.KeyEvent evt) {

// TODO add your handling code here:

/**

* @param args the command line arguments


Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

*/

public static void main(String args[]) {

java.awt.EventQueue.invokeLater(new Runnable() {

public void run() {

new Rectangulo().setVisible(true);

});

// Variables declaration - do not modify

private javax.swing.JTextField alturatxt;

private javax.swing.JTextField areatxt;

private javax.swing.JTextField basetxt;

private javax.swing.JButton calcularbt;

private javax.swing.JLabel jLabel1;

private javax.swing.JLabel jLabel2;

private javax.swing.JLabel jLabel3;

private javax.swing.JLabel jLabel4;

private javax.swing.JLabel jLabel5;

private javax.swing.JTextField pertxt;

// End of variables declaration

Imágenes.
Imagen del programa ya ejecutado.
Generated by Foxit PDF Creator © Foxit Software
http://www.foxitsoftware.com For evaluation only.

Das könnte Ihnen auch gefallen