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

时间:2013-07-22 19:45:42

标签: java multithreading swing bufferstrategy

我是Java的初学者,我在扩展JPanel但不扩展canvas的类中创建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);
    }
}

1 个答案:

答案 0 :(得分:0)

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