0

I am creating a 2D scroller game in Java. I do have experience with making games on the web using javascript, html, css and node.js, so I understand that nearly all games have a main loop updating everything. The problem is, I can't think of a way to implement a game loop into my code. Here is my code:

import javax.swing.*;

public class Main {
    public static boolean isRunning = true;
    
    public static void main(String[] args) throws InterruptedException {
        JFrame frame = new JFrame("Oxygen - Version 1.0");
        JPanel panel = new Panel();
        
        frame.setSize(1000, 500);
        frame.setResizable(false);
        frame.add(panel);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
import java.awt.*;

import javax.swing.*;

public class Panel extends JPanel {
    public void paint(Graphics graphics) {
        this.setBackground(Color.BLACK);
        graphics.setColor(Color.BLUE);
        graphics.fillRect(0, 0, 100, 100);
    }
}

This code works fine, but where would the game loop be in this code and how often would it run?

luk2302
  • 55,258
  • 23
  • 97
  • 137
MisterHazza
  • 188
  • 1
  • 10
  • If you have nothing dynamic happening, no rendering, no physics, no timed game logic, etc. then there is no need / place for a game loop. – luk2302 Aug 06 '20 at 08:21
  • Ok good point, so lets say for example if I wanted to move the sqaure on the screen from the left to the right, where would the game loop be? – MisterHazza Aug 06 '20 at 08:25
  • I think swing is not the best thing to use in this case. You cant make a loop in the ui thread. and then its easier to do it with events. But there is one example for animating in swing https://stackoverflow.com/questions/21247776/java-swing-how-to-smoothly-animate-move-component – Paxmees Aug 06 '20 at 08:27
  • Thanks for your comment! If I don't use swing, then how would I draw images and shapes onto the JPanel? – MisterHazza Aug 06 '20 at 08:42
  • 1
    JPanel is part of swing. I would recommend to to use a game library. If you still what to use swing then you need to create separate thread to update game objects (it can be just an array) then call repaint and then sleep for a while. – Paxmees Aug 06 '20 at 09:24
  • oh i found something https://stackoverflow.com/a/31226312/640180 – Paxmees Aug 06 '20 at 09:27
  • Here's a simple animation that answered a different question. https://stackoverflow.com/questions/61974240/moving-of-an-object/61978945#61978945 – Gilbert Le Blanc Aug 06 '20 at 10:42

1 Answers1

-1

implement a while loop in your main object which will iterate indefinitely until you specify to exit. You game objects would then be updated within the loop