Powered By Blogger
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas
Mostrando entradas con la etiqueta Java. Mostrar todas las entradas

martes, 18 de mayo de 2010

Otro Ejemplo de Eventos en Java

Este ejemplo es un applet que permite realizar operaciones básica arisméticas una vez introducido números en cuadros de texto, tambien posee un conjunto de validaciones sobre éstas operaciones.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import java.applet.Applet;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

/**
*
* @author renan
*/
public class BotonesApplet extends Applet implements ActionListener{
JLabel etiqueta1,etiqueta2,etiqueta3;
JTextField campo1,campo2,campo3;
JButton suma_bot, resta_bot, multi_bot, divi_bot, mayor_bot, limp_bot, raiz1_bot, raiz2_bot;
float var,var2,var3;
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public void init() {

etiqueta1 = new JLabel("Primer Número: ");
etiqueta2 = new JLabel("Segundo Número: ");
etiqueta3 = new JLabel("Resultado: ");

campo1 = new JTextField(10);
campo1.setHorizontalAlignment(JTextField.RIGHT);//para que los numero se escriban a la derecha
campo2 = new JTextField(10);
campo2.setHorizontalAlignment(JTextField.RIGHT);
campo3 = new JTextField(15);
campo3.setHorizontalAlignment(JTextField.RIGHT);
campo3.setEditable(false);

suma_bot = new JButton("Sumar");
resta_bot = new JButton("Restar");
multi_bot = new JButton("Multiplicar");
divi_bot = new JButton("Dividir");
raiz1_bot = new JButton("Raiz del primero");
raiz2_bot = new JButton("Raiz del segundo");
mayor_bot = new JButton("Mayor");
limp_bot = new JButton("Limpiar Todo");

add(etiqueta1);
add(campo1);
add(etiqueta2);
add(campo2);
add(suma_bot);
add(resta_bot);
add(multi_bot);
add(divi_bot);
add(raiz1_bot);
add(raiz2_bot);
add(mayor_bot);
add(limp_bot);
add(etiqueta3);
add(campo3);

suma_bot.addActionListener(this);
resta_bot.addActionListener(this);
multi_bot.addActionListener(this);
divi_bot.addActionListener(this);
limp_bot.addActionListener(this);
mayor_bot.addActionListener(this);
raiz1_bot.addActionListener(this);
raiz2_bot.addActionListener(this);
// TODO start asynchronous download of heavy resources

}

public void actionPerformed(ActionEvent e) {

if(e.getSource() == suma_bot)
{
if(verificar())
{
var2 = Float.valueOf(campo1.getText());
var3 = Float.valueOf(campo2.getText());
campo3.setText(String.valueOf(var2 + var3));
}
else
JOptionPane.showMessageDialog(this, "Error, alguno de los campos estan vacios");
}

if(e.getSource() == resta_bot)
{
if(verificar())
{
var2 = Float.valueOf(campo1.getText());
var3 = Float.valueOf(campo2.getText());
campo3.setText(String.valueOf(var2 - var3));
}
else
JOptionPane.showMessageDialog(this, "Error, alguno de los campos estan vacios");
}

if(e.getSource() == multi_bot)
{
if(verificar())
{
var2 = Float.valueOf(campo1.getText());
var3 = Float.valueOf(campo2.getText());
campo3.setText(String.valueOf(var2 * var3));
}
else
JOptionPane.showMessageDialog(this, "Error, alguno de los campos estan vacios");
}

if(e.getSource() == divi_bot)
{
if(verificar())
{
var2 = Float.valueOf(campo1.getText());
var3 = Float.valueOf(campo2.getText());
if(var3 == 0)
JOptionPane.showMessageDialog(this, "Error, no es posibe la división entre cero");
else
campo3.setText(String.valueOf(var2 / var3));
}
else
JOptionPane.showMessageDialog(this, "Error, alguno de los campos estan vacios");
}

if(e.getSource() == mayor_bot)
{
if(verificar())
{
var2 = Float.valueOf(campo1.getText());
var3 = Float.valueOf(campo2.getText());
if(var2 > var3)
campo3.setText(String.valueOf(var2));
if(var2 <>
campo3.setText(String.valueOf(var3));
if(var2 == var3)
campo3.setText("Son iguales");
}
else
JOptionPane.showMessageDialog(this, "Error, alguno de los campos estan vacios");

}

if(e.getSource() == raiz1_bot)
{
var = Float.valueOf(campo1.getText());
if(var<0) var =" Float.valueOf(campo2.getText());">

Applet en Java: Eventos. Cambio de Color de fondo

Aqui un ejemplo del manejo de eventos en Java utilizando un applet para seleccionar el color de fondo del mismo haciendo uso de 3 ScrollBar por medio de las funciones paint y repain.

/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import javax.swing.JLabel;
import javax.swing.JScrollBar;
import javax.swing.JTextField;

/**
*
* @author renan
*/
public class NewApplet extends Applet implements AdjustmentListener{
JLabel etiqueta1, etiqueta2, etiqueta3;
JScrollBar barra1,barra2,barra3;
JTextField campo1,campo2,campo3;
int valor1,valor2,valor3;
/**
* Initialization method that will be called after the applet is loaded
* into the browser.
*/
public void init() {
// TODO start asynchronous download of heavy resources

barra1 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);
barra2 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);
barra3 = new JScrollBar(JScrollBar.HORIZONTAL, 0, 1, 0, 255);

etiqueta1 = new JLabel("Deslizador #1: ");
etiqueta2 = new JLabel("Deslizador #2: ");
etiqueta3 = new JLabel("Deslizador #3: ");

campo1 = new JTextField(3);
campo1.setEditable(false);
campo2 = new JTextField(3);
campo2.setEditable(false);
campo3 = new JTextField(3);
campo3.setEditable(false);

add(barra1);
add(barra2);
add(barra3);
add(etiqueta1);
add(campo1);
add(etiqueta2);
add(campo2);
add(etiqueta3);
add(campo3);

barra1.addAdjustmentListener(this);
barra2.addAdjustmentListener(this);
barra3.addAdjustmentListener(this);
}

public void adjustmentValueChanged(AdjustmentEvent e) {
valor1 = barra1.getValue();
campo1.setText(""+valor1);

valor2 = barra2.getValue();
campo2.setText(""+valor2);

valor3 = barra3.getValue();
campo3.setText(""+valor3);

repaint();
}
public void paint(Graphics g)
{

g.drawRect(0, 0, 200, 400);
g.setColor(new Color(valor1, valor2, valor3));

g.fillRect(0, 0, 200, 400);
g.setColor(Color.BLACK);
}
// TODO overwrite start(), stop() and destroy() methods
}

Más información: http://es.wikipedia.org/wiki/Applet_Java

viernes, 14 de mayo de 2010

Programación en Java. Tema: Eventos


Eventos

Un evento se refiere a alguna acción que puede ser realizada por el usuario para que el applet realice alguna serie de instrucciones. Entre algunos eventos dentro de un applet tenemos:

  • oprimir en un botón específico.

  • mover una barra de desplazamiento.

  • oprimir una tecla específica.

Cuando un applet esta ejecutándose, éste puede estar esperando que el usuario active alguna secuencia de instrucciones mediante la selección de algún elemento de interfaz gráfica definida para esto, como lo hemos hecho anteriormente con el objeto de la clase Button.

Cuando creamos un objeto de interfaz gráfica que nos servirá para que el usuario indique alguna acción, es importante definirle a este objeto que será escuchado por la clase específica que se encarga de revisar si hay algún evento que ha sido realizado.

Escuchadores de eventos (Listeners)

Un Escuchador (Listener) es un objeto que es notificado cuando un evento ocurre. Este tiene dos requerimientos: 1) Debió haber sido registrado con una o más fuentes que reciben notificaciones sobre tipos de eventos específicos, y 2) Debe implementar métodos que reciban y procesen éstas notificaciones.

Los métodos que reciben y procesan estas notificaciones están definidos en un grupo de interfaces encontradas en java.awt.event. Por ejemplo la clase MouseMotionListener define dos métodos que reciben notificaciones cuando el ratón es arrastrado o movido. Algún objeto puede recibir y procesar uno o ambos de estos eventos si éste provee una implementación de esta interfase. Ver ejemplo.