Animacion Con Lineas en Java

Capturas de Pantalla



Codigo

package masterdavidjavabasico;

import java.awt.*;
import java.applet.Applet;

public class BouncingLines extends Applet implements Runnable {

    Thread runner = null;

    final static int WIDTH  = 600;
    final static int HEIGHT = 500;

    Image    image;
    Graphics graphics;



    int[] x1;
    int[] y1;
    int[] x2;
    int[] y2;

    int dx1 = 2 + (int)( 3 * Math.random() );
    int dy1 = 2 + (int)( 3 * Math.random() );
    int dx2 = 2 + (int)( 3 * Math.random() );
    int dy2 = 2 + (int)( 3 * Math.random() );

    static int first = 0;

    final static int LINES = 50;


    public void init() {


        x1 = new int[LINES];
        y1 = new int[LINES];
        x2 = new int[LINES];
        y2 = new int[LINES];

    

        x1[0] = (int)( WIDTH  * Math.random() );
        y1[0] = (int)( HEIGHT * Math.random() );
        x2[0] = (int)( WIDTH  * Math.random() );
        y2[0] = (int)( HEIGHT * Math.random() );

      

        for ( int i = 1; i < LINES; i++ ) {

            x1[i] = x1[0];
            y1[i] = y1[0];
            x2[i] = x2[0];
            y2[i] = y2[0];
        }
        image    = createImage( WIDTH, HEIGHT );
        graphics = image.getGraphics();
    }


    public void start() {

      

        if ( runner == null ) {

            runner = new Thread( this );
            runner.start();
        }
    }


    public void stop() {

       

        if ( runner != null && runner.isAlive() )
            runner.stop();

        runner = null;
    }


    public void run() {

        while (runner != null) {

            repaint();

            try {

                Thread.sleep( 20 );

            } catch ( InterruptedException e ) {

              
            }
        }
    }


    public void paint( Graphics g ) {

        update( g );
    }


    public void update( Graphics g ) {


        graphics.setColor( Color.white );
        graphics.fillRect( 0, 0, WIDTH, HEIGHT );

       

        graphics.setColor( Color.red );

        int line = first;

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

            graphics.drawLine( x1[line], y1[line],
                               x2[line], y2[line] );
            line++;
            if ( line == LINES ) line = 0;
        }

        line = first;

        first--;

        if ( first < 0 ) first = LINES - 1;

        x1[first] = x1[line];
        y1[first] = y1[line];
        x2[first] = x2[line];
        y2[first] = y2[line];

     
        if (x1[first] + dx2 < WIDTH)
            x1[first] += dx1;
        else
            dx1 = -(2 + (int)( 3 * Math.random() ));

        if (x1[first] + dx1 >= 0)
            x1[first] += dx1;
        else
            dx1 = 2 + (int)( 3 * Math.random() );

        if (y1[first] + dy1 < HEIGHT)
            y1[first] += dy1;
        else
            dy1 = -(2 + (int)( 3 * Math.random() ));

        if (y1[first] + dy1 >= 0)
            y1[first] += dy1;
        else
            dy1 = 2 + (int)( 3 * Math.random() );

        if (x2[first] + dx2 < WIDTH)
            x2[first] += dx2;
        else
            dx2 = -(2 + (int)( 3 * Math.random() ));

        if (x2[first] + dx2 >= 0)
            x2[first] += dx2;
        else
            dx2 = 2 + (int)( 3 * Math.random() );

        if (y2[first] + dy2 < HEIGHT)
            y2[first] += dy2;
        else
            dy2 = -(2 + (int)( 3 * Math.random() ));

        if (y2[first] + dy2 >= 0)
            y2[first] += dy2;
        else
            dy2 = 2 + (int)( 3 * Math.random() );



        g.drawImage( image, 0, 0, this );
    }
}

Descargar Programa

Animacion Sencilla en Java usando un circulo




Codigo

package masterdavidjavabasico;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Demo1 extends JComponent {

    private final static int ANCHO = 512;

    private final static int ALTO = 384;

    private final static int DIAMETRO = 20;

    private float x, y;

    private float vx, vy;

    public Demo1() {
        setPreferredSize(new Dimension(ANCHO, ALTO));
        x = 10;
        y = 20;
        vx = 300;
        vy = 400;
    }

    private void fisica(float dt) {
        x += vx * dt;
        y += vy * dt;
        if (vx < 0 && x <= 0 || vx > 0 && x + DIAMETRO >= ANCHO)
            vx = -vx;
        if (vy < 0 && y < 0 || vy > 0 && y + DIAMETRO >= ALTO)
            vy = -vy;
    }

    public void paint(Graphics g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, ANCHO, ALTO);
        g.setColor(Color.RED);
        g.fillOval(Math.round(x), Math.round(y), DIAMETRO, DIAMETRO);
    }

    private void dibuja() throws Exception {
        SwingUtilities.invokeAndWait(new Runnable() {
                public void run() {
                    paintImmediately(0, 0, ANCHO, ALTO);
                }
            });
    }

    public void cicloPrincipalJuego() throws Exception {
        long tiempoViejo = System.nanoTime();
        while (true) {
            long tiempoNuevo = System.nanoTime();
            float dt = (tiempoNuevo - tiempoViejo) / 1000000000f;
            tiempoViejo = tiempoNuevo;
            fisica(dt);
            dibuja();
        }
    }

    public static void main(String[] args) throws Exception {
        JFrame jf = new JFrame("Demo1");
        jf.addWindowListener(new WindowAdapter() {
                public void windowClosing(WindowEvent e) {
                    System.exit(0);
                }
            });
        jf.setResizable(false);
        Demo1 demo1 = new Demo1();
        jf.getContentPane().add(demo1);
        jf.pack();
        jf.setVisible(true);
        demo1.cicloPrincipalJuego();
    }
}
Descargar el Programa

