Home > Blockchain >  Swing application can't display a gif background properly
Swing application can't display a gif background properly

Time:11-24

So I'm trying to display a GIF background to my java app but the GIF doesn't seem to display properly That's the GIF but when I'm displaying it in my app the pixels just fly everywhere and it looks nothing like the original GIF

Code:

public class PlayerPanel extends JPanel
{
    Player player ;
    Image img;
    boolean moveFlag=false;
    private HashMap<Character,Integer> keyMap=new HashMap<>();

    public PlayerPanel()
    {
        img = (new ImageIcon("assets\\space.gif")).getImage(); //background
        player = new Player(this);

        keyMap.put('w',0);
        keyMap.put('s',0);
        keyMap.put('a',0);
        keyMap.put('d',0);

        addKeyListener(new KA());
        setFocusable(true);
    }
}

    public void paintComponent(Graphics g)
    {
        super.paintComponent(g);

        g.drawImage(img,0,0,getWidth(),getHeight(),null);
    }

Main:

public class Main {

    public static void main(String[] args) throws InterruptedException {
        JFrame f=new JFrame("Asteroids Game");
        PlayerPanel playerPanel=new PlayerPanel();
        f.add(playerPanel);
        f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        f.setSize(1024,700);
        f.setResizable(true);
        f.setVisible(true);
        f.setFocusable(false);
}

CodePudding user response:

Apparently it was a size issue and the image size was kinda small anyway, I managed to fix the bug by resizing the image to a larger resolution

  • Related