我正在嘗試製作彈跳球的程序。我已經嘗試了一些條件。但我沒有得到我想要的東西。球繼續在框架的對角線方向上前後移動。問題在哪裏?我強調了這個計劃的主要邏輯。無法獲得正確的條件
下面是程序:
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