Animacion Relog en Java Con Imagenes

Capturas 





Codigo

package relog03dic09;

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

/**
 *
 * @author Master
 */
public class AnimadorLogo extends JPanel
        implements ActionListener{
    protected ImageIcon imagenes[]; // declaramos un arreglo de imagenes
    protected int totalImagenes=24, //variable de tipo entero ultima imagen
            imagenActual=0, // variable de tipo entero primera imagen
            retardoAnimacion=1500; //1500 milisegundos de retardo
    protected Timer cronoAnimacion; // variable de tipo tiempo
    public AnimadorLogo() // constructor
    {
        setSize(getPreferredSize()); // toma el valor de las dimenciones de la imagen
        imagenes=new ImageIcon[totalImagenes]; // manda una instancia al arreglo de imagenes
        for(int i=0; i<imagenes.length; ++i) // se hace un incremento en i empesando de 0 de 1 en 1 hasta el valor asignado a la variable totalImagenes
            imagenes[i]=
                    new ImageIcon("imgrelog/relog"+i+".gif"); // genera un nombre para la imagen y lo va cambiando dependiendo el valor de i
        iniciaAnimacion(); // manda a llamar el metodo iniciaAnimacion que esta mas abajo
            }
public void paintComponent(Graphics g)
{
        super.paintComponent(g);//inicia los componentes del metodo graphics
if(imagenes[imagenActual].getImageLoadStatus()==MediaTracker.COMPLETE){//va cambiando la imagen
    imagenes[imagenActual].paintIcon(this, g, 0, 0);// imprime la imagen en las cordenandas 0,0
            imagenActual=(imagenActual+1)%totalImagenes;// cuando la imagen llega a la ultima regresa al principio
}


}
public void actionPerformed(ActionEvent e)
{
    repaint();// actualiza la ventana para que no se amontonen las imagenes
}
public void iniciaAnimacion()
{
    if(cronoAnimacion ==null){
        imagenActual=0;
        cronoAnimacion = new Timer(retardoAnimacion, this);
        cronoAnimacion.start();
    }
    else
        if(!cronoAnimacion.isRunning())
            cronoAnimacion.restart();
}
public void terminaAnimacion()
{
    cronoAnimacion.stop();
}
public Dimension getMinimumSize()
{
    return getPreferredSize();
}
public Dimension getPreferedSize()
{
    return new Dimension(500,500);
}
public static void main(String args[])
{
    AnimadorLogo anim = new AnimadorLogo();
    JFrame app = new JFrame("Master Animacion");
    app.getContentPane().add( anim, BorderLayout.CENTER);
    app.addWindowListener(new WindowAdapter(){
        public void windowClosing(WindowEvent e)
        {
            System.exit(0);
        }
    }
    );
    app.setSize ( anim.getPreferredSize().width+58+250,
            anim.getPreferredSize().height+80+250);
    app.show();
}
}
Descargar Proyecto

Interfas en Java con Imagen de Fondo - Programa para el calculo de resistencias

Capturas

Codigo

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

/*
 * masterdavid.java
 *
 * Created on 15/12/2009, 12:06:35 AM
 */

package resistenciasmasterdavid;

/**
 *
 * @author Master David
 */
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.awt.event.ComponentListener;
import java.awt.event.ComponentEvent;
import com.sun.awt.AWTUtilities;
import java.util.Locale;

public class masterdavid extends javax.swing.JFrame {
    int fr1,fr2,fr3,fr4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JButton jButton1;
private javax.swing.JButton boton0;
private javax.swing.JButton boton1;
private javax.swing.JButton boton2;
private javax.swing.JButton boton3;
private javax.swing.JButton boton4;
private javax.swing.JButton boton5;
private javax.swing.JButton boton6;
private javax.swing.JComboBox jComboBox1;
private javax.swing.JComboBox jComboBox2;
private javax.swing.JComboBox jComboBox3;
private javax.swing.JComboBox jComboBox4;
private javax.swing.JTextField jTextField1;
private javax.swing.JTextField jTextField2;
private javax.swing.JTextField jTextField3;
private javax.swing.JTextField jTextField4;
    /** Creates new form masterdavid */
    public masterdavid() {
        jLabel6 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
         boton0 = new javax.swing.JButton();
         boton1 = new javax.swing.JButton();
         boton2 = new javax.swing.JButton();
         boton3 = new javax.swing.JButton();
         boton4 = new javax.swing.JButton();
         boton5 = new javax.swing.JButton();
         boton6 = new javax.swing.JButton();
         jComboBox1 = new javax.swing.JComboBox();
         jComboBox2 = new javax.swing.JComboBox();
         jComboBox3 = new javax.swing.JComboBox();
         jComboBox4 = new javax.swing.JComboBox();
         jTextField1 = new javax.swing.JTextField();
         jTextField2 = new javax.swing.JTextField();
         jTextField3 = new javax.swing.JTextField();
         jTextField4 = new javax.swing.JTextField();


//boton0
         boton0 = new JButton("");
                boton0.setBackground(Color.white);
                boton0.setBounds(new Rectangle(200+52,112,32,110));
                add(boton0);
                boton0.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton1ActionPerformed(evt);
            }
                 });
