我正在尝试制作弹跳球的程序。我已经尝试了一些条件。但我没有得到我想要的东西。球继续在框架的对角线方向上前后移动。问题在哪里?我强调了这个计划的主要逻辑。无法获得正确的条件
下面是程序:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
class MovingBall2D extends JPanel{
int x_Pos=0;
int y_Pos=0;
int speedX=1;
int speedY=1;
int diameter=30;
int height=30;
int frameX=500;
int frameY=500;
MovingBall2D() {
ActionListener taskPerformer = new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if(x_Pos > (frameX - diameter)) { // <------ logic starts from here
x_Pos = frameX - diameter;
speedX = -1;
}
else if(x_Pos < 0) {
x_Pos = 0;
speedX = 1;
}
else if(y_Pos > (frameY - diameter)) {
y_Pos = frameY - height;
speedY = -1;
}
else if(y_Pos < 0) {
y_Pos = 0;
speedY = 1;
}
x_Pos = x_Pos + speedX;
y_Pos = y_Pos + speedY;
repaint();
}
};
new Timer(10,taskPerformer).start(); // <------- logic ends here
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
g.setColor(Color.red);
g.fillOval(x_Pos,y_Pos,diameter,height);
}
}
class Main2D {
Main2D() {
JFrame fr=new JFrame();
MovingBall2D o = new MovingBall2D();
fr.add(o);
fr.setSize(500,500);
fr.setVisible(true);
fr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public static void main(String args[]) {
new Main2D();
}
}
编辑 -球来回移动。 为什么会发生这种情况?我期待输出shown here。 如果问题对任何人都不清楚,请编译然后运行以查看输出。
你能解释一下你所得到的吗?和你想要得到什么? – 2011-06-13 16:28:37
那么......你想要什么?您应该准确描述您所看到的(问题是什么?)以及您想要看到的内容(什么是解决方案?)。球是否熄灭?球是否弹跳,但仍然在屏幕上以某些角度反弹之前熄灭?窗户根本没有露面吗?我们不知道你想要什么样的答案。帮助我们帮助你:) – 2011-06-13 16:29:54
@猎人我正在尝试制作弹跳球的程序。我期望在这个applet中显示的输出http://www.roseindia.net/java/java-tips/45examples/40animation/40BouncingBall/bouncingball.shtml – 2011-06-13 16:30:05