import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
import javax.swing.JButton;
import javax.swing.JFrame;
public class BallTest {
public static void main(String[] args) {
Ball1 ball = new Ball1();
ball.init();
}
}
class Ball1 {
private JFrame fTable;
// 桌面大小
private final int TABLE_WIDTH = 300;
private final int TABLE_HEIGHT = 400;
// 球拍的垂直位置
private final int BALL_START_X = 50;
private final int BALL_START_Y = 50;
// 球大小
private final int BALL_SIZE = 30;
// 小球纵向运行速度
private int xSpeed = 3;
private int ySpeed = 5;
// 小球初始方向
private int xDirection = 1;
private int yDirection = 1;
private Timer timer;
public void init() {
// 设置窗体大小
fTable = new JFrame("小球碰撞");
fTable.setSize(TABLE_WIDTH, TABLE_HEIGHT);
// 创建按钮对象
JButton b = new JButton();
b.setSize(BALL_SIZE, BALL_SIZE);
b.setLocation(BALL_START_X, BALL_START_Y);
// 按钮点击事件
b.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
System.out.println("点击按钮");
if(timer.isRunning()) {
timer.stop();
}else {
timer.start();
}
}
});
// Timer事件
ActionListener taskPerformer = new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
}
};
timer = new Timer(50, taskPerformer);
// 采用了null布局
fTable.setLayout(null);
// 把按钮添加到窗体上
fTable.add(b);
// 设置窗体可见
fTable.setVisible(true);
}
}