//boton1
                boton1 = new JButton("");
                boton1.setBackground(Color.white);
                boton1.setBounds(new Rectangle(300-2,112,32,110));
                add(boton1);

                boton2 = new JButton("");
                boton2.setBackground(Color.white);
                boton2.setBounds(new Rectangle(252+96,112,32,110));
                add(boton2);

                boton3 = new JButton("");
                boton3.setBackground(Color.white);
                boton3.setBounds(new Rectangle(252+147,112,32,110));
                add(boton3);
//Por colores
                boton4 = new JButton("Por Colores");
                boton4.setBounds(new Rectangle(50,50,120,20));
                add(boton4);
                boton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton4ActionPerformed(evt);
            }
                 });

//Por valor
                boton5 = new JButton("Por Valor");
                boton5.setBounds(new Rectangle(50,90,120,20));
               
                boton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton5ActionPerformed(evt);
            }
                 });

//Calcular
                boton6 = new JButton("Obtener Valor");
                boton6.setBounds(new Rectangle(100,300,120,20));
                add(boton6);
                boton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                boton6ActionPerformed(evt);
            }
                 });

//combobox1
                jComboBox1.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1","Negro", "Cafe", "Rojo", "Naranja","Amarillo","Verde","Azul","Violeta","Gris","Blanco" }));
                jComboBox1.setBounds(200,60 , 70, 19);
                add(jComboBox1);
         jComboBox1.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox1ItemStateChanged(evt);
            }
        });
//combobox2
       jComboBox2.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"2","Negro", "Cafe", "Rojo", "Naranja","Amarillo","Verde","Azul","Violeta","Gris","Blanco" }));
                jComboBox2.setBounds(200+80,60 , 70, 19);
                add(jComboBox2);
         jComboBox2.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox2ItemStateChanged(evt);
            }
        });

        //combobox3
        jComboBox3.setModel(new javax.swing.DefaultComboBoxModel(new String[] {"3","Negro", "Cafe", "Rojo", "Naranja","Amarillo","Verde","Azul","Violeta","Gris","Blanco" }));
                jComboBox3.setBounds(200+160,60 , 70, 19);
                add(jComboBox3);
         jComboBox3.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox3ItemStateChanged(evt);
            }
        });

        //combobox4
        jComboBox4.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "4", "Plateado", "Dorado" }));
                jComboBox4.setBounds(200+240,60 , 70, 19);
                add(jComboBox4);
         jComboBox4.addItemListener(new java.awt.event.ItemListener() {
            public void itemStateChanged(java.awt.event.ItemEvent evt) {
                jComboBox4ItemStateChanged(evt);
            }
        });
        // boton para cerrar
        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resistenciasmasterdavid/cerrar.png"))); // NOI18N
        jButton1.setBounds(580, 40, 30  , 20);
        add(jButton1);
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
//resultado
        jLabel6.setText("El Valor de la Resistencia es: ");
        jLabel6.setBounds(170, 250, 170, 20);
        add(jLabel6);
        jTextField1.setText("Valor");
        jTextField1.setBounds(350, 250, 120, 20);
        add(jTextField1);
        //res max
        jLabel3.setText(" Valor Maximo: ");
                jLabel3.setBounds(250, 250+30, 170, 20);
        add(jLabel3);
        jTextField2.setText(" Valor Max");
        jTextField2.setBounds(350, 280, 120, 20);
        add(jTextField2);
        //res min
        jLabel4.setText(" Valor Minimo: ");
                jLabel4.setBounds(250, 250+60, 170, 20);
        add(jLabel4);
        jTextField3.setText("Valor Min");
        jTextField3.setBounds(350, 310, 120, 20);
        add(jTextField3);
        //tolerancia
        jLabel5.setText("Tolerancia: ");
                jLabel5.setBounds(270, 250+90, 170, 20);
        add(jLabel5);
        jTextField4.setText("Tolerancia");
        jTextField4.setBounds(350, 340, 120, 20);
        add(jTextField4);



         setUndecorated(true);
         setResizable(false);
        AWTUtilities.setWindowOpaque(this, false);
// setLocation(400, 300);
 setSize(660,440);
 setLocationRelativeTo(null);

initComponents();


      
    }

