I was just wondering how I could manipulate buttons in java to make a bouncing ball stop, and then start. I tried writing an if else statement with a command to start the thread, and a command to stop it. However, that did not work. Could anyone possibly help me? Here is my code:
package javaapplication1;
import java.awt.*;
import java.applet.*;
import java.applet.Applet;
import java.awt.event.*;
public class BouncingBallOriginal extends Applet implements Runnable, ActionListener
{
Thread t=new Thread(this); /* declare and initialize a new thread */
int x = 0;
int y = 0;
int countX = 0;
int countY = 0;
Button button1; //space bar
Button button2;
public void init()
{
setSize(600,350);
t.start(); /* starts the thread */
setBackground(Color.blue);
button1 = new Button("Button 1");
add(button1);
button1.addActionListener(this);
button2 = new Button("Button 2");
add(button2);
button2.addActionListener(this);
}
private void incrementX() { x += 10; }
private void decrementX() { x -= 10; }
private void incrementY() { y += 10; }
private void decrementY() { y -= 10; }
public void run()
{
try
{
for(int i = 1; i > 0; i++)
{
Thread.sleep(200);
repaint();
}
}
catch(InterruptedException e)
{
//do nothing!
}
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == button1)
{
System.out.println("Button 1 was pressed");
}
else
{
System.out.println("Button 2 was pressed");
}
}
public void paint(Graphics g)
{
g.setColor(Color.yellow);
g.fillOval(x, y, 20, 20);
if(countX< (getSize().width / 10) - 1)
{
incrementX();
countX++;
}
if(countX >= (getSize().width / 10) - 1)
{
decrementX();
countX++;
}
if(countX >= (getSize().width / 5) - 2)
{
countX=0;
}
if(countY < (getSize().height / 10) - 1)
{
incrementY();
countY++;
}
if(countY >= (getSize().height / 10) - 1)
{
decrementY();
countY++;
}
if(countY >= (getSize().height / 5) - 2)
{
countY=0;
}
}
}