Home

Creating Graphics Using Swing

- Anshul Kashyap; August 1, 2018

Note:

This is the absolute basic way to use Swing. If you want me to go into more depth, email me at the bottom. I am not creating any external classes for any game objects such as the player, enemy, etc. This entry is just for graphical purposes and to teach you about displaying graphics, not designing a game.


Prerequisites:


Overview:

Swing is a Java graphics library that allows the user to quickly and efficiently implement and use graphics to create a desktop application. Swing is quite easy to learn as the basic concepts and ideas are all you need to know to create very intricate applications. Swing can be used for many types of applications including: Games, TextEdit softwares, Applications such as calculators, etc. The list goes on and on. The resources that swing provide the user allows them to create a vast variety of applications showing the true capabilities of Swing and its ability to create desktop applications.


Introduction:

Just like any other graphics library, Swing has special functions that allow the user to create their own custom application. To get started, let’s first import Swing and create a basic window. We can create a window by using the JFrame utility that Swing provides us. This is basically the shell of our application and the container for all the graphics we will be displaying.

          //Import statement for JFrame
          import javax.swing.JFrame; 
          public class Main{
              public static void main(String[] args){
                  //Creating the window object using the JFrame class
                  JFrame window = new JFrame();
                  //Setting the display size to 500px * 500px
                  window.setSize(500, 500);
                  //Takes String input and sets the title of the window to “Basic Application”
                  window.setTitle(“Basic Application”);
                  //This is very important. Observe that this function enables the window to actually close. Without this, after running the program, you wouldn't be able to actually close the window. You would have to manually terminate the program
                  window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 
                  //Obviously you need to set the visibility to true :)
                  window.setVisible(true);
              }
          }
                    

When I first started, I had a hard time remembering all of these functions. The only way to learn it is to keep applying it just like any other skill in the real world.


JPanel:

We have our frame, but where is our picture? In Swing, you can think of the JPanel class as the picture that you place inside of the frame. JPanel is the actual container for all the graphics and JFrame is a JPanel container. To create a JPanel, you have to create a class that inherits all the attributes of the JPanel class.

          //Import statement for JPanel
          import javax.swing.JPanel
          //Take note of the “extends” keyword. It shows that inheritance is taking place
          public class Panel extends JPanel{
              //Constructor
              public Panel(){

              }
          }
                    

Now back in our Main.java file, let’s add the JPanel. Below the window object initialization line:

          //Adds a new Panel object to the window
          window.add(new Panel());
                    

Thread:

Okay, now we need some type of loop that keep the application running until the user wants to quit it. In java, every line of code inside of the main function executes only once… just once. We don’t want that to happen to our game, so we have to create a game loop that allows the game to keep updating the frames. In swing, we use something called a thread to execute a program. A thread is basically a path that the compiler follows. To use the thread, we have to implement the Runnable class. You can get more info about the Runnable class at: https://docs.oracle.com/javase/7/docs/api/java/lang/ Runnable.html.

          public class Panel extends JPanel implements Runnable{
              //Creating Thread object
              private Thread thread;
              //Boolean value will be useful for the loop later
              private boolean isRunning;
              //The target frame rate we want the computer to run at
              private int targetFPS;
              public Panel(){
                  //Initializing thread vars
                  //Observe keyword “this” 
                  thread = new Thread(this);
                  isRunning = true;
                  targetFPS = 60;
              }
              //Initial method that comes with the Runnable class. All the updates for the graphics and rendering will sprout out of here
              public void run(){

              }
          }
                    

Loop:

Alright, we have created the JPanel, now let’s move onto the root of the application, the loop. This allows us to control frame updates, rendering, and possibly everything that is vital to the application.

          public void run(){
              //For fps purposes
              int frames = 0;
              long lastChecked = System.nanoTime();
              //The loop itself
              while(isRunning){
                  //To catch any compiler error that may occur with sleep();
                  try {
                      //To make sure that the loop runs at a steady frame rate. This is a vital component. Don’t forget this.
                      thread.sleep(1000 / FPS);
                  } catch (InterruptedException e) {
                      e.printStackTrace();
                  }
                  //Calling the render method
                  render();
                  //For fps purposes
                  frames++;
                  if(System.nanoTime() - lastChecked >= 1000000000L){
                      //Printing fps to console
                      System.out.println(“FPS: ” + frames);
                      //Resetting frame value
                      frames = 0;
                      //Updating lastChecked
                      lastChecked = System.nanoTime();
                  }
              }
          }
          //Calls this method every time the computer renders one frame
          public void render(){

          }
                    

Beginning Graphics:

Finally!!! The good part. We will now start displaying graphics to the screen. To do this, we have to create a new function in the Panel.java file. It is called “paintComponent(g)”. paintComponent has 1 parameter, a Graphics object. Using this graphics object and its functions, we will be able to display graphics onto the window.

          //New import statements at the top
          import java.awt.Graphics;
          import java.awt.Graphics2D;
                    
          ...
                    
          public void paintComponent(Graphics g){
              Graphics2D g2 = (Graphics2D) g;
              super.paintComponent(g2);
          }
                    

In this function, we will be able to display different polynomials and distinct shape using the classes that the awt library provides us.


Drawing Shapes:

Using the awt library, we can draw different shapes and interact with them as well.

          //Initial import statement
          import java.awt.Rectangle;
                    
          ...
                    
          //Creating the box object
          Rectangle box;
          //In the constructor
          public Panel(){
              thread = new Thread(this);
              isRunning = true;
              targetFPS = 60;
              //Initializing the box object 
              //Rectangle takes in the following parameters: Rectangle(int x, int y, int width, int height);
              //The origin (0, 0) is in the top left corner
              box = new Rectangle(0, 0, 100, 100);
          }
          public void paintComponent(Graphics g){
              Graphics2D g2 = (Graphics2D) g;
              super.paintComponent(g2);
              //Drawing the intial background
              g2.setColor(Color.BLACK);
              g2.fillRect(0, 0, 500, 500);
              //Setting the paint, this color will be used for drawing all objects until it is changed
              g2.setColor(Color.WHITE);
              //Filling the box, g2.draw(box) just draws the outline
              g2.fill(box);
          }
                    

Now, when you run the program, you should see a white box in the top left corner. That is the end of the entry today. If you want to know more, check out the resources below or email me at the bottom.

For more resources: https://docs.oracle.com/javase/tutorial/uiswing/