【问题标题】:How to create bufferstrategy in a class which extends JPanel如何在扩展 JPanel 的类中创建缓冲区策略
【发布时间】:2013-07-22 19:45:41
【问题描述】:

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

【问题讨论】:

  • Swing 组件默认是双缓冲的,那何必呢?顺便说一句,不要从 Thread 而非事件调度线程调用 GUI 方法,也不要在 EDT 上调用 sleep。如果需要,请使用基于 Swing 的 Timer
  • 还有@AndrewThompson cmets running = true 应该是running == true
  • 强烈推荐阅读Concurrency in SwingPerforming custom painting官方Swing tutorial的课程。它们涵盖了您的代码示例中的所有相关主题。
  • @nachokk 或者更简单,while (running) ;)

标签: java multithreading swing bufferstrategy


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-11
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多