使用BufferStrategy在Java中轻击Image

时间:2014-08-06 15:19:28

标签: java swing timer graphics2d bufferstrategy

我尝试使用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();
}

(抱歉我的英语不好)

1 个答案:

答案 0 :(得分:1)

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