I've made a bouncing ball in Java, but now I have to add "start" and "stop" buttons to the animation, but I'm not really sure how to go about that. This is what I have so far:
import java.awt.Color;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
//import javax.swing.JFrame;
//import javax.swing.JPanel;
//import javax.swing.Timer;
/**
*
*
*/
public class BouncingBall extends JPanel implements ActionListener {
Timer tm = new Timer(5,this);
int x = 0, velX = 1;
int y = 0, velY = 1;
public void paintComponent(Graphics g)
{
super.paintComponent(g);
g.setColor(Color.yellow);
g.fillOval(x, y, 50, 50);
tm.start();
}
public void actionPerformed(ActionEvent E)
{
if(x < 0 || x > 550)
velX = -velX;
if (y < 0 || y > 280)
velY = -velY;
x = x + velX;
y = y + velY;
repaint();
}
public static void main(String[] args) {
BouncingBall s = new BouncingBall();
JFrame jf = new JFrame();
jf.setTitle("Bouncing Ball");
jf.setSize(600,350);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
}
}
Any ideas on how I should implement the start/stop buttons?
Thank you in advance
UPDATE: I did the following, but I'm getting an error because of this line: start.addActionListener(this); It says "non static variable this cannot be referenced from a static context"
public void actionPerformed(ActionEvent E)
{
if (E.getActionCommand().equals("Start")){
if(x < 0 || x > 550)
velX = -velX;
if (y < 0 || y > 280)
velY = -velY;
x = x + velX;
y = y + velY;
repaint();
}
else
{}
}
public static void main(String[] args) {
BouncingBall s = new BouncingBall();
JFrame jf = new JFrame();
JPanel jp = new JPanel();
JButton start = new JButton("Start");
start.addActionListener(this);
jp.add(start);
jf.add(jp,BorderLayout.SOUTH);
jf.setTitle("Bouncing Ball");
jf.setSize(600,350);
jf.setVisible(true);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.add(s);
}
}
Can anyone tell me what I'm doing incorrectly? The duplicate question didn't help me a lot.