Java,导入的图像甚至在双缓冲区(JFrame)之后闪烁

时间:2016-10-06 08:48:26

标签: java swing jframe

使用双缓冲区后,我将在使用导入的图像后显示它们,它们偶尔会闪烁。闪烁仅发生在动画GIF精灵中,而不发生在诸如程序地面之类的实心拼贴中。我认为可能的事实是,当将图像从站立位置改变到播放器的移动位置时,有一个没有图像的时刻,所以它消失但是这是不对的,因为即使不改变图像和移动,玩家也会闪烁。

程序的基本代码(压缩了很多并删除了一堆以简化阅读):

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

public class FrontHand extends JFrame implements Runnable{
    public static void main(String []args){
        // Start Main Thread
        FrontHand Thread1 = new FrontHand();
        Thread1.run();
    }

// Define Frame Properties
private FrontHand(){
    ImageImport.main();
    setSize(1600, 900);
    setResizable(false);
    setFocusable(true);
    setVisible(true);
    requestFocus();
    addKeyListener(new AL());
    addMouseListener(new ML());
    setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
}

// Frame Double Buffer
public void paint(Graphics g){
    Image dbImage = createImage(getWidth(), getHeight());
    Graphics dbg = dbImage.getGraphics();
    paintComponents(dbg);
    g.drawImage(dbImage, 0, 0, this);
}

// Call paint functions
public void paintComponents(Graphics g){
    // draw GUI
    InVar.GUI.paintIcon(this, g, 0, 0);

    // draw Ground Tiles
    for (int i = 0; i != 10; i++) {
        for (int n = 0; n != 22; n++) {
            InVar.grass_tile.paintIcon(this, g, n * 62 + 118, 106 + i * 62);
           // g.drawRect(n * 62 + 118, 106 + i * 62, 62, 62);
        }
    }

    // Draw Player
    InVar.player.paintIcon(this, g, InVar.player_x, InVar.player_y);

    repaint();
}

// player movement
private void move(){PRETEBD THERE IS ADDITION AND SUBTRACTION TO THE PLAYER X AND Y HERE}
    // check if there is any tiles left to move too and if null then redefine as non moving
    if (InVar.p_m_x_counter == 0 && InVar.p_m_y_counter == 0){
        InVar.player_moving = false;
        // change the sprite of the player to the corresponding stationary one to the current player's sprite
        if (InVar.player == InVar.player_m_up){
            InVar.player = InVar.player_s_up;
        }
        else if (InVar.player == InVar.player_m_down){
            InVar.player = InVar.player_s_down;
        }
        else if (InVar.player == InVar.player_m_left){
            InVar.player = InVar.player_s_left;
        }
        else if (InVar.player == InVar.player_m_right){
            InVar.player = InVar.player_s_right;
        }

    }
    else{
        InVar.player_moving = true;
    }
}

@Override
public void run(){
    while (InVar.game_running){
        try{
            Thread.sleep(5);
            move();
        }catch (InterruptedException e){System.out.println("Interrupted Exception Caught, ignore");}
    }
}

}

用于导入图像的代码:

    ImageIcon a_1 = new ImageIcon(FrontHand.class.getResource("/Sprites/Tiles/GrassTile1.jpg"));
    a_1.setImage(a_1.getImage());
    InVar.grass_tile = a_1;

在我使用.getScaledInstance进行动画GIF之前,这也是我认为导致闪烁却没有使用它,只是从外部改变它们的大小并没有解决闪烁的问题。

0 个答案:

没有答案