如何在扩展JPanel的类中创建BufferStrategy

3
我是Java的初学者,我在一个扩展JPanel而不是Canvas类的类中创建bufferstrategy遇到了困难。能否有人展示如何在这里添加buffer strategy。
我编写了非常简化的代码来说明我的问题。我将矩形移动到x和y位置,但是当速度较高时,我看不到矩形的平滑移动。我希望buffer strategy可以解决这个问题。我可能错了。无论如何,如果我想看到平滑的矩形移动,我应该在这里做什么?我会非常感激任何帮助。我已经卡在这个位置几天了。
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
Swing组件默认使用双缓冲,那还有什么问题呢?顺便提一下,不要在除事件分派线程(Event Dispatch Thread)之外的“线程”中调用GUI方法,也不要在EDT上使用“sleep”。如果需要,可以使用基于Swing的计时器(Timer)来处理。 - Andrew Thompson
2
同时,@AndrewThompson的评论中,“running = true”应该改为“running == true”。 - nachokk
3
强烈建议阅读官方Swing教程中的并发处理章节自定义绘制章节,它们涵盖了你代码示例中的所有相关主题。 - linski
2
@nachokk 或者更简单点,while (running) ;) - Andrew Thompson
1个回答

0
你不能仅使用继承JPanel的类创建BufferStrategy,最好的选择是将“setDoubleBuffered”设置为true,这样可以使用2个缓冲区,但它并不完全创建一个可访问的bufferStrategy。我建议使用一个Canvas,将其添加到JPanel中,这样你就可以获得bufferStrategy以及更加平滑、更好控制的图形。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接