import java.awt.Graphics;
import javax.swing.JApplet;
import javax.swing.JPanel;
public class Circle extends JPanel {
int x = 75;
int y = 100;
int diameter = 50;
public void setAnimationY(int y) {
this.y = y;
}
public int getAnimationY() {
return y;
}
public int getDiameter() {
return diameter;
}
public void setDiameter(int startDiameter) {
diameter = startDiameter;
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawOval(x, y, diameter, diameter);
}
}
import java.awt.BorderLayout;
import java.awt.Graphics;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JApplet;
import javax.swing.JPanel;
import javax.swing.Timer;
public class BouncingBall extends JApplet {
private int speed = 5;
private Timer timer;
private Circle draw;
@Override
public void init() {
super.init();
setLayout(new BorderLayout());
draw = new Circle();
add(draw);
timer = new Timer(30, new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
int y = draw.getAnimationY();
int diameter = draw.getDiameter();
int roof = getHeight();
y += speed;
if (y < 0) {
y = 0;
speed *= -1;
} else if (y + diameter > roof) {
y = roof - diameter;
speed *= -1;
}
draw.setAnimationY(y);
repaint();
}
});
}
@Override
public void start() {
super.start();
timer.start();
}
@Override
public void stop() {
timer.stop();
super.stop();
}
}
我正在嘗試創建一個JApplet,其中包含一個彈跳上下的球。到目前爲止,我已經能夠讓球上下移動,但是現在我正在努力使球更加「像生活一樣」,所以我希望每次球彈起時球的高度都會減小,直到球停止。循環JApplet動畫Java
我試圖做一個while循環使用我創建的getHeight()方法的屋頂變量,但由於某種原因,當我試圖使用它,要麼球根本沒有移動或循環沒有影響在球上。
我也嘗試了一個for循環,但我遇到了與while循環一樣的問題。我相信問題是我沒有把這個for循環放在正確的位置,以使它正常工作。
在此先感謝。
請引用您對此主題的原始問題,[使用JApplet創建動畫](http://stackoverflow.com/questions/19648353/creating-an-animation-using-japplet);另外,考慮一個[混合](http://stackoverflow.com/a/12449949/230513)applet/applicaiton。 – trashgod
你的屋頂不是你的屋頂,而是你的地板。 (0,0)座標位於左上角。 – DSquare