ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel
  • »
  • Technology»
  • Computers & Software»
  • Computer Science & Programming»
  • Programming Languages

Programming Basic 2D Shapes in Java Using Graphics and JFrame Classes

Updated on May 5, 2016

Introduction to Java Shapes

Programming shapes in Java is like any other language. All you need to know is what classes you need to call and how to draw the shapes to the screen. Once you know how to set up the classes and how to render the shapes to the screen, then you can create your own template that you can use later within other programs that you create.

In this article, I will show how to make calls to the “Graphics,” class that will allow you to call basic 2D shapes that can be drawn to a window. Secondly, I will show you how to make a call to the “JFrame,” class that allows for you to create a regular window to draw you shapes to the screen. Finally, our program is going to use the “Canvas,” extension which allows for us to use the paint function to make it easier to draw the shapes to the screen.

To create this program I am using NetBeans version 7.2.1 which is a free download. If you want to copy and paste the code without typing it then doing so with NetBeans 7.0 and later would be better due to possible compatibility issues. However, this program should also work for the Eclipse IDE. Just remember that when you create this new project, just create it as a regular JAVA application and give it the class name “Drawing Canvas.”

A Little Info about the Graphics, Canvas, and JFrame Classes.

Before I show you the initial code, I wanted to explain the two main classes we will be using to create our shapes. Plus, I wanted to touch on the Canvas extension I will be using to have access to the “paint” function.

First, we will tell our program to extend the Canvas class. As stated above, this will allow us to have access to the “paint” function (in which we will override). This function is where we will do all of our drawings prior to passing the shapes to the JFrame function.

Next, there is the Graphics class that we will need to help draw our shapes. The Graphics class can be added to any program using the import statement, ‘import java.awt.*”. The Graphics class contains many of the drawing functions to draw basic shapes like circles, lines, and squares (rectangles).

Finally, there is the JFrame class that allows the programmer to create a window where the drawings will be rendered. In fact, when we call this class, we will also pass it our own created class with its Canvas extension so the program will know to use the JFrame window to draw the shapes.

Program Template: The Basic Class

The following code is the basic template we will use for this article:

Initial Code Template

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

So, let me explain the above code to help you understand better what you’re looking at. The two imports are needed to give you access to the Graphics and JFrame classes. Remember that these two classes will allow your program to make calls to the Graphics and JFrame functions to help create the shapes and the window to render those shapes respectively.

Next you will see the program class “Drawing Canvas”. JAVA is class driven, so when you create a new project and give it a class name, the IDE creates a template class in this case the class “Drawing Canvas. Also, you may see that this class extends the “Canvas, “class. By giving your main class this extension, you now can access the Canvas class “paint,” function.

The next item you may notice is what programmers call a constructor function. Constructor functions allow you to initialize any internal private variables or functions within your class. However, in this case, there is nothing to initialize. So, this function is not really necessary for this tutorial, however, I always add a constructor to all of my classes in case I need them in later programs.

The next function is the “paint,” function (which is why we need the Canvas extension). It takes in the Graphics class as a parameter. This is the function we will use to create our shapes we want to render prior to creating the window where the shapes will be drawn.

Finally, we have the main function which actually runs the program. We create a new Graphic Canvas and we create our JFrame object to create our window. Finally, we pass the canvas object through JFrame getContentPane() function so that the window created by JFrame knows to draw our shapes.

Now for the shapes:

Remember the function “paint”? Well now we are going to use the Graphics class and the Canvas extension to draw the following shapes:

Draw a Line

To draw a line we are going to use the following two functions:

graphics.setColor()

graphics.drawLine()

