Excersise: 15 Moving Balls | Java | Tamizhan Goals

Moving Ballls

Excersise: 15

    Create a Program for Moving Ball (Start and Stop)

Program

    
import java.awt.*;
import java.awt.event.*;
import java.applet.*;
/**/
public class MovingBalls extends Applet implements ActionListener,Runnable
{
	Thread t;
	Button btnStart,btnStop;
	int i,m,j;
	TextField txtSpeed;
	Label lblSpeed;
	public void init()
	{
		lblSpeed=new Label("Enter the Speed in ms");
		txtSpeed=new TextField(5);
		btnStart=new Button("START");
		btnStop=new Button("STOP");	
		btnStart.addActionListener(this);	
		btnStop.addActionListener(this);
		add(lblSpeed);
		add(txtSpeed);
		add(btnStart);
		add(btnStop);
	}
	public void actionPerformed(ActionEvent ae)
	{
		if((ae.getSource()==btnStart)&&(t==null))
		{
			t=new Thread(this);
			t.start();
		}
		else if((ae.getSource()==btnStop)&&(t!=null))
		{
			t.stop();
			t=null;
		}
	}
	public void run()
	{
		m=((int)(Math.random()*1000))%700;
		for(j=100;;j--)
		{
			if(j<-1000)
			{
				m=((int)(Math.random()*1000))%700;
				j=500;
			}
			repaint();
			try
			{
				Thread.sleep(Integer.parseInt(txtSpeed.getText()));
			}
			catch(Exception e)
			{
			}
		}
	}
	public void paint(Graphics g)
	{
		setBackground(Color.yellow);		
		g.setColor(Color.green);
		g.fillOval(i,j,100,100);
	}
}

Output

1 Comments

Thanks for your comments. Please be visit and given positive review on our site.

Post a Comment

Thanks for your comments. Please be visit and given positive review on our site.

Previous Post Next Post