【发布时间】:2011-06-13 16:25:45
【问题描述】:
我正在尝试制作一个弹跳球的程序。我已经尝试了一些条件。但我没有得到我想要的。球一直在框架的对角线方向上来回移动。问题出在哪里?我已经强调了这个程序的主要逻辑。
这是程序:
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。 如果任何人不清楚问题,请编译然后运行以查看输出。
【问题讨论】:
-
你能解释一下你得到了什么吗?你想得到什么?
-
嗯...你想要什么?你应该准确地描述你所看到的(什么是问题?)以及你想看到的(什么是解决方案?)。球会离开屏幕吗?球是否会弹跳,但在以特定角度弹跳之前仍会离开屏幕?窗口根本不显示吗?我们不知道您想要什么样的答案。帮助我们帮助你:)
-
@Hunter 我正在尝试制作弹跳球的程序。我希望在此小程序roseindia.net/java/java-tips/45examples/40animation/… 中显示此处的输出
-
我想要的输出显示在这个小程序roseindia.net/java/java-tips/45examples/40animation/…
标签: java swing user-interface graphics 2d