【问题标题】:Flicking Image in Java with BufferStrategy使用 BufferStrategy 在 Java 中滑动图像
【发布时间】:2014-09-29 14:41:51
【问题描述】:

我正在尝试使用 BufferStrategy 和 Graphics2D 渲染图像。代码运行良好,但图像闪烁。在我用 Graphics2D 测试它之前,我只用 Graphics 尝试过,而且 Frame 闪烁着疯狂。这是代码:

public Main() {

    x = 0;

    Dimension size = new Dimension(sx, sy);
    setPreferredSize(size);

    frame = new JFrame();

    ImageIcon player2 = new ImageIcon("res/gfx/char.png");
    player = player2.getImage();

    addKeyListener(new AL());

    time = new Timer(5, this);
    time.start();

}

public synchronized void start() {
    running = true;
    thread = new Thread(this, "Display");
    thread.start();
}

public synchronized void stop() {
    running = false;
    try {
        thread.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

public void run() {
    while (running) {
        render();
        update();
    }
}

public void render() {
    BufferStrategy bs = getBufferStrategy();
    if (bs == null) {
        createBufferStrategy(3);
        return;
    }

    Graphics g = bs.getDrawGraphics();

    Graphics2D g2d = (Graphics2D) g;

    g2d.setColor(Color.WHITE);
    g2d.fillRect(0, 0, 800, 600);

    g2d.drawImage(player, x, 350, null);

    g.dispose();
    bs.show();
}

(对不起,我的英语不好)

【问题讨论】:

    标签: java swing timer graphics2d bufferstrategy


    【解决方案1】:

    我认为您是直接在 jframe 上绘制图像。尝试使用像 JPanel 这样的中级容器组件并在其上绘制图像并将面板添加到框架中。直接绘制会产生闪烁效果。

    【讨论】:

    • 如果我按照你说的那样做,我可以保留三重缓冲吗?
    • 目前还不清楚您实际渲染图像的方式和位置。如果你正在做一些动画,也尽量避免线程,尝试使用 javax.swing.Timer。
    • 正如您在代码中看到的,我正在使用 javax.swing.Timer,但感谢答案!
    • 你需要三重缓冲吗? JPanel 默认有一个双缓冲区。如果绝对需要,您可以使用 JPanel 制作一个非常混乱的 BufferStrategy。 . .
    猜你喜欢
    • 2012-12-01
    • 2013-10-14
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多