public void paintComponent(Graphics g) {
}
    /** 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() {

        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Resistencias Master David");
        setAlwaysOnTop(true);
        setCursor(new java.awt.Cursor(java.awt.Cursor.CROSSHAIR_CURSOR));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/resistenciasmasterdavid/masterbackground.png"))); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel2))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel2)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>                       
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
        if(0==0){      
            System.exit(0);
        }
}
    //evento boton 1
    public void boton1ActionPerformed(java.awt.event.ActionEvent evt){
   if(0==0) {
  
   }
}
     //evento boton 4 por color
    public void boton4ActionPerformed(java.awt.event.ActionEvent evt){
   if(0==0) {
       jComboBox1.setSelectedItem(null);
       jComboBox2.setSelectedItem(null);
       jComboBox3.setSelectedItem(null);
       jComboBox4.setSelectedItem(null);
       jComboBox1.setEnabled(true);
       jComboBox2.setEnabled(true);
       jComboBox3.setEnabled(true);
       jComboBox4.setEnabled(true);
       boton0.setBackground(Color.white);
       boton1.setBackground(Color.white);
       boton2.setBackground(Color.white);
    boton3.setBackground(Color.white);
    boton4.setEnabled(false);
    boton5.setEnabled(true);
   }
}
         //evento boton 5 por valor
    public void boton5ActionPerformed(java.awt.event.ActionEvent evt){

   if(0==0) {
              jComboBox1.setSelectedItem(null);
       jComboBox2.setSelectedItem(null);
       jComboBox3.setSelectedItem(null);
       jComboBox4.setSelectedItem(null);
       boton0.setBackground(Color.white);
       boton1.setBackground(Color.white);
       boton2.setBackground(Color.white);
    boton3.setBackground(Color.white);
       jComboBox1.setEnabled(false);
       jComboBox2.setEnabled(false);
       jComboBox3.setEnabled(false);
       jComboBox4.setEnabled(false);
       boton5.setEnabled(false);
       boton4.setEnabled(true);

   }
}

    // evento de jcombobox1
private void jComboBox1ItemStateChanged(java.awt.event.ItemEvent evt) {
 //   int fr1=0;
    int opcion = jComboBox1.getSelectedIndex();
       if(opcion== 0){
           boton0.setBackground(Color.white);
       }
    if(opcion== 1){
        boton0.setBackground(Color.black);
        fr1=00;
       }
    if(opcion== 2){
       boton0.setBackground(new Color(152, 102, 0));
       fr1=10;
       }
    if(opcion== 3){
       boton0.setBackground(Color.red);
       fr1=20;
       }
    if(opcion== 4){
       boton0.setBackground(Color.ORANGE);
       fr1=30;
       }
    if(opcion== 5){
       boton0.setBackground(Color.yellow);
       fr1=40;
       }
    if(opcion== 6){
       boton0.setBackground(Color.GREEN);
       fr1=50;
       }
    if(opcion== 7){
       boton0.setBackground(Color.BLUE);
       fr1=60;
       }
    if(opcion== 8){
      boton0.setBackground(new Color(153,0,153));
      fr1=70;
       }
    if(opcion== 9){
       boton0.setBackground(Color.GRAY);
       fr1=80;
       }
    if(opcion== 10){
       boton0.setBackground(Color.white);
       fr1=90;
       }

    }
private void jComboBox2ItemStateChanged(java.awt.event.ItemEvent evt) {
  //  int fr2=0;
     int opcion2 = jComboBox2.getSelectedIndex();
       if(opcion2== 0){
           boton1.setBackground(Color.white);

       }
    if(opcion2== 1){
        boton1.setBackground(Color.black);
        fr2=0;
       }
    if(opcion2== 2){
       boton1.setBackground(new Color(152, 102, 0));
       fr2=1;
       }
    if(opcion2== 3){
       boton1.setBackground(Color.red);
       fr2=2;
       }
    if(opcion2== 4){
       boton1.setBackground(Color.ORANGE);
       fr2=3;
       }
    if(opcion2== 5){
       boton1.setBackground(Color.yellow);
       fr2=4;
       }
    if(opcion2== 6){
       boton1.setBackground(Color.GREEN);
       fr2=5;
       }
    if(opcion2== 7){
       boton1.setBackground(Color.BLUE);
       fr2=6;
       }
    if(opcion2== 8){
      boton1.setBackground(new Color(153,0,153));
      fr2=7;
       }
    if(opcion2== 9){
       boton1.setBackground(Color.GRAY);
       fr2=8;
       }
    if(opcion2== 10){
       boton1.setBackground(Color.white);
       fr2=9;
       }       // TODO add your handling code here:
    }
private void jComboBox3ItemStateChanged(java.awt.event.ItemEvent evt) {
 //   int fr3=0;
    int opcion3 = jComboBox3.getSelectedIndex();
       if(opcion3== 0){
           boton2.setBackground(Color.white);

       }
    if(opcion3== 1){
        boton2.setBackground(Color.black);
        fr3=1;
       }
    if(opcion3== 2){
       boton2.setBackground(new Color(152, 102, 0));
       fr3=10;
       }
    if(opcion3== 3){
       boton2.setBackground(Color.red);
       fr3=100;
       }
    if(opcion3== 4){
       boton2.setBackground(Color.ORANGE);
       fr3=1000;
       }
    if(opcion3== 5){
       boton2.setBackground(Color.yellow);
       fr3=10000;
       }
    if(opcion3== 6){
       boton2.setBackground(Color.GREEN);
       fr3=100000;
       }
    if(opcion3== 7){
       boton2.setBackground(Color.BLUE);
       fr3=1000000;
       }
    if(opcion3== 8){
      boton2.setBackground(new Color(153,0,153));
      fr3=10000000;
       }
    if(opcion3== 9){
       boton2.setBackground(Color.GRAY);
       fr3=100000000;
       }
    if(opcion3== 10){
       boton2.setBackground(Color.white);
       fr3=1000000000;
       }    // TODO add your handling code here:
    }
private void jComboBox4ItemStateChanged(java.awt.event.ItemEvent evt) {
    //int fr4=0;
    int opcion4 = jComboBox4.getSelectedIndex();
   
    if(opcion4== 0){// TODO add your handling code here:
        boton3.setBackground(Color.white);
       
    }
    if(opcion4== 1){// TODO add your handling code here:
        boton3.setBackground(new Color(204,204,204));
        fr4=10;
    }
    if(opcion4== 2){
        boton3.setBackground(new Color(204,204,0));
        fr4=5;
    }
    }
        public void boton6ActionPerformed(java.awt.event.ActionEvent evt){

            int resultadores;
            int mx;
            String max;
            int mn;
            String min;
            int tol=fr4;
            String tole;
            String produc;
   if(0==0) {
resultadores=(fr1+fr2)*fr3;
produc=resultadores+" ohms";
jTextField1.setText(produc);

tole=tol+" %";
jTextField4.setText(tole);

mx=resultadores+((resultadores*fr4)/100);
max=mx+" ohms";
jTextField2.setText(max);

mn=resultadores-((resultadores*fr4)/100);
min=mn+" ohms";
jTextField3.setText(min);

   }
}
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new masterdavid().setVisible(true);

            }
        });

    }

    // Variables declaration - do not modify                    
    private javax.swing.JLabel jLabel2;
    // End of variables declaration                  
    private Image imagen = null;

}


DESCARGAR ARCHIVO

Establecer los componentes para la apariencia

el cuadro de texto que aparece debajo de la etiqueta tiene la apariencia de una
etiqueta. Esto le indica la potencia de la gestión de apariencias en Swing.

package masterdavidjavabasico;

import java.awt.*;
import javax.swing.*;

/*
<APPLET
    CODE=plafcomponente.class
    WIDTH=210
    HEIGHT=200 >
</APPLET>
*/

