2
私は画面上を移動するボールからなるアプレットを作っています。 ボールの最初のX座標とY座標は0に設定されていますが、楕円はこれらの点から少し離れて描画されます(画像参照)。 もう1つの問題は、アプリケーションを実行するときに、希望の幅と高さのアプレットが取得されることがありますが、それ以外のときは小さいことがあります。なぜこのようなことが起こるのか分かりません。私は以下のコード貼り付けましたJavaアプレット:塗装されたボールがハードコードされた位置に表示されません。アプレットが一定のサイズを維持しない
:
import java.applet.Applet;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.Timer;
public class StartingPoint extends Applet implements ActionListener
{
final int DELAY = 10;
final int APPLET_WIDTH = 400;
final int APPLET_HEIGHT = 300;
int x=0;
int y=0;
int ballRadius = 20;
int movementX = 10;
int movementY = 10;
private Image appletImage;
private Graphics appletGraphics;
public void init()
{
super.init();
//StartingPoint.this.setSize(APPLET_WIDTH, APPLET_HEIGHT);
}
public void start()
{
Timer animationTimer = new Timer(60, this);
animationTimer.start();
}
public void stop()
{
super.stop();
}
public void destroy()
{
super.destroy();
}
public void update(Graphics g)
{
if(appletImage == null)
{
appletImage = createImage(this.getSize().width, this.getSize().height);
appletGraphics = appletImage.getGraphics();
}
//draw applet background
appletGraphics.setColor(getBackground());
appletGraphics.fillRect(0, 0, this.getSize().width, this.getSize().height);
//draw applet foreground
appletGraphics.setColor(getForeground());
this.paint(appletGraphics);
//draw images on the applet
g.drawImage(appletImage, 0, 0, this);
}
public void paint(Graphics g)
{
super.paint(g);
this.setBackground(Color.BLUE);
g.setColor(Color.RED);
g.fillOval(this.x, this.y, ballRadius, ballRadius);
}
@Override
public void actionPerformed(ActionEvent e)
{
if((x+movementX) > (this.getWidth()-ballRadius))
{
this.x = this.getWidth()-ballRadius;
this.movementX = -movementX;
}else if(x+movementX < ballRadius)
{
this.x = ballRadius;
this.movementX = -movementX;
}
else
this.x += movementX;
if((y+movementY) > this.getHeight()-ballRadius)
{
this.y = this.getHeight()-ballRadius;
this.movementY = -movementY;
}else if(y+movementY < ballRadius)
{
this.y = ballRadius;
this.movementY = -movementY;
}
else
this.y += movementY;
this.repaint();
}
}
私はwhileループとスリープコールでアニメーションを処理することは非常に良い考えだとは思わない。 Swing Timerクラス[here](http://docs.oracle.com/javase/6/docs/api/javax/swing/Timer.html)をチェックしてください。 – broncoAbierto
このチップはありがとうございます:)なぜボールは0,0で描かれないのですか? –