As it pertains to setColor() we are going to pass it the color black (i.e. graphics.setColor(Color.BLACK)

And for drawLine () we will set the initial coordinates within the window to start drawing and the coordinates to end the drawing. The following is the full code when you add these functions to the paint function:

Adding Code to Draw A Line

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        //Drawing a Line
        graphics.setColor(Color.BLACK);
        graphics.drawLine(100, 100, 340, 380);    
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

When you run the above code, you get the following window:

Figure 1: Draw Line

Drawing a Rectangle:

Next I will show you how to code and draw a rectangle. We will use only one function at this time and that function will be graphics.drawRect(10,10,100,100). We are not going to worry about the color now; I just wanted to show you the code to draw it. The following is the code:

Drawing a Rectangle

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        
        //Drawing a Rectangle
        graphics.drawRect(10, 10, 100, 100);
        
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

Here is how it will look when you run the program:

Figure 2: Draw Rectangle

Now, if you want to change the border color of the rectangle, you just make another call to graphics.setColor(). In this case, I decided to change the border to red. Here is the code:

Draw a Red Rectangle

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        
        //Changing Rectangle Border Color
        graphics.setColor(Color.RED);
        graphics.drawRect(10, 10, 100, 100);
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

And here is what it looks like when you run the program:

Figure 3: Red Rectangle

We can also make a call to fill the rectangle with a color. The function to do this is graphics.fillRect(). In this case, I decided to fill the rectangle with the color yellow. Here is the code:

Draw a Filled Rectangle

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        
        //Filled Rect with a Color
        graphics.setColor(Color.YELLOW);
        graphics.fillRect(10, 10, 100, 100);
        graphics.setColor(Color.RED);
        graphics.drawRect(10, 10, 100, 100);
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

Here is what it looks like when you run the code:

Figure 4: Filled Rectangle

Circles (OVALS)

You can also create circles (AKA Ovals) with the “Graphics” class with different colors for the border and fills. To do this, you just make calls by using a combination of the functions setColor(), fillOval(), and drawOval(). The following code creates a circle and gives it a red border with a yellow background.

Draw a filled Circle

/* Drawing Program that allows you to draw some shapes
 */
package drawingcanvas;

/**
 *
 * @author Binkster
 * version 1
 */
import java.awt.*;
import javax.swing.*;

public class DrawingCanvas extends Canvas {

    /**
     * @param args the command line arguments
     */
    
    //constructor
    public DrawingCanvas(){
        
    }
    //Set up a function to draw the shapes
    @Override
    public void paint (Graphics graphics){
        //Draw Circle with a Color for border and fill
        graphics.setColor(Color.YELLOW);
        graphics.fillOval(50, 50, 100, 100);
        graphics.setColor(Color.RED);
        graphics.drawOval(50, 50, 100, 100);
    }
    public static void main(String[] args) {
        // Sets up the drawing canvas
        DrawingCanvas canvas = new DrawingCanvas();
        //Create new Window
        JFrame frame = new JFrame();
        //Set Window Size
        frame.setSize(500, 500);
        //Make Sure Program Ends when Window Exit Button is Clicked
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //Draw to Canvas
        frame.getContentPane().add(canvas);
        //Show Window
        frame.setVisible(true);
    }
}

This is what you get when you run the program:

Figure 5: Filled Oval

Conclusion:

So, the above article gives you a general idea on how to create basic 2D shapes in Java. The above is also a good template for code reuse in case you need to draw a shape in your future projects.

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      behlool ansari 4 years ago

      Thanks :-P

    • Binkster profile image
      Author

      Binkster 4 years ago

      Not yet. But I will look into it. Actually that is a good idea for my next research. Thank you Roy..Sorry to get to your post late.

    • profile image

      Roy 4 years ago

      Nice peace of job, very helpful to implement in my programs. Do you have also this kind of work for translating-rotating a drwaing?

    working

    This website uses cookies

    As a user in the EEA, your approval is needed on a few things. To provide a better website experience, hubpages.com uses cookies (and other similar technologies) and may collect, process, and share personal data. Please choose which areas of our service you consent to our doing so.

    For more information on managing or withdrawing consents and how we handle data, visit our Privacy Policy at: "https://hubpages.com/privacy-policy#gdpr"

    Show Details
    Necessary
    HubPages Device IDThis is used to identify particular browsers or devices when the access the service, and is used for security reasons.
    LoginThis is necessary to sign in to the HubPages Service.
    Google RecaptchaThis is used to prevent bots and spam. (Privacy Policy)
    AkismetThis is used to detect comment spam. (Privacy Policy)
    HubPages Google AnalyticsThis is used to provide data on traffic to our website, all personally identifyable data is anonymized. (Privacy Policy)
    HubPages Traffic PixelThis is used to collect data on traffic to articles and other pages on our site. Unless you are signed in to a HubPages account, all personally identifiable information is anonymized.
    Amazon Web ServicesThis is a cloud services platform that we used to host our service. (Privacy Policy)
    CloudflareThis is a cloud CDN service that we use to efficiently deliver files required for our service to operate such as javascript, cascading style sheets, images, and videos. (Privacy Policy)
    Google Hosted LibrariesJavascript software libraries such as jQuery are loaded at endpoints on the googleapis.com or gstatic.com domains, for performance and efficiency reasons. (Privacy Policy)
    Features
    Google Custom SearchThis is feature allows you to search the site. (Privacy Policy)
    Google MapsSome articles have Google Maps embedded in them. (Privacy Policy)
    Google ChartsThis is used to display charts and graphs on articles and the author center. (Privacy Policy)
    Google AdSense Host APIThis service allows you to sign up for or associate a Google AdSense account with HubPages, so that you can earn money from ads on your articles. No data is shared unless you engage with this feature. (Privacy Policy)
    Google YouTubeSome articles have YouTube videos embedded in them. (Privacy Policy)
    VimeoSome articles have Vimeo videos embedded in them. (Privacy Policy)
    PaypalThis is used for a registered author who enrolls in the HubPages Earnings program and requests to be paid via PayPal. No data is shared with Paypal unless you engage with this feature. (Privacy Policy)
    Facebook LoginYou can use this to streamline signing up for, or signing in to your Hubpages account. No data is shared with Facebook unless you engage with this feature. (Privacy Policy)
    MavenThis supports the Maven widget and search functionality. (Privacy Policy)
    Marketing
    Google AdSenseThis is an ad network. (Privacy Policy)
    Google DoubleClickGoogle provides ad serving technology and runs an ad network. (Privacy Policy)
    Index ExchangeThis is an ad network. (Privacy Policy)
    SovrnThis is an ad network. (Privacy Policy)
    Facebook AdsThis is an ad network. (Privacy Policy)
    Amazon Unified Ad MarketplaceThis is an ad network. (Privacy Policy)
    AppNexusThis is an ad network. (Privacy Policy)
    OpenxThis is an ad network. (Privacy Policy)
    Rubicon ProjectThis is an ad network. (Privacy Policy)
    TripleLiftThis is an ad network. (Privacy Policy)
    Say MediaWe partner with Say Media to deliver ad campaigns on our sites. (Privacy Policy)
    Remarketing PixelsWe may use remarketing pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to advertise the HubPages Service to people that have visited our sites.
    Conversion Tracking PixelsWe may use conversion tracking pixels from advertising networks such as Google AdWords, Bing Ads, and Facebook in order to identify when an advertisement has successfully resulted in the desired action, such as signing up for the HubPages Service or publishing an article on the HubPages Service.
    Statistics
    Author Google AnalyticsThis is used to provide traffic data and reports to the authors of articles on the HubPages Service. (Privacy Policy)
    ComscoreComScore is a media measurement and analytics company providing marketing data and analytics to enterprises, media and advertising agencies, and publishers. Non-consent will result in ComScore only processing obfuscated personal data. (Privacy Policy)
    Amazon Tracking PixelSome articles display amazon products as part of the Amazon Affiliate program, this pixel provides traffic statistics for those products (Privacy Policy)