3

我是 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);
    }
}
4

1 回答 1

0

您不能真正在仅使用该类扩展 JPanel 的类上创建 BufferStrategy 最佳选项设置为“setDoubleBuffered” true 这允许缓冲区为 2,但它并不能完全创建可访问的 bufferStrategy 我建议使用您添加到 JPanel 的画布,这样您可以获得 bufferStrategy 以及更平滑更好的受控图形

于 2019-01-22T13:51:38.207 回答