Mastering Java Swing
Create a Window and Draw a Square - STEP 1
ProjectilesIn this step, we're laying the groundwork for our game by doing two simple tasks:
Create the Game Window: This will be the area where everything in the game takes place.
Draw the Player: The player is represented as a square, which we’ll display inside the window.
Here’s the code for this step:
import javax.swing.*;
import java.awt.*;
public class Projectiles extends JPanel {
private int squareX = 50, squareY = 250; // Player position
public Projectiles() {
setPreferredSize(new Dimension(500, 500)); // Set the window size
setBackground(Color.WHITE); // Set the background color
}
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
// Draw the player (the square)
g.setColor(Color.BLUE); // Set the color of the square
g.fillRect(squareX, squareY, 30, 30); // Draw the square at (50, 250)
}
public static void main(String[] args) {
JFrame frame = new JFrame("Window with Square"); // Create the window
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Close the program when the window is closed
frame.add(new Projectiles()); // Add our JPanel to the window
frame.pack(); // Adjust the window size to fit the panel
frame.setVisible(true); // Show the window
}
}Members only
Keep reading this lesson
You've reached the end of the free preview. Unlock the rest of this lesson plus 27 more lessons in Mastering Java Swing.
- Unlimited coding questions
- Unlimited access to all classroom material
- Weekly live call for questions and guidance
- 3,000 AI tutor tokens / month
- Personal SQL database (3 MB)
- Progress tracking
Cancel any time.