私は Java の初心者であり、キャンバスではなく JPanel を拡張するクラスで bufferstaregy を作成するのに苦労しています。ここにバッファ戦略を追加する方法を示すことができますか。私の問題を説明する非常に単純化されたコードを書きました。四角形を x と y の位置で移動しますが、高速で四角形の滑らかな動きが見られません。バッファ戦略がこの問題を解決できることを願っています。私は間違っているかもしれません。いずれにせよ、滑らかな長方形の動きを見たい場合は、ここで何をすればよいですか? どんな助けにもとても感謝しています。私は数日間この位置で立ち往生しています。
import javax.swing.*;
import java.awt.*;
public class simpleAnimation {
public static void main(String args[]){
Runnable animation = new moveAnimation();
Thread thread = new Thread(animation);
thread.start();
}
}
// Creates window and performs run method
class moveAnimation implements Runnable{
JFrame frame;
int x = 0;
int y = 0;
boolean running = true;
moveAnimation(){
frame = new JFrame("Simple Animation");
frame.setSize(600,600);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void run() {
while(running == true){
if(x<=500 || y<=500){
x++;
y++;
}
frame.add(new draw(x, y)); // I create new object here from different class which is below
frame.setVisible(true);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
}
}
// I use this class to draw rect on frame
class draw extends JPanel{
int x;
int y;
draw(int x, int y){
this.x=x;
this.y=y;
}
public void paintComponent(Graphics g){
Graphics2D g2 = (Graphics2D)g;
g2.setColor(Color.BLACK);
g2.fillRect(0,0,getWidth(),getHeight());
g2.setColor(Color.GREEN);
g2.fillRect(x,y,50,50);
}
}