Step 1

Opening the Graphics Intro project


In this project, we will learn the basics of how to create a graphical Java program by learning how to create our own drawings that can appear on a window that we create.

Let’s start by opening up the new project. In the top left corner, click “File->Open” and open up the “GraphicsIntro” project.

If it does not open automatically, open up the “Main” file. You will see the code as shown here.

Right now our “Main” file has a few imports that are used for adding graphics. We can also see that it extends/inherits from “JPanel.” A “JPanel” is essentially Java’s version of a section of a window. Since we are making a graphical program, we need to do this for our program to appear and behave within a window.


Creating our first window


Now let’s go ahead and code our very first window! Complete the code as shown here to do so.

The first thing we do is create something called a “JFrame.” A “JFrame” is basically Java’s version of a window. We need this is we want anything to appear at all! The text inside the constructor is its title, feel free to customize this!

Next, we create a new instance of the “Main” class. We do this because Main extends from “JPanel,” so we are basically making a “JPanel” that we can put inside the “JFrame.”

We then add main into the “JFrame.” After which, we set the size of our new window (in pixels), we tell it to be visible, and we tell it to exit the program when we close it.

Once you’ve completed this code, go ahead and run it. If coded successfully, you should see a blank window as shown here. Congrats! You’ve made your very first window in Java!


Prepping the window for drawing


Before we move on, there’s one last bit of code we need to complete. Add the code as shown here.

This code will make sure our window always updates itself when it needs to draw. If we didn’t put this code, our window wouldn’t update and show any of the things that we’ll be coding.

The “thread.sleep” adds a 10 millisecond delay before the next repaint/update, this helps increase performance.