0

sorry if my title is worded strangely. I couldn't think of an alternative way. Here's my code, and then I'll try and explain my problem.

    Image dbImage;
    public static Graphics dbg;
    public boolean hasDone = true;

    @Override
    public void paint(Graphics g) {
        int xDrawPos = 0;
        int yDrawPos = 32;

        dbImage = createImage(getWidth(), getHeight());
        dbg = dbImage.getGraphics();
        paintComponent(dbg);
        g.drawImage(dbImage, xPos, yPos, 364, 488, null);
        if(hasDone) {
            for(int i = 0; i < 25; i ++) {
                for(int x = 0; x < 25; x ++) {
                    g.drawImage(map.getSpritesheet().grabSprite(0, 0, 16, 16), xDrawPos, yDrawPos, 128, 128, null);
                    xDrawPos = xDrawPos + 128;
                }
                yDrawPos = yDrawPos + 128;
                System.out.println(yDrawPos);
            }
            hasDone = true;
        }
    }

This is my paint method. I'm trying to make a 2D game. This method calls paintComponent which calls repaint(), so it's an infinite loop. Here's the problem: dbImage is my player, and needs to be repainted constantly as it moves. However, I'm also trying to draw a tilemap inside those two for loops, but constantly repainting all the tiles causes tremendous lag. I tried using a boolean to only paint them once, but then they were wiped in the next repaint(). I need to somehow paint my tiles once and still be able to update my player, but I can't figure it out.

Any help is greatly appreciated.

  • Create an image with all tiles painted one into it, and use that image in your paint. Also do create images each time paint is called! That is too much time-consuming, create that image once and then use it as needed. – Jean-Baptiste Yunès Apr 13 '18 at 06:13
  • 1
    You cannot create your game without to understand how Swing works. [Here](https://stackoverflow.com/questions/21142686/making-a-robust-resizable-swing-chess-gui) is an example how to draw chessboard. When you can completly understand the solution, you can try to start implementing your own game. If not - you should start to learn the Swing basics. – Sergiy Medvynskyy Apr 13 '18 at 06:38
  • `This method calls paintComponent which calls repaint(),` - you should never call paintCompnent() directly and paintCompnent() should never call repaint(). For animation use a Swing Timer. When the Timer fires you invoke repaint() on the component you want to repaint. `I'm also trying to draw a tilemap inside those two for loops,` - paint the tiles to a BufferedImage and then just repaint the image. – camickr Apr 13 '18 at 15:19
  • Thank you Jean-Baptiste Yunes and Camickr, your solutions worked great for me. I appreciate your time. – Moist Von Lipvig Apr 14 '18 at 07:34

0 Answers0