简体   繁体   English

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

[英]How to create bufferstrategy in a class which extends JPanel

I am beginner in Java and I am having difficulties creating bufferstaregy in a class which extends JPanel but not canvas. 我是Java的初学者,我在扩展JPanel而不是canvas的类中创建bufferstaregy有困难。 Can some one show how to add buffer strategy here. 有人可以在这里展示如何添加缓冲策略。 I wrote very simplified code which illustrates my problem. 我写了非常简化的代码来说明我的问题。 I move rectangle in x and y position, however I can't see smooth movement of the rectangle at high speed. 我在x和y位置移动矩形,但是我看不到高速矩形的平滑移动。 I hope that buffer strategy can solve this problem. 我希望缓冲策略可以解决这个问题。 I might be wrong. 我可能错了。 In any case what should I do here if I want to see smooth rectangle movement? 无论如何,如果我想看到平滑的矩形运动,我该怎么办? I would be very grateful for any help. 我会非常感谢任何帮助。 I am stucked at this position for a few days. 我被困在这个位置几天。

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);
    }
}

你不能真正在一个只使用该类扩展JPanel的类上创建一个BufferStrategy,最好的选项也设置为“setDoubleBuffered”,这允许缓冲区为2,但它并不能完全创建一个可访问的bufferStrategy我建议使用一个您添加到JPanel的Canvas,您可以获得bufferStrategy以及更流畅更好的受控图形

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM