domingo, junio 21, 2009

Dos botones con evento




import javax.swing.*;

import java.awt.*;

import java.awt.event.*;



public class MiVentana extends JFrame {



    JLabel etiqueta;

    JButton boton;

    JButton boton2;

    JTextField caja;

    Papel papel;



    public MiVentana() {

        setTitle("ventanitita");

        setSize(300, 200);

        iniciarComponentes();

    }



    public void iniciarComponentes() {

        getContentPane().setLayout(null);

        setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

        etiqueta = new JLabel();

        boton = new JButton();

        boton2 = new JButton();

        caja = new JTextField();

        papel = new Papel();

        papel.setTF(caja);



        etiqueta.setText("Mete un #");

        etiqueta.setFont(new Font("Arial", Font.BOLD, 12));

        getContentPane().add(etiqueta);

        etiqueta.setBounds(20, 20, 100, 20);



        boton.setText("Validar");

        boton2.setText("Mostrar imagen");

        boton.setToolTipText("has click");

        getContentPane().add(boton);

        getContentPane().add(boton2);

        boton.setBounds(20, 120, 100, 20);

        boton2.setBounds(20, 140, 100, 20);

        getContentPane().add(caja);

        caja.setBounds(20, 60, 100, 20);



        boton.addActionListener(

                new ActionListener() {



                    public void actionPerformed(ActionEvent evt) {

                        codigoBoton1(evt);



                    }

                });

        boton2.addActionListener(

                new ActionListener() {



                    public void actionPerformed(ActionEvent evt) {

                        codigoBoton2(evt);

                    }

                });

    }



    public void codigoBoton1(ActionEvent ev) {

        String cad = caja.getText();

        boolean pasa = true;

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

            if (!Character. isDigit(cad. charAt( i)) ) {

                pasa = false;

            }

        }

                



        if (pasa) {

            float valor = Float.parseFloat( caja. getText() );

            etiqueta.setText("resultado de " + valor * 10);

        } else {

            etiqueta.setText("ingresa dato validos");

        }



    }

    public void codigoBoton2(ActionEvent ev) {

        getContentPane().add(papel);



        papel.setBounds(120, 60, 100, 100);

    }

    public static void main(String args[]) {

        new MiVentana().setVisible(true);

    }

}



class Papel extends Canvas {



    JTextField tf;



    public void setTF(JTextField tf) {

        this.tf = tf;

    }



    public void paint(Graphics g) {



        g.setColor(Color.yellow);



        g.drawOval(40, 40, 20, 20);

        g.drawOval(45, 40, 10, 20);

        g.drawOval(40, 45, 20, 10);



        g.drawRect(0, 0, 99, 99);



    }

}