I have a program that animates a ball in a Jpanel. I have two buttons Stop and Go. Stop stops the ball moving and go is meant for the ball to move around. In my ball class I have a boolean variable that if it is true the ball moves and if it is false the ball doesn't move. So I thought in my main class when I create the frame and put the ball class in the panel I could use the buttons to change the variable to false or true depending on the button press.
public class BallTask extends JPanel implements ActionListener{
public static boolean run = false;
public BallTask(){
this.setPreferredSize(new Dimension(width, height));
Thread gameThread = new Thread() {
public void run() {
while (run) {
.... working code
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
JFrame window = new JFrame();
window.setLayout(new BorderLayout());
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
window.add(new BallTask());
JPanel buttons = new JPanel();
JButton stop = new JButton("STOP");
stop.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
run = false;
}
});
JButton go = new JButton("GO");
go.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
run = true;
}
});
buttons.add(go);
buttons.add(stop);
window.add(buttons,BorderLayout.SOUTH);
window.pack();
window.setVisible(true);
}
});
The problem I have with the code is that the buttons don't actually change the boolean value in the BallTask class. Any ideas?