今天写了一个小球反弹的练习,但是程序还有些小问题。斜率有时候改变的时候就会导致小球不反弹,比如斜率为3的时候,就不反弹 所以就先设置了几个斜率,没有随机生成。。。。一直没搞懂。。改天在说吧。。。
public class Ball extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
/**
* @param args
*/
public static void main(String[] args) {
new Ball();
}
private JPanel Panel;
private Timer mytimer;
private JLabel myLabel;
private int x, y, b;
private double a;
private boolean istrun = true;
public Ball() throws HeadlessException {
super();
this.setSize(400, 300);
this.setDefaultCloseOperation(EXIT_ON_CLOSE);
Toolkit tk = Toolkit.getDefaultToolkit();
this.setLocation((tk.getScreenSize().width - 400) / 2, (tk
.getScreenSize().height - 300) / 2);
this.getContentPane().setLayout(null);
this.getContentPane().setBackground(Color.yellow);
mypanelInit();
timerInit();
this.setVisible(true);
}
private void mypanelInit() {
Random rl=new Random();
int key=rl.nextInt(4);
switch (key) {
case 0:
a=8;
break;
case 1:
a=2;
break;
case 2:
a=10;
break;
case 3:
a=16;
break;
case 4:
a=5;
break;
default:
break;
}
b = 0;
x = 0;
y = 0;
Panel = new JPanel();
this.getContentPane().add(Panel);
Panel.setLayout(null);
Panel.setSize(310, 210);
Panel.setLocation(50, 35);
Panel.setBackground(Color.LIGHT_GRAY);
myLabel = new JLabel();
myLabel.setIcon(new ImageIcon("src\\Ball.png"));
myLabel.setForeground(Color.red);
myLabel.setBounds(x, y, 10, 10);
Panel.add(myLabel);
}
private void timerInit() {
mytimer = new Timer(100, new myListenner());
mytimer.start();
}
class myListenner implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
if (istrun) {
x+=5;
y = (int) (a * x + b);
} else {
x-=5;
y = (int) (a * x + b);
}
if (x == 300) {
istrun = false;
b = (int) (600*a+b);
a = (-1) * a;
}
if (x == 0) {
istrun = true;
a = (-1) * a;
}
if (y == 0) {
b=-b;
a = (-1) * a;
}
if (y == 200) {
b = 400-b;
a = (-1) * a;
}
myLabel.setBounds(x, y, 10, 10);
}
}
}