public class plafcomponente extends JApplet
{
    public void init()
    {
        Container contentPane = getContentPane();

        JNewLabel jnewlabel = new JNewLabel(
                "Esta es una etiqueta falsa.");

        contentPane.setLayout(new FlowLayout());
                                   
        contentPane.add(new JLabel("Esta es una etiqueta real."));
        contentPane.add(jnewlabel);
    }
}

class JNewLabel extends JTextField
{
    public JNewLabel(String s)
    {
        super(s);
    }
    public void updateUI()
    {
        super.updateUI();

        setHighlighter(null);
        setEditable(false);

        LookAndFeel.installBorder(this, "Label.border");

        LookAndFeel.installColorsAndFont(this, "Label.background",
            "Label.foreground", "Label.font");
    }
}

Cambio de apariencia

muestra la applet con la apariencia Metal, Motify  y la de Windows. Cambiar entre estas apariencias es tan
fácil como hacer clic sobre un botón de opción.

package masterdavidjavabasico;

import java.awt.*;
import javax.swing.*;
import java.awt.event.*;


/*
<APPLET
    CODE=plaf.class
    WIDTH=210
    HEIGHT=200 >
</APPLET>
*/

public class plaf extends JApplet
{

    JRadioButton b1 = new JRadioButton("Metal"),
    b2 = new JRadioButton("Motif"),
    b3 = new JRadioButton("Windows");

    public void init()
    {
        Container contentPane = getContentPane();
        contentPane.add(new jpanel(), BorderLayout.CENTER);
    }

    class jpanel extends JPanel implements ActionListener
    {
        public jpanel()
        {
            add(new JButton("JBoton"));
            add(new JTextField("JCuadro_de_texto"));
            add(new JCheckBox("JCasilla_de_activacion"));
            add(new JRadioButton("JBoton_de_opcion"));
            add(new JLabel("JEtiqueta"));
            add(new JList(new String[] {
                "JLista Elemento 1", "JLista Elemento 2","JLista Elemento 3"}));
            add(new JScrollBar(SwingConstants.HORIZONTAL));

            ButtonGroup group = new ButtonGroup();
            group.add(b1);
            group.add(b2);
            group.add(b3);

            b1.addActionListener(this);
            b2.addActionListener(this);
            b3.addActionListener(this);

            add(b1);
            add(b2);
            add(b3);
        }

        public void actionPerformed(ActionEvent e)
        {
            JRadioButton src = (JRadioButton)e.getSource();

            try {
                if((JRadioButton)e.getSource() == b1)
                    UIManager.setLookAndFeel(
                      "javax.swing.plaf.metal.MetalLookAndFeel");
                else if((JRadioButton)e.getSource() == b2)
                    UIManager.setLookAndFeel(
                        "com.sun.java.swing.plaf.motif.MotifLookAndFeel");
                else if((JRadioButton)e.getSource() == b3)
                    UIManager.setLookAndFeel(
                        "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
            }
            catch(Exception ex) {}

            SwingUtilities.updateComponentTreeUI(getContentPane());
        }
    }
}

Holo desde java Swing JFrame

Ahora, además, hemos usado el método setBounds para fijar la posición y
tamaño de la ventana JFrame.
package masterdavidjavabasico;

import javax.swing.*;
import java.awt.*;


public class app extends JFrame
{
    jpanel j;

    public app()
    {
        super("Aplicacion Swing");

        Container contentPane = getContentPane();
        j = new jpanel();
        contentPane.add(j);
    }

