小球练习

       今天写了一个小球反弹的练习,但是程序还有些小问题。斜率有时候改变的时候就会导致小球不反弹,比如斜率为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);
		}
	}
}


 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值