私はJavaで簡単なアニメーションを作成しており、可能な限りスムーズに作成しようとしています。
各Shapeオブジェクトの*.Double内部クラスのみを使用し、Graphics2Dオブジェクトでアンチエイリアスを設定します。fill()メソッドのみを使用している限り、すべて機能しますが、draw()メソッドを使用して同じシェイプの周りに線を描画すると、これらの線のアニメーションが途切れ途切れになります(ピクセルごと)。
キャンバス上の私の長方形のそれぞれには、それ自体をペイントするためのこのメソッドがあります。20msごとに移動し、TimerとTimerListenerを使用してキャンバス全体を再描画します。
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class AnimationTest {
public static void main(String[] args) {
JFrame frm = new JFrame("Test");
frm.setBounds(200, 200, 400, 400);
frm.setResizable(false);
frm.setLocationRelativeTo(null);
AnimationCanvas a = new AnimationCanvas();
frm.add(a);
frm.setVisible(true);
a.startAnimation();
}
}
class AnimationCanvas extends JPanel {
SimpleSquare[] squares = new SimpleSquare[2];
AnimationCanvas() {
squares[0] = new SimpleSquare(50, 80, true);
squares[1] = new SimpleSquare(160, 80, false);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
for (SimpleSquare c : squares) {
c.paintSquare(g);
}
}
Timer t;
public void startAnimation() {
t = new Timer(30, new Animator());
t.start();
}
private class Animator implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
squares[0].y += 0.10;
squares[1].y += 0.10;
repaint();
}
}
}
class SimpleSquare {
double x;
double y;
Color color = Color.black;
boolean fill;
SimpleSquare(double x, double y, boolean fill) {
this.x = x;
this.y = y;
this.fill = fill;
}
void paintSquare(Graphics g) {
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
Shape s = new Rectangle.Double(x, y, 100, 100);
g.setColor(color);
((Graphics2D) g).setStroke(new BasicStroke(2));
if (fill) {
((Graphics2D) g).fill(s);
} else {
((Graphics2D) g).draw(s);
}
}
}
この問題を解決する方法はありますか?私はかなり長い間見回しました。