Drawing Lines & Shapes in Java: Methods & Examples

An error occurred trying to load this video.

Try refreshing the page, or contact customer support.

Coming up next: Java Graphics2D Class: Uses & Features

You're on a roll. Keep up the good work!

Take Quiz Watch Next Lesson
 Replay
Your next lesson will play in 10 seconds
  • 0:04 Lines & Shapes
  • 0:37 Lines
  • 1:24 Rectangles
  • 2:22 Corners & Shadows
  • 3:18 Other Shapes
  • 5:16 Lesson Summary
Save Save Save

Want to watch this again later?

Log in or sign up to add this lesson to a Custom Course.

Log in or Sign up

Timeline
Autoplay
Autoplay
Speed Speed

Recommended Lessons and Courses for You

Lesson Transcript
Instructor: Martin Gibbs

Martin has 16 years experience in Human Resources Information Systems and has a PhD in Information Technology Management. He is an adjunct professor of computer science and computer programming.

In this lesson, learn how to draw lines and shapes in Java. See how to draw lines, rectangles, ovals, and polygons (which are key to game programming). Working code examples are provided.

Lines & Shapes

How boring would the web be without graphics? Or, how could you play a video game that didn't make use of shapes or lines? These fundamental graphical components are key to GUI applications. Let's take a look at how to create these elements.

Open your Java compiler and create a package called 'LinesAndShapes.' The code in this lesson was developed using NetBeans IDE 8.2. We'll need utilities/APIs to create the geometric shapes. At first, the program should resemble this block of code.

package linesandshapes;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;
public class LinesAndShapes extends JPanel {
  public static void main(String[] args) {
   //let's setup the frame so we can keep adding to our program
   JFrame f = new JFrame("Twilight Zone");
   f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
   f.getContentPane().add(new LinesAndShapes());
   f.setSize(290, 325);
   f.setLocation(550, 25);
   f.setVisible(true);
  }
}

Lines

In order to draw a line, you need to use the drawLine method of the Graphics class. This method takes four parameters, the starting x and y coordinates and the ending x and y coordinates.

Let's create a paint method that we will be adding to. We've already created the main method that runs the code, so we can simply add our shapes as we go.

Within the LinesAndShapes class, but before the main method, create the paint method. This sets a color for the line and then draws a line starting at 10, 10, and ending at 40, 10. Since the y-coordinates are the same, this will be a horizontal line.

public void paint(Graphics g) {
  //custom color
  String hexColor = new String("0x45e5B");
  g.setColor(Color.decode(hexColor));
  //draw a line (starting x,y; ending x,y)
  g.drawLine(10, 10, 40, 10);
}

The output is shown in the Draw Line Output image.


Draw Line Output
Draw Line Output


You can also set the thickness of the line, using Graphics2D and the setStroke method:

g2.setStroke(new BasicStroke(5));

Rectangles

For our line, we used the Graphics class. We can make use of the newer Graphics2D class, which allows some more options when it comes to 2-D shapes, including thickness, anti-aliasing, etc. Add code to the beginning of the paint method to create a Graphics 2D instance that casts the Graphics class to Graphics2D:

Graphics2D g2 = (Graphics2D) g;

Now, let's use the g2 object to create a cool rectangle. Like lines, rectangles take starting and ending x and y coordinates. The method is drawRect. Add this code to the paint method you have, or feel free to comment out the lines so the screen isn't cluttered. We will be adding lots of shapes!

//draw rectangle
g2.drawRect(10, 20, 150, 40);
g2.setColor(Color.decode(hexColor));

The output is displayed in the Draw Rectangle Output image.


Draw Rectangle Output
DrawRect Output


Now, if you want to draw a solid rectangle, replace the drawRect method with the fillRect method. Recall that we already set the color in the paint method.

//fill rectangle
g2.fillRect(10, 20, 150, 40);

The Filled Rectangle Output image shows the result.


Filled Rectangle Output
Filled Rectangle Output


Corners & Shadows

There's something a little softer about a rounded shape in an application; rounded corners take the edges off and present a user-friendly display. We have created our rectangle, now let's give it some rounded corners.

For the rounded rectangle, we use the RoundRectangle2D class. Like a normal rectangle, it takes starting and ending coordinates, plus a definition of the arc that defines the rounded edges. Add the code to the paint method.

  //rounded rectangle
  RoundRectangle2D rd = new RoundRectangle2D.Float(10, 20, 150, 40, 5, 5);
  g2.draw(rd);


If you want to fill the rounded rectangle, replace these lines of code (or comment them out), with the fillRoundRect method:

g2.fillRoundRect(10, 20, 150, 40, 15, 15);

You'll notice the output isn't as smooth as it could be. The Grahpics2D class provides anti-aliasing. Replace the previous line of code with the following. You'll find you'll want to use the anti-aliasing in all of your graphics programs!

  g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
  g2.fillRoundRect(10, 20, 150, 40, 15, 15);

When the program is run, the output is displayed as seen in the Anti-Aliased Filled Rectangle Output image.


Aliased Filled Rectangle Output
Aliased Filled Rectangle Output


To unlock this lesson you must be a Study.com Member.
Create your account

Register to view this lesson

Are you a student or a teacher?

Unlock Your Education

See for yourself why 30 million people use Study.com

Become a Study.com member and start learning now.
Become a Member  Back
What teachers are saying about Study.com
Try it risk-free for 30 days

Earning College Credit

Did you know… We have over 200 college courses that prepare you to earn credit by exam that is accepted by over 1,500 colleges and universities. You can test out of the first two years of college and save thousands off your degree. Anyone can earn credit-by-exam regardless of age or education level.

To learn more, visit our Earning Credit Page

Transferring credit to the school of your choice

Not sure what college you want to attend yet? Study.com has thousands of articles about every imaginable degree, area of study and career path that can help you find the school that's right for you.

Create an account to start this course today
Try it risk-free for 30 days!
Create an account
Support