I'm trying to learn Java and Swing by making a little game (i don't need performances at the moment). I'm using Swing to manage my game window (JFrame) and to render the game scene (JPanel). I've found two ways to achieve the same result: Overloading JPanel.paintComponent and painting directly on its Graphics object. Here are the two examples (I'm importing the whole awt and swing packages to avoid errors since i'm writing this from another PC):
First method:
import javax.swing.*;
import java.awt.*;
public class Game
{
private static JFrame f;
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setContentPane(new JPanel()
{
@Override
protected void paintComponent(Graphics g)
{
super.paintComponent(g);
// I'm doing my paint operations here
}
});
f.getContentPane().setPreferredSize(new Dimension(320, 240));
f.pack();
f.setVisible(true);
});
while(true)
{
// Game logic should go here
SwingUtilities.invokeLater(() ->
{
if(f == null)
return;
f.repaint();
});
try
{
Thread.sleep(1000 / 60); // Cap FPS to 60
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
return;
}
}
}
}
Second method:
import javax.swing.*;
import java.awt.*;
public class Game
{
private static JFrame f;
public static void main(String[] args)
{
SwingUtilities.invokeLater(() ->
{
f = new JFrame("Test");
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setResizable(false);
f.setContentPane(new JPanel());
f.getContentPane().setPreferredSize(new Dimension(320, 240));
f.pack();
f.setVisible(true);
});
while(true)
{
// Game logic should go here
SwingUtilities.invokeLater(() ->
{
if(f == null)
return;
Graphics g = f.getContentPane().getGraphics();
// Paint operations ...
g.dispose();
});
try
{
Thread.sleep(1000 / 60); // Cap FPS to 60
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
return;
}
}
}
}
What's the most standard way of doing this and why? My second bonus question is: Is there a way of managing my window with Swing but drawing stuff using OpenGL?
PS: Sorry for the bad english!