    public static void main(String args[])
    {
        final JFrame f = new app();

        f.setBounds(100, 100, 300, 300);
        f.setVisible(true);
        f.setBackground(Color.white);
        //f.setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        //f.addWindowListener(new WindowAdapter() {
        //    public void windowClosed(WindowEvent e) {
        //        System.exit(0);
        //    }
        //});

    }
}

class jpanel extends JPanel
{
    jpanel()
    {
        setBackground(Color.white);
    }

    public void paintComponent (Graphics g)
    {
        super.paintComponent(g);
        g.drawString("Hola desde Swing!", 0, 60);
    }
}

Applet que abre una ventana con menus

package masterdavidjavabasico;

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*
<APPLET
    CODE=menu.class
    WIDTH=200
    HEIGHT=200 >
</APPLET>
*/

public class menu extends Applet implements ActionListener
{
    Button b1;
    frame menuWindow;

    public void init()
    {
        b1 = new Button("Visualizar el menu de la ventana");
        add(b1);
        b1.addActionListener(this);

        menuWindow = new frame("Menus");
        menuWindow.setSize(200, 200);
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == b1){
            menuWindow.setVisible(true);
        }
    }
}

class frame extends Frame implements ActionListener
{
    Menu menu;
    MenuBar menubar;
    MenuItem menuitem1, menuitem2, menuitem3;

    Label label;

    frame(String title)
    {
        super(title);
        label = new Label("Hola desde Java!");
        setLayout(new GridLayout(1, 1));
        add(label);
        menubar = new MenuBar();

        menu = new Menu("Archivo");

        menuitem1 = new MenuItem("Elemento 1");
        menu.add(menuitem1);
        menuitem1.addActionListener(this);

        menuitem2 = new MenuItem("Elemento 2");
        menu.add(menuitem2);
        menuitem2.addActionListener(this);

        menuitem3 = new MenuItem("Elemento 3");
        menu.add(menuitem3);
        menuitem3.addActionListener(this);

        menubar.add(menu);

        setMenuBar(menubar);

         addWindowListener(new WindowAdapter() {public void
              windowClosing(WindowEvent e) {setVisible(false);}});
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == menuitem1){
            label.setText("Eligio el elemento 1");
        } else if(event.getSource() == menuitem2){
            label.setText("Eligio el elemento 2");
        } else if(event.getSource() == menuitem3){
            label.setText("Eligio el elemento 3");
        }
    }
}

Abrir una ventana desde otra ventana

Como se puede ver, la ventana
aparece con un borde mínimo y la etiqueta de control que visualiza un mensaje.

package masterdavidjavabasico;

import java.awt.*;
import java.awt.event.*;


public class ventana 
{
    public static void main(String [] args)
    {
       AppFrame f = new AppFrame();

       f.setSize(200, 200);

       f.addWindowListener(new WindowAdapter() { public void
           windowClosing(WindowEvent e) {System.exit(0);}});

       f.show();
    }
}

class AppFrame extends Frame implements ActionListener
{
    Button b1, b2;
    labelWindow window;

    AppFrame()
    {
        setLayout(new FlowLayout());
        b1 = new Button("Visualizar la ventana");
        add(b1);
        b1.addActionListener(this);

        b2 = new Button("Ocultar la ventana");
        add(b2);
        b2.addActionListener(this);

        window = new labelWindow(this);
        window.setSize(300, 200);
        window.setLocation(300, 200);
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == b1){
            window.setVisible(true);
        }
        if(event.getSource() == b2){
            window.setVisible(false);
        }
    }
}

class labelWindow extends Window {
    Label label;

    labelWindow(AppFrame af){
        super(af);
        setLayout(new FlowLayout());
        label = new Label("Hola desde Java!");
        add(label);
    }

    public void paint (Graphics g)
    {
        int width = getSize().width;
        int height = getSize().height;

        g.drawRect(0, 0, --width, --height);
    }
}

Gestionar eventos de ventana

se puede ver, la ventana
frame gestiona eventos MouseListener, visualizando mensajes.

package masterdavidjavabasico;

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*
<APPLET
    CODE=frame.class
    WIDTH=300
    HEIGHT=200 >
</APPLET>
*/

public class frame extends Applet implements ActionListener {

    Button b1, b2;
    labelFrame window;

    public void init()
    {
        b1 = new Button("Visualizar la ventana");
        add(b1);
        b1.addActionListener(this);

        b2 = new Button("Ocultar la ventana");
        add(b2);
        b2.addActionListener(this);

        window = new labelFrame("Ventana Java");
        window.setSize(350, 250);
    }

    public void actionPerformed(ActionEvent event)
    {
        if(event.getSource() == b1){
            window.setVisible(true);
        }
        if(event.getSource() == b2){
            window.setVisible(false);
        }
    }
}

class labelFrame extends Frame implements MouseListener {
    Label label;

    labelFrame(String title){
        super(title);
        setLayout(new FlowLayout());
        label = new Label("Hola desde Java! Esta es una ventana frame.");
        add(label);
        addMouseListener(this);
         addWindowListener(new WindowAdapter() {public void
             windowClosing(WindowEvent e) {setVisible(false);}});
    }

