ArtsAutosBooksBusinessEducationEntertainmentFamilyFashionFoodGamesGenderHealthHolidaysHomeHubPagesPersonal FinancePetsPoliticsReligionSportsTechnologyTravel

Java 2D Tutorial I--The Basics, Creating New Package, Abstract Class, and Class that extends Abstract Class

Updated on July 24, 2012
Our first assignment was to design a Car using Java 2D...and this is what I designed. I know the drawing is a little crude.
Our first assignment was to design a Car using Java 2D...and this is what I designed. I know the drawing is a little crude.

Intro

Why Java 2D?

For those of you that are tired of text based/console programming and want to add original two dimensional drawings to your Java code, than Java 2D is for you!!!

If you have not read my profile, I was awarded my A.S. in Computer Science in May 2012. I was fortunate that in my last semester of school, I was able to learn Java 2D (it was the first time that class was offered). The picture of the Car to the right and the Pirate Boat below this section are screenshots of my own original designs that the instructor assigned.

This is Part One of a Three Part Tutorial

In this tutorial, I will give you the very basics of starting in Java 2D. Using Eclipse, I will cover how to create a Package, I will give a brief explanation of Classes, how to create a Java Abstract Class, and a Java Class that Extends the Abstract Class. By the time you have finished the tutorials, you will reveal the Mystery Drawing and hopefully have a good grasp of starting Java 2D.

This tutorial is meant for those that are already familiar with Java and/or other OOP (Object Orientated Programming) languages.

Although this tutorial is not meant to serve as an Introduction to Programming for those not familiar with OOP, I will do my best to explain each step.

The assignment was to animate our own original Car Drawings. Just for fun and for a challenge, I designed and animated this Pirate Boat instead.  *Note that this was only the 2nd Drawing I ever did in Java, so I know it is a little crude
The assignment was to animate our own original Car Drawings. Just for fun and for a challenge, I designed and animated this Pirate Boat instead. *Note that this was only the 2nd Drawing I ever did in Java, so I know it is a little crude

Before We Begin

You will need the following free software installed on your computer:

You may want to read the Java SE JDK Installation Guide



Screenshot: Create a New Java Project
Screenshot: Create a New Java Project

Time To Begin

Once you have installed the JDK and Eclipse, now you are ready to begin.

  • Start Eclipse

*Note when you start Eclipse you will see a pop up asking you to Select a workspace, you can either accept the default location or choose a location of your choice.


Starting a New Project

At the top left hand of the screen:

  • select File > New > Java Project
  • Create a New Java Project window will appear. In the Project Name text box, type Mystery Drawing and then click Finish.


Screenshot: Package Explorer
Screenshot: Package Explorer

Create a New Package


On the left hand sized of the screen in the Package Explorer:

  • Right click on the Mystery Drawing folder
  • Then select New > Package
  • Name the package com.java2D.mysterydrawing
  • Click Finish


Class

Again this is not an Intro To Programming Tutorial, however, for those that don't know, a Class can be described as the building blocks/blueprints that individual objects are created from.

Very Basic Example: Let's say you were building a house. What does a house have?

House

  • stories (as in how many floors--upstairs/downstairs etc.)
  • bathrooms (how many bathrooms)
  • bedrooms (how many bedrooms)

With this information we have the building blocks/blueprints of creating a house.

Now we can create many individual objects from the class House

House Ranch
House Victorian
House Colonial
stories = 1
stories = 3
stories = 2
bathrooms = 1
bathrooms = 2
bathrooms = 1.5
bedrooms = 3
bedrooms = 5
bedrooms = 4

If you are new to programming in Java, you may want to read about Inheritance, Interfaces, and Abstract Methods. For those that are familiar with C++, Java does not have multiple inheritance.


Now we are going to Create our first Class.

Right click on com.java2D.mysterydrawing > New > Class

  • In the Name text box type Model
  • Under the text box you will see Modifiers check abstract

Type the code listed below. You should type the code instead of copying and pasting...this will help you become comfortable with the language.

The // are used to write one line of comments to explain the code.

/* */ are used to write more than one line of comments. All comments are placed above the code so that you know what you are looking at.

