my code stock.com

Snippet options

Download: Download snippet as animacion-pelota.java.
Copy snippet: For this you need a free my code stock.com account.
Embed code : You will find the embed code for this snippet at the end of the page, if you want to embed it into a website or a blog!

package usothreads;

import java.awt.*;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;


public class Animacion extends JFrame {
	

	public static void main(String[] args) {
		
		//-------------frame basico---------------------------
		JFrame frame = new JFrame("Animacion test");
		frame.setBounds(700, 400,500,400);
		frame.setVisible(true);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		//----------------------------------------------------
		
		
		LaminaPrincipal laminaPrincipal=new LaminaPrincipal();
		frame.add(laminaPrincipal);

		

	}
	
}

class LaminaPrincipal extends JPanel{
	public LaminaPrincipal(){
		
		this.setLayout(new BorderLayout());
		
		//---------------------------------------------
		LaminaPelota laminaPelota=new LaminaPelota();
		this.add(laminaPelota, BorderLayout.CENTER);		
		//---------------------------------------------
		
		JPanel laminaBotones=new JPanel();
		JButton btnStart=new JButton("Start");
		
		
		
		btnStart.addActionListener(new ActionListener(){

			@Override
			public void actionPerformed(ActionEvent e) {
				// TODO Auto-generated method stub
				for(int i=0;i<100;i++){
					laminaPelota.mover();
					laminaPelota.repaint();
					try {
						Thread.sleep(4);
					} catch (InterruptedException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}
		
				}
			}
			
		});
		laminaBotones.add(btnStart);
		this.add(laminaBotones,BorderLayout.SOUTH);
		

	}
}
//------------------------------------------------------------------------------------------------
class LaminaPelota extends JPanel{
	int posX=1;
	int posY=1;
	int radio=20;
	int velocidadX=1;
	int velocidadY=1;
	
	
	public void paint(Graphics g){
		super.paint(g);
		g.fillOval(posX, posY, radio*2, radio*2);
	}
	
	//------metodo para mover--------------------------
	public void mover(){
		
		if(posX>=(this.getWidth()-radio*2)){
			velocidadX=-1;
		}
		
		if(posY>=this.getHeight()-radio*2){
			velocidadY=-1;
		}
		
		if(posX<=this.getX()){
			velocidadX=1;
		}
		
		if(posY<=this.getY()){
			velocidadY=1;
		}
		
		posX+=velocidadX;
		posY+=velocidadY;
	}
}

Create a free my code stock.com account now.

my code stok.com is a free service, which allows you to save and manage code snippes of any kind and programming language. We provide many advantages for your daily work with code-snippets, also for your teamwork. Give it a try!

Find out more and register now

You can customize the height of iFrame-Codes as needed! You can find more infos in our API Reference for iframe Embeds.