    public void mousePressed(MouseEvent e)
    {
        if((e.getModifiers() & InputEvent.BUTTON1_MASK) ==
            InputEvent.BUTTON1_MASK){
            label.setText("Boton izquierdo del raton pulsado en " + e.getX() + "," + e.getY());
        }
        else{
            label.setText("Boton derecho del raton pulsado en " + e.getX() + "," + e.getY());
        }
    }

    public void mouseClicked(MouseEvent e)
    {
        label.setText("Pulso el raton en " + e.getX() + "," + e.getY());
    }

    public void mouseReleased(MouseEvent e)
    {
        label.setText("Se solto el boton del raton.");
    }

    public void mouseEntered(MouseEvent e)
    {
        label.setText("Raton para introducir.");
    }

    public void mouseExited(MouseEvent e)
    {
        label.setText("Raton para salir.");
    }
}

Usar la interfaz lmageobserver en un applet de java

El resultado se muestra  donde la imagen aparece una vez
que ha sido totalmente cargada.

Bueno el ejemplo se pude ver mejor cuando la imagen al igual que el applet estan en un servidor web para realmente ver como se carga la imagen.

package masterdavidjavabasico;

import java.awt.*;
import java.applet.*;
import javax.swing.*;

/*
  <APPLET
      CODE=iobserver.class
      WIDTH=600
      HEIGHT=150 >
  </APPLET>
*/

public class iobserver extends Applet
{
    ImageIcon image;

    public void init()
    {
        image = new ImageIcon( "image.png");
    }

    public void paint(Graphics g)
    {
        image.paintIcon(this, g, 0, 0);
    }

  public boolean imageUpdate(Image img, int flags, int x, int y, int w, int h)
  {
      if ((flags & ALLBITS) != 0) { 
          repaint(x, y, w, h);      
      } 
      return (flags & ALLBITS) == 0;
  }
}

Canvas en applet de java

Cuando se hace clic sobre el applet, el canvas, que visualiza una figura pequeña, se mueve a la izquierda y
luego hacia la derecha.


package masterdavidjavabasico;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
  <APPLET
      CODE=canvas.class
      WIDTH=400
      HEIGHT=200 >
  </APPLET>
*/

public class canvas extends java.applet.Applet implements MouseListener {

    graphicsCanvas gc;
    Button button1;

    public void init()
    {
        gc = new graphicsCanvas();
        gc.setSize(100, 100);
        add(gc);
        addMouseListener(this);
    }
   
    public void mousePressed(MouseEvent e){}

    public void mouseClicked(MouseEvent e)
    {
       for(int loop_index = 0; loop_index < 150; loop_index++){
           gc.setLocation(loop_index, 0);
       }
    }
    public void mouseReleased(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
}

class graphicsCanvas extends java.awt.Canvas
{
    public void paint (Graphics g)
    {
        g.drawOval(10, 50, 40, 40);
        g.drawLine(10, 50, 50, 90);
        g.drawLine(50, 50, 10, 90);
    }
}

Operar con figuras y libre en un applet activo

El usuario hace clic sobre un botón indicando qué clase de figura quiere dibujar,
con lo que se activa un indicador booleano en el programa. Cuando después
el usuario presiona el ratón en la superficie de dibujo, ésa ubicación se
almacena como start, usando un objeto Point (que tiene dos miembros de
datos: x e y). Cuando se suelta el ratón en una nueva posición, esta se
almacena como end. Al soltar el ratón, también se vuelve a pintar el programa,
y el usuario puede seleccionar la figura a dibujar, una recta, óvalo,
rectángulo o rectángulo redondeado, entre las posiciones start y end basándo- ,
se en el indicador boleano fijado al hacer clic sobre los botones.
El dibujo libre con el ratón es diferente. En ese caso, se almacenan hastfl
1.000 puntos sobre los que se mueve el ratón. En el momento de dibujar,
basta con unir los puntos con líneas (observe que no se genera un evento de
ratón por cada pixel sobre el que se mueve el ratón, por lo tanto es necesario
dibujar líneas entre las distintas posiciones del ratón que Java comunica).

package masterdavidjavabasico;

import java.awt.*;
import java.lang.Math;
import java.awt.event.*;
import java.awt.Graphics;
import java.applet.Applet;

/*
  <APPLET
      CODE=dibujar.class
      WIDTH=600
      HEIGHT=200 >
  </APPLET>
*/

public class dibujar extends Applet implements ActionListener, MouseListener, MouseMotionListener {
    Button bDraw, bLine, bOval, bRect, bRounded;
    Point dot[] = new Point[1000];
    Point start, end;
    int dots = 0;

    boolean mouseUp = false;
    boolean draw = false;
    boolean line = false;
    boolean oval = false;
    boolean rectangle = false;
    boolean rounded = false;

    public void init()
    {
        bLine = new Button("Dibujar rectas");
        bOval = new Button("Dibujar ovalos");
        bRect = new Button("Dibujar rectangulos");
        bRounded = new Button("Dibujar rectangulos redondeados");
        bDraw = new Button("Dibujo libre");

        add(bLine);
        add(bOval);
        add(bRect);
        add(bRounded);
        add(bDraw);

        bLine.addActionListener(this);
        bOval.addActionListener(this);
        bRect.addActionListener(this);
        bRounded.addActionListener(this);
        bDraw.addActionListener(this);

        addMouseListener(this);
        addMouseMotionListener(this);
    }
   
