Bouncing Ball with Buttons using Swing


[Up]
Launch the applet via Java Web Start.

Source Code

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class SBBall extends JApplet implements Runnable, ActionListener {
    private Thread thr;
    private JButton b1, b2;
    private int x = 20, y = 300, r = 7;
    private int vx = 5, vy = 0, a = 3;
    private double d = 0.88;
    private Boolean loop = true;
    private JPanel gp;

    public void init() {
	JPanel p = new JPanel();
	Container cnt = getContentPane();

	b1 = new JButton("Start");
	b1.addActionListener(this);
	b2 = new JButton("Stop");
	b2.addActionListener(this);
	p.add(b1); p.add(b2);
	cnt.add(p, BorderLayout.NORTH);

	gp = new JPanel() {
		public void paintComponent(Graphics g) {
		    calc();
		    g.setColor(Color.blue);
		    g.fillOval(50+x-r, 380-y+r, 2*r, 2*r);
		}
        };
	cnt.add(gp, BorderLayout.CENTER);
    }

    public void bstart() {
	if (thr == null) {
	    loop = true;
	    thr = new Thread(this);
	    thr.start();
	}
    }

    public void run() {
	while(loop) {
	    repaint();
	    try{
		Thread.sleep(50);
	    }
	    catch(InterruptedException e) { }
	}
    }

    void calc() {
	x += vx; y -= vy;
	vy += a;
	if (x > 300) {
	    x = 600-x; vx *= -1;
	}
	else if (x < 0) {
	    x *= -1; vx *= -1;
	}
	if (y < 0) {
	    y = (int)(-(double)y * d); vy = (int) (-(double) vy * d);
	}
	else if (y == 0 && vy == 0) {
	    x = 20; y = 300;
	}
    }

    public void stop() {
	if (thr != null) {
	    loop = false;
	    thr = null;
	}
    }

    public void actionPerformed(ActionEvent evt) {
	String command = evt.getActionCommand();
	if (command.equals("Start")) {
	    bstart();
	}
	else if (command.equals("Stop")) {
	    stop();
	}
    }
}

naniwa@rbt.his.u-fukui.ac.jp