【问题标题】:Java Simple Graphic Loop is slowJava 简单图形循环很慢
【发布时间】:2013-07-03 13:48:07
【问题描述】:

我是 Java 图形编程的新手,但我没想到一开始我会遇到问题:

我有一个简单的循环 - 它移动并调整立方体的大小,但它非常缓慢且“不干净”。当您知道我的意思时,我可以看到像素在变化。我在这里能做些什么更好?为什么它这么慢?谢谢大家!

所以,代码如下:

package game;

import javax.swing.*;
import java.awt.*;

public class Main extends JPanel implements Runnable{

    Box b = new Box(0, 0, 20, 20);
    Thread t = new Thread(this);

    public Main(){
        JFrame f = new JFrame();
        f.setSize(800, 600);
        f.setLocationRelativeTo(null);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setLayout(null);
        f.setVisible(true);

        setBounds(0, 0, f.getWidth(), f.getHeight());
        setBackground(Color.BLUE);
        f.add(this);

        t.start();
    }

    public void paintComponent(Graphics g){
        super.paintComponent(g);
        b.paint(g);
    }

    public void run(){
        while(b.x < 100){
            b.x++;
            b.y++;
            b.width++;
            b.height++;
            repaint();
            try{Thread.sleep(10);}catch(Exception e){}
        }
    }

    public static void main(String[] args) {
        new Main();
    }

    public class Box {

        public int x;
        public int y;
        public int width;
        public int height;
        public boolean used;

        public Box(int x, int y, int width, int height){
            this.x = x;
            this.y = y;
            this.width = width;
            this.height = height;
        }

        public void paint(Graphics g){
            g.setColor(Color.GREEN);
            g.fillRect(x, y, width, height);
        }

    }

}

【问题讨论】:

  • 你需要Thread.sleep
  • 你是什么意思?..你能解释一下吗?
  • 使用Swing TimerThread 并由Thread.sleep(int) 处理,因为Thread.sleep(int) 导致EDT 锁定,顺便说一句(可能一百万次)在这里提出了类似的问题:-)
  • @trashgod OP 没有在 EDT 上休眠,所以这不是这里的问题。
  • @haraldK:谢谢,你是对的; GFP:请引用您所参考的教程。

标签: java performance swing java-2d thread-sleep


【解决方案1】:

我会使用 cmets 中提到的 Swing Timer,否则您的代码没有任何明显错误。

但是,要在屏幕上获得完美平滑的图形,您需要“垂直同步”(即,整个绘画必须在屏幕刷新之间完成)。我建议你先看看How to use BufferStrategy in Java

编辑

出于好奇,我使用上面博文中的想法做了一些实验,虽然动画变得相当流畅,但我没有在 OS X 上使用 Java 6 实现完全垂直同步。我仍然有些“撕裂”。这真是令人失望。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多