    public void mousePressed(MouseEvent e)
    {
        mouseUp = false;
        start = new Point(e.getX(), e.getY());
    }

    public void mouseReleased(MouseEvent e)
    {
        if(line){
            end = new Point(e.getX(), e.getY());
        } else {
            end = new Point(Math.max(e.getX(), start.x),
                Math.max(e.getY(), start.y));
            start = new Point(Math.min(e.getX(), start.x),
                Math.min(e.getY(), start.y));
        }
        mouseUp = true;
        repaint();
    }

    public void mouseDragged(MouseEvent e)
    {
        if(draw){
            dot[dots] = new Point(e.getX(), e.getY());
            dots++;
            repaint();
        }
    }

    public void mouseClicked(MouseEvent e){}
    public void mouseEntered(MouseEvent e){}
    public void mouseExited(MouseEvent e){}
    public void mouseMoved(MouseEvent e){}

    public void paint (Graphics g)
    {
        if (mouseUp) {
            int width = end.x - start.x;
            int height = end.y - start.y;

            if(line){
                g.drawLine(start.x, start.y, end.x, end.y);
            }
            else if(oval){
                g.drawOval(start.x, start.y, width, height);
            }
            else if(rectangle){
                g.drawRect(start.x, start.y, width, height);
            }
            else if(rounded){
                g.drawRoundRect(start.x, start.y, width, height, 10, 10);
            }
            else if(draw){
                for(int loop_index = 0; loop_index < dots - 1; loop_index++){
                    g.drawLine(dot[loop_index].x, dot[loop_index].y,
                        dot[loop_index + 1].x, dot[loop_index + 1].y);
                }
            }
        }
    }

    public void actionPerformed(ActionEvent e)
    {
        setFlagsFalse();
        if(e.getSource() == bDraw)draw = true;
        if(e.getSource() == bLine)line = true;
        if(e.getSource() == bOval)oval = true;
        if(e.getSource() == bRect)rectangle = true;
        if(e.getSource() == bRounded)rounded = true;
    }

    void setFlagsFalse()
    {
        rounded = false;
        line = false;
        oval = false;
        rectangle = false;
        draw = false;
    }
}

Poner una imagen en un applet de java

Aqui veremos como colocar una imagen en un applet y darle hubicasion

package masterdavidjavabasico;

import java.awt.*;
import java.applet.*;
import javax.swing.*;

/*
  <APPLET
      CODE=imagen.class
      WIDTH=500
      HEIGHT=150 >
  </APPLET>
*/

public class imagen extends Applet
{
    private ImageIcon image;
   

    public void init()
    {
       
        image = new ImageIcon("image.png");
    }

    public void paint(Graphics g)
    {


        image.paintIcon(this, g, 0, 0);
       
    }
}

Escribir directamente en un Applet de java

el usuario puede escribir texto directamente en esta applet, que funciona
como se esperaba.

Esto es sólo el comienzo del trabajo con texto.

package masterdavidjavabasico;

import java.awt.*;
import java.awt.event.*;
import java.applet.Applet;

/*
  <APPLET
      CODE=tecla.class
      WIDTH=300
      HEIGHT=200 >
  </APPLET>
*/

public class tecla extends Applet implements KeyListener {

    String text = "";

    public void init()
    {
        addKeyListener(this);
        requestFocus();
    }

    public void paint(Graphics g)
    {
        g.drawString(text, 0, 100);
    }

    public void keyTyped(KeyEvent e)
    {
        text = text + e.getKeyChar();
        repaint();
    }

    public void keyPressed(KeyEvent e) {}
    public void keyReleased(KeyEvent e) {}
}

Eventos del Mouse en un applet de java

Se puede ver esta applet funcionando Cuando se mueve el
ratón o se usa uno de sus botones, la applet permite saber lo que ocurre.

package masterdavidjavabasico;

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;

/*
<APPLET
    CODE=raton.class
    WIDTH=300
    HEIGHT=200 >
</APPLET>
*/

public class raton extends Applet implements MouseListener, MouseMotionListener
{
    TextField text1;

    public void init(){
        text1 = new TextField(35);
        add(text1);
        addMouseListener(this);
        addMouseMotionListener(this);
    }

    public void mousePressed(MouseEvent e)
    {
        if((e.getModifiers() & InputEvent.BUTTON1_MASK) == InputEvent.BUTTON1_MASK){
            text1.setText("Boton izquierdo del raton apretado en " + e.getX() + "," + e.getY());
        }
        else{
            text1.setText("Boton derecho del raton apretado en " + e.getX() + "," + e.getY());
        }
    }

    public void mouseClicked(MouseEvent e)
    {
        text1.setText("Hizo clic sobre el raton en " + e.getX() + "," + e.getY());
    }

    public void mouseReleased(MouseEvent e)
    {
        text1.setText("Se solt el boton del raton.");
    }


    public void mouseEntered(MouseEvent e)
    {
        text1.setText("Raton para introducir.");
    }

    public void mouseExited(MouseEvent e)
    {
        text1.setText("Raton para salir.");
    }

    public void mouseDragged(MouseEvent e)
    {
        text1.setText("Se arrasto el raton.");
    }

    public void mouseMoved(MouseEvent e)
    {
        text1.setText("Se movio el raton.");
    }
}