Skip to content

Instantly share code, notes, and snippets.

@firejox
Created May 23, 2014 17:38
Show Gist options
  • Save firejox/adc075d4458c92261a1d to your computer and use it in GitHub Desktop.
Save firejox/adc075d4458c92261a1d to your computer and use it in GitHub Desktop.
ce1002.a12.s101201046
package ce1002.a12.s101201046;
import java.awt.event.*;
import java.awt.*;
import javax.swing.*;
public class A12 extends KeyAdapter {
static JFrame jf;
static { //initial JFrame
jf = new JFrame("A12");
jf.getContentPane().setLayout(null);
jf.getContentPane().setPreferredSize(new Dimension(500, 500));
jf.setLocation(300, 300);
jf.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jf.setVisible(true);
jf.requestFocusInWindow();
jf.pack();
}
public static void main(String[] args) {
jf.addKeyListener(new A12()); //set keylistener
}
public void keyPressed(KeyEvent e) {
new Thread(new MovingButton()).start(); //create thread
}
}
package ce1002.a12.s101201046;
import javax.swing.*;
import static java.lang.Math.*;
public class MovingButton extends JButton implements Runnable {
private double dx, dy;
private int bounceCounter = 0;
/*** initial **/
public MovingButton() {
double r = random() * PI;
dx = cos(r) * 3.0;
dy = sin(r) * 3.0;
A12.jf.getContentPane().add(this);
this.setBounds((int)(random()*(getParent().getWidth() - 50)),
(int)(random()*(getParent().getHeight() - 50)),
50, 50);
this.setText(String.valueOf(bounceCounter));
}
//thread run
public void run() {
try {
while(true) {
Thread.sleep(10);
setLocation(getX() + (int)dx, getY() + (int)dy);
//wall collision check
if (getX() < 0 || getX() > (getParent().getWidth() - getWidth())) {
dx = -dx;
setText(String.valueOf(++bounceCounter));
}
if (getY() < 0 || getY() > (getParent().getHeight() - getHeight())) {
dy = -dy;
setText(String.valueOf(++bounceCounter));
}
}
} catch(InterruptedException e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment