2013-05-04 15:41:58Morris
[JAVA][作業] 做一個移動的按鈕
讓按鈕四處以彈性碰撞撞擊視窗四周,並且計數於按鈕上。
同時按鈕被點擊的時候,要隨機切換別的方向。
package ce1002.A6.s100502205;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.util.Timer;
import java.util.TimerTask;
public class A6 extends JFrame {
public JButton btn;
public final int btnSideLen = 60;
public double btnX, btnY, vx, vy;
public int crashTimes;
public A6() {
this.setTitle("A6");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(650, 750);
this.setResizable(false);
this.setLayout(null);
btnX = getWidth() / 2.0;
btnY = getHeight() / 2.0;
vx = Math.sin(1) * 5;
vy = Math.cos(1) * 5;
btn = new JButton("" + crashTimes);
btn.setBounds((int) btnX, (int) btnY, btnSideLen, btnSideLen);
btn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double theta = Math.random() * 2 * Math.PI;
vx = Math.sin(theta) * 5;
vy = Math.cos(theta) * 5;
}
});
this.add(btn);
this.setVisible(true);
Timer timer = new Timer();
timer.schedule(new RunningButton(), 1000, 20);
}
class RunningButton extends TimerTask {
public void run() {
boolean crash = false;
if (btnX + vx < 0) {
vx = -vx;
crash = true;
}
if (btnX + vx + btnSideLen >= getWidth()) {
vx = -vx;
crash = true;
}
if (btnY + vy < 0) {
vy = -vy;
crash = true;
}
if (btnY + vy + btnSideLen >= getHeight()) {
vy = -vy;
crash = true;
}
if (crash) {
crashTimes++;
btn.setText("" + crashTimes);
}
btnX += vx;
btnY += vy;
btn.setBounds((int) btnX, (int) btnY, btnSideLen, btnSideLen);
// repaint();
}
}
public static void main(String[] args) {
new A6();
}
}
上一篇:[JAVA][作業] 視窗繪圖