class HitBallPanel extends JPanel{
private int ballX = 100;
private int ballY = 100;
private int rectX = 0;
private int rectY = 350;
public HitBallPanel(){
Timer timer = new Timer(100,new ActionListener(){
public void actionPerformed(ActionEvent e){
ballY+=10;
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_LEFT : rectX-=1;break;
case KeyEvent.VK_RIGHT : rectX+=1;break;
}
repaint();
}
});
if(ballY == rectY){
ballX = (int)(Math.random()*300);
ballY = (int)(Math.random()*300);
}
repaint();
}
});
timer.start();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.fillOval(ballX,ballY,10,10);
g.fillRect(rectX,rectY,80,10);
}
private int ballX = 100;
private int ballY = 100;
private int rectX = 0;
private int rectY = 350;
public HitBallPanel(){
Timer timer = new Timer(100,new ActionListener(){
public void actionPerformed(ActionEvent e){
ballY+=10;
addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent e){
switch(e.getKeyCode()){
case KeyEvent.VK_LEFT : rectX-=1;break;
case KeyEvent.VK_RIGHT : rectX+=1;break;
}
repaint();
}
});
if(ballY == rectY){
ballX = (int)(Math.random()*300);
ballY = (int)(Math.random()*300);
}
repaint();
}
});
timer.start();
}
protected void paintComponent(Graphics g){
super.paintComponent(g);
g.fillOval(ballX,ballY,10,10);
g.fillRect(rectX,rectY,80,10);
}
解决方案 »
- java中将byte数组写入文件的问题
- 一个需求(一般人看了也白看),大拿进来
- LinkedList 的简单的问题啊
- 学线程时碰到的问题!
- Java客户端调用Java编写WebSerivice出现特别麻烦的问题。回答的都给分~~~~小弟先谢谢各位GGJJ了~~~~~~~
- 求代码,产生不大于X的数并且X大于0,感谢。
- 在程序中如何保证只有一个connection呢?
- 我写了一个关于接口的程序,大家来讨论一下接口的作用
- JBuilder8(D版)安装好了,可是编译时总提示一些库里面的类找不到。
- 将很大的对象写入ByteArrayOutputStream中,发生OutOfMemoryError,怎样处理?
- Eclipse3.7.2可视化开发?如何实现?谢谢!
- 求助哈
弹起后ballY 的值十有八九不是10的倍数了,所以这个条件就不可能满足了
需改成 if(ballY >= rectY)
应该写成if(ballY-rectY < 10) 10是精确度, 可以改。
1.if(ballY >= rectY){
ballX = (int)(Math.random()*300);
ballY = (int)(Math.random()*300);
}
2.if(ballY == rectY){
ballX = (int)(Math.random()*300);
ballY = ((int)(Math.random() * 300) / 10) * 10;
}
if((ballX - rectX) <= 80 && ballY >= rectY)
{
ballX = (int)(Math.random()*300);
ballY = (int)(Math.random()*300);
}
这样就判断只有小球落到了的范围之内,并且ballY>=rectY才能弹起来...
这样又有新的问题了,开始的时候每次移动木板走的很慢,随着移动米板的次数增多,后面每次移动木板rectX就变化很快了我想不明白这是为什么一个这么简单的题弄这么久诶。。