In the previous tutorial, How do I get started with 2D game programming in Java?, we created our first game window and drew a simple rectangle using Java Swing.
Our first example placed everything inside a single Java class. This approach is useful when learning the basics, but as we add more features, our game will become harder to maintain.
In this tutorial, we will improve the structure of our project by separating the game window from the drawing area.
By the end of this tutorial, you will learn how to:
- Create a game window using
JFrame. - Create a drawing area using
JPanel. - Separate the game window and rendering responsibilities.
- Configure the window size, title, and close operation.
- Draw a simple player object using
Graphics2D. - Start a Swing application using the Event Dispatch Thread.
We will continue using Java 25, Java Swing, and Apache Maven.
1. Understanding the game window
Before writing the code, let’s understand the two main components we will use.
JFrame — The game window
JFrame represents the main window of our desktop application.
It provides a title bar, borders, and window controls such as minimize, maximize, and close.
In our game, the frame acts as a container for the drawing area.
JPanel — The drawing area
JPanel is a Swing component that can be used to organize other components or display custom graphics.
We will extend JPanel and override its paintComponent() method to draw our game objects.
Our application will have three classes:
| Class | Responsibility |
|---|---|
Game |
Starts the application |
GameWindow |
Creates and configures the main window |
GamePanel |
Draws the game content |
This separation makes our code easier to understand and extend.
Later, we can add classes for player movement, keyboard input, game objects, and collision detection without putting everything inside a single class.
2. Creating the Maven project
Create a Maven project named java-2d-game.
We will organize the project using the following structure:
java-2d-game/
├── pom.xml
└── src/
└── main/
└── java/
└── org/
└── kodejava/
└── game/
├── Game.java
├── GameWindow.java
└── GamePanel.java
All three classes belong to the org.kodejava.game package.
If you are continuing from Week 01, replace the previous Game.java implementation and add the two new classes.
3. Creating the GamePanel class
Let’s start with the drawing area.
Create a file named GamePanel.java:
package org.kodejava.game;
import javax.swing.JPanel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
public class GamePanel extends JPanel {
public static final int GAME_WIDTH = 800;
public static final int GAME_HEIGHT = 600;
public GamePanel() {
setPreferredSize(new Dimension(
GAME_WIDTH, GAME_HEIGHT));
setBackground(new Color(15, 23, 42));
setDoubleBuffered(true);
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
try {
g2d.setRenderingHint(
RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
drawWelcomeMessage(g2d);
drawPlayer(g2d);
} finally {
g2d.dispose();
}
}
private void drawWelcomeMessage(Graphics2D g2d) {
g2d.setColor(Color.WHITE);
g2d.setFont(new Font(
Font.SANS_SERIF, Font.BOLD, 24));
String message = "Welcome to Java 2D Game!";
int textWidth = g2d.getFontMetrics()
.stringWidth(message);
int x = (GAME_WIDTH - textWidth) / 2;
int y = 150;
g2d.drawString(message, x, y);
}
private void drawPlayer(Graphics2D g2d) {
int playerSize = 50;
int x = (GAME_WIDTH - playerSize) / 2;
int y = (GAME_HEIGHT - playerSize) / 2;
g2d.setColor(new Color(96, 165, 250));
g2d.fillRect(x, y, playerSize, playerSize);
}
}
Understanding setPreferredSize()
The following code defines the preferred size of our game panel:
setPreferredSize(new Dimension(
GAME_WIDTH, GAME_HEIGHT));
We use an 800 × 600 pixel drawing area.
Notice that this defines the size of the game panel, not necessarily the entire desktop window.
The outer window also includes decorations such as the title bar and borders.
Understanding paintComponent()
The paintComponent() method is responsible for drawing the content of our panel.
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D) g.create();
try {
drawWelcomeMessage(g2d);
drawPlayer(g2d);
} finally {
g2d.dispose();
}
}
The Graphics object represents the drawing context supplied by Swing.
We create a separate graphics context using g.create() so that changes to rendering settings do not affect the original context.
Calling dispose() releases the resources associated with our copy.
Important: We must not call dispose() on the original Graphics object provided by Swing.
Why do we call super.paintComponent()?
The following statement should usually be the first operation in our overridden painting method:
super.paintComponent(g);
It allows Swing to perform the standard painting behavior for the component.
Since our panel is opaque and has a background color, this also allows Swing to clear the drawing area before we render our objects.
What is double buffering?
Double buffering is a technique that helps reduce flickering while drawing graphics.
Instead of exposing partially drawn frames directly to the screen, the drawing operations can be performed using an offscreen buffer.
The completed image is then displayed.
In our example, we call:
setDoubleBuffered(true);
Swing already uses double buffering for normal painting in common configurations, so this call makes our intention explicit.
We do not need to create a separate image buffer manually.
Later in the series, we will learn more about smooth animation and efficient rendering.
4. Creating the GameWindow class
Now we need a class that creates and configures the main window.
Create GameWindow.java:
package org.kodejava.game;
import javax.swing.JFrame;
public class GameWindow extends JFrame {
public GameWindow() {
setTitle("KodeJava 2D Game");
setDefaultCloseOperation(
JFrame.EXIT_ON_CLOSE);
setContentPane(new GamePanel());
pack();
setLocationRelativeTo(null);
setResizable(false);
setVisible(true);
}
}
This class extends JFrame, so it inherits the functionality of a Swing window.
Let’s examine its configuration.
Setting the window title
setTitle("KodeJava 2D Game");
This determines the text displayed in the window’s title bar.
Configuring the close operation
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
This tells Swing to exit the application when the user closes the window.
For our simple standalone game, this behavior is appropriate.
Adding the GamePanel
setContentPane(new GamePanel());
This places our custom game panel inside the frame as its content pane.
The GameWindow class does not need to know how the panel draws its contents.
Its responsibility is to manage the window.
Using pack()
pack();
The pack() method sizes the frame according to the preferred sizes of its contained components.
Because our GamePanel requests an 800 × 600 drawing area, pack() calculates a suitable frame size that also accounts for the window’s decorations.
This is generally better than using setSize(800, 600) when we want the actual game area to have a specific size.
Centering the game window
setLocationRelativeTo(null);
This positions the window in the center of the screen.
Preventing window resizing
setResizable(false);
For now, we will use a fixed-size window.
This makes it easier to understand coordinates and object positions.
We can introduce resizable windows and scaling after learning more about rendering.
5. Creating the Game class
Finally, create the application’s entry point.
Create Game.java:
package org.kodejava.game;
import javax.swing.SwingUtilities;
public class Game {
public static void main(String[] args) {
SwingUtilities.invokeLater(GameWindow::new);
}
}
This is now a very small class.
Its only responsibility is to start our application.
Why use SwingUtilities.invokeLater()?
Swing applications use the Event Dispatch Thread (EDT) to process events and interact with GUI components.
The following code schedules creation of our window on the EDT:
SwingUtilities.invokeLater(GameWindow::new);
This is equivalent to:
SwingUtilities.invokeLater(() -> {
new GameWindow();
});
A constructor reference is simply a more concise way to express the same operation.
Creating and updating Swing components on the EDT helps avoid threading problems.
When we introduce a game loop, we will also learn why long-running calculations should not block this thread.
6. Running the game
We now have three Java classes:
Game.javaGameWindow.javaGamePanel.java
Compile the project:
mvn clean compile
Then run the application from your IDE.
You can also execute it from the command line:
java -cp target/classes org.kodejava.game.Game
If everything works correctly, a window titled KodeJava 2D Game will appear.