If you are familiar with C++, import it is the equivalent to C++ #include.

*Note in the Model Class code posted below for some reason the below constructor shows up in green like the comments do. This should NOT be commented out.

public Model(){
		this(0, 0);
	}

Model Class

package com.java2D.mysterydrawing;

import java.awt.Graphics2D;

public abstract class Model {
	
	// this will be the position of our Mystery Drawing
	
	protected float x = 50, y = 100;

	/*This is a default constructor 
	 * a constructor that does not pass any arguments 
	 * this constructor updates x and y to specific values
	 */
	
	
	public Model(){
		this(0, 0);
	}

	

	/*
	 * This is a 2 argument constructor the first argument is float xNew the
	 * second argument is float yNew this constructor updates x and y to values
	 * passed in as arguments
	 */
	public Model(float xNew, float yNew) {
		x = xNew;
		y = yNew;
	}

	// method to draw shape of our Mystery Drawing
	public abstract void drawShape(Graphics2D g);

}

Text Version of Model Class

package com.java2D.mysterydrawing;

import java.awt.Graphics2D;

public abstract class Model {

// this will be the position of our Mystery Drawing

protected float x = 50, y = 100;

/*This is a default constructor

* a constructor that does not pass any arguments

* this constructor updates x and y to specific values

*/

public Model(){

this(0, 0);

}

/*

* This is a 2 argument constructor the first argument is float xNew the

* second argument is float yNew this constructor updates x and y to values

* passed in as arguments

*/

public Model(float xNew, float yNew) {

x = xNew;

y = yNew;

}

// method to draw shape of our Mystery Drawing

public abstract void drawShape(Graphics2D g);

}


Now we are going to Create our first Class that will extend the Model class.

Right click on com.java2D.mysterydrawing > New > Class

  • In the Name text box type Mystery
  • Under Which methods stubs would you like to create: check public static void main (String[] args) and Inherited abstract methods
  • Click Finish

*Note it make take a few moments to build.

Mystery.Java should look like this:

package com.java2D.mysterydrawing;

public class Mystery {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

}


Where it says public class Mystery after the word Mystery type extends Model

When you do this, you will notice the word Mystery has a red squiggly line, hover your mouse over the word Mystery you should receive a pop up, click Add unimplemented methods.

Notice you now have the drawShape method created in the abstract class Model.

*Note that the word method (used in Java) is the same as function in other languages.

Rearrange your code so that it looks the same as the code posted below. All I really did was move the drawShape method above the public static main void.


package com.java2D.mysterydrawing;

import java.awt.Graphics2D;

public class Mystery extends Model{

	@Override
	public void drawShape(Graphics2D g) {
		// TODO Auto-generated method stub
		
	}
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		// TODO Auto-generated method stub

	}

	

}

Text Version of the Mystery Class

package com.java2D.mysterydrawing;

import java.awt.Graphics2D;

public class Mystery extends Model{

@Override

public void drawShape(Graphics2D g) {

// TODO Auto-generated method stub

}

/**

* @param args

*/

public static void main(String[] args) {

// TODO Auto-generated method stub

}

}


This Concludes Tutorial I

In the next tutorial, I will cover JFrame, JPanel, Coordinate system, Custom Colors, Gradient Paint and Testing your code.

I hope you find my tutorials informative and I hope they give you a better understanding of the subjects covered. If you do like my tutorials you might want to check out my other Hubs and perhaps learn something new.

THANK-YOU for taking the time to read this. GOOD LUCK!!!!

Comments

    0 of 8192 characters used
    Post Comment

    • profile image

      carthick 

      4 years ago

      am not getting how to run thisZ????????????????

    • Patty Kenyon profile imageAUTHOR

      Patty Kenyon 

      6 years ago from Ledyard, Connecticut

      Leo, Thank-you!! I will be doing more tutorials soon! Thanks Again!!

    • Leo Lucas profile image

      Leo Lucas 

      6 years ago

      Muito bom! Obrigado pelo tutorial!

    • profile image

      IntegrityYes 

      6 years ago

      OOH, Patty! HEH-HEH!

    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)