【发布时间】:2013-10-29 02:00:18
【问题描述】:
我正在开发一个使用 JApplet 的 Java 程序,它可以让球上下弹跳。我能够将形状绘制到 JApplet 和类似的东西上。我似乎无法让它移动。我对此进行了研究,发现我需要创建一个方法来暂停形状,然后从 JApplet 中清除它,更改坐标,然后在新区域中重新绘制形状,但由于某种原因,它对我不起作用。
提前感谢您的帮助。
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class Circle extends JApplet {
int x=100;
int y=100;
int diameter=50;
public void paint(Graphics g) {
int xResize=500;
int yResize=500;
super.paint(g);
resize(xResize,yResize);
g.drawOval(x, y, diameter, diameter);
}
public Circle (int startX, int startY,int startDiameter) {
this.x=startX;
this.y=startY;
this.diameter=startDiameter;
}
public int getX() {
return x;
}
public void setX(int startX){
x=startX;
}
public int getY() {
return y;
}
public void setY(int startY){
y=startY;
}
public int getDiameter() {
return diameter;
}
public void setDiameter(int startDiameter){
diameter=startDiameter;
}
while (ball.getY() + ballDiameter < windowHeight) {
g.clearRect(x-1,100,20,20);
g.fillOval(x,100,20,20);
try
{
Thread.sleep(70);
}
catch(Exception e)
{
}
pause.wait(0.05);
//g.clearRect(0,0,windowWidth,windowHeight);
g.clearRect(x-1,100,20,20);
g.fillOval(x,100,20,20);
try
{
Thread.sleep(70);
}
catch(Exception e)
{
}
ball.setY( ball.getY()+spacer);
}
while (ball.getY() + ballDiameter > 0) {
g.clearRect(x-1,100,20,20);
g.fillOval(x,100,20,20);
try
{
Thread.sleep(70);
}
catch(Exception e)
{
}
pause.wait(0.05);
//g.clearRect(0,0, windowWidth, windowHeight);
ball.setY(ball.getY()-spacer);
}
弹跳球类:
import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JApplet;
public class BouncingBall extends JApplet {
public void paint(Graphics g) {
super.paint(g);
final int x = 0;
int y = 0;
final int diameter = 15;
final int spacer = 5;
int windowWidth = getWidth();
int windowHeight = getHeight();
Circle ball = new Circle(x, y, diameter);
Pause pause = new Pause();
int ballDiameter = ball.getDiameter();
int roof = getHeight();
【问题讨论】:
-
您可以发布您尝试过的内容吗?您可能已经冻结了
EDT。无论哪种方式,您为什么要为此使用 Swing?对于动画等,有很多更好的库。例如,JavaFX可以更轻松地完成此操作,并且使用起来相对简单。 -
是的,我会的。目前它不起作用,因为我已经尝试了很多东西并且刚刚将某些代码更改为 cmets 以查看它们如何影响代码。
-
我正在尝试对其进行格式化,以便将其放入我的问题中。这就是为什么它需要一段时间。
-
问题在发布后最明显,下次您可能需要在发布问题之前准备代码。问题也可以通过标签找到,因此优先考虑最相关的问题(例如“swing”而不是“init”),我已经编辑了 btw
-
是的,格式化代码总是一场噩梦。
标签: java swing animation repaint japplet