Inside the window, you should see:
- A dark background.
- A white welcome message.
- A blue square positioned in the center of the drawing area.
The blue square represents our player.
It does not move yet, but our project now has a better structure for future development.
7. Understanding the rendering coordinates
Java 2D uses a coordinate system where the origin (0, 0) is located at the upper-left corner of the component.
The horizontal coordinate increases toward the right, and the vertical coordinate increases downward.
For example:
g2d.fillRect(100, 150, 50, 50);
This draws a rectangle with its top-left corner at (100, 150).
Its width and height are both 50 pixels.
In our drawPlayer() method, we use a simple calculation to position the player in the center:
int playerSize = 50;
int x = (GAME_WIDTH - playerSize) / 2;
int y = (GAME_HEIGHT - playerSize) / 2;
For an 800 × 600 drawing area and a 50 × 50 player, the calculated position is:
x = (800 - 50) / 2 = 375
y = (600 - 50) / 2 = 275
This places the rectangle’s top-left corner at (375, 275).
Its center is therefore at (400, 300), which is the center of our game area.
We will explore coordinates in more detail in Week 04.
8. Why separate GameWindow and GamePanel?
You might wonder why we need several classes when the previous example worked with only one.
The main reason is separation of responsibilities.
GameWindow handles the desktop window, while GamePanel handles the drawing area.
This separation becomes more valuable as we develop larger games.
For example, later we can extend our project with additional classes:
org.kodejava.game
├── Game.java
├── GameWindow.java
├── GamePanel.java
├── Player.java
├── Enemy.java
└── GameLoop.java
Each class will have a specific responsibility.
This approach makes our code easier to read, test, maintain, and reuse.
For a simple example, three classes may seem unnecessary. However, we are preparing a foundation for projects that will eventually include movement, animation, collision detection, and game logic.
9. Try it yourself
Before moving to the next tutorial, try these exercises.
Exercise 1 — Change the game resolution
Modify the dimensions in GamePanel:
public static final int GAME_WIDTH = 1024;
public static final int GAME_HEIGHT = 768;
Run the application again.
Notice how pack() automatically adjusts the window to accommodate the new preferred size.
Exercise 2 — Change the background color
Replace:
setBackground(new Color(15, 23, 42));
with:
setBackground(Color.DARK_GRAY);
Exercise 3 — Draw another object
Add the following code inside drawPlayer():
g2d.setColor(Color.YELLOW);
g2d.fillOval(100, 100, 40, 40);
Now the game displays both a square and a circle.
Exercise 4 — Allow window resizing
Change:
setResizable(false);
to:
setResizable(true);
Try resizing the window.
Notice that our player position is still calculated using the fixed values GAME_WIDTH and GAME_HEIGHT.
This means the player will not automatically remain centered when the window becomes larger.
As an additional challenge, try using getWidth() and getHeight() from GamePanel when calculating the player position.
10. Summary
In this tutorial, we improved the structure of our Java 2D game project.
We learned how to:
- Create a main game window using
JFrame. - Create a custom drawing panel using
JPanel. - Separate window management from rendering.
- Configure window dimensions and positioning.
- Draw text and objects using
Graphics2D. - Start Swing components on the Event Dispatch Thread.
- Understand the basic coordinate system used for drawing.
Our game is still simple, but we now have a foundation that can grow into a complete 2D game.
In the next tutorial, How do I draw 2D shapes using Graphics2D?, we will learn how to draw lines, rectangles, circles, and other shapes, as well as how to use colors and rendering settings.
Maven Dependencies
Java Swing and Java 2D are included in the standard Java Development Kit as part of the java.desktop module.
We do not need any external libraries for this tutorial.
Here is the complete pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.kodejava</groupId>
<artifactId>java-2d-game</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<maven.compiler.release>25</maven.compiler.release>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
</plugin>
</plugins>
</build>
</project>
Required Maven dependencies: None.
Build plugin: org.apache.maven.plugins:maven-compiler-plugin:3.14.1

