Hello everybody,

Michael here, and this post (my last 1 for 2021) will serve as a continuation of the previous post, but this time, instead of discussing how to describe lines on the JFrame, I'll discuss how to draw (and color) shapes on the JFrame.

Now, before we start drawing shapes onto our JFrame, permit'due south create the JFrame and make all the necessary imports (this lawmaking will probably seem familiar to y'all if you lot read my previous Java lesson):

                  import javax.swing.*; import java.awt.*; import javax.swing.JComponent;   public grade Graphics101 {      public static void main(String[] args) {         JFrame frame = new JFrame("My commencement JFrame");         frame.setSize(600, 600);           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);            frame.setVisible(true);       }      }                

Ok, at present that nosotros've got our JFrame window set, let's start drawing some shapes. Nosotros're going to start off past drawing a rectangle:

                  import javax.swing.*; import java.awt.*; import javax.swing.JComponent;  class ShapeDrawing extends JComponent {        public void pigment(Graphics one thousand)     {         Graphics2D g2 = (Graphics2D) chiliad;         g2.drawRect(100, 150, 60, 200);     } }  public class Graphics101 {      public static void main(String[] args) {         JFrame frame = new JFrame("My first JFrame");         frame.setSize(600, 600);           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           frame.getContentPane().add together(new ShapeDrawing ());         frame.setVisible(true);       }      }                

At present, to be able to describe shapes onto the JFrame, I created a new class that contains an object of the Graphics form. I also used a .paint() method that executes the drawing. I did all of this when I was drawing lines onto a JFrame, withal for this example I changed the name of the class to ShapeDrawing. Also, simply as I did with the LineDrawing class'due south .paint() method, I created a separate object of the Graphics class (g2 in this instance); this fourth dimension, I'm using g2'due south .drawRect() method to draw a rectangle on the JFrame window.

The .drawRect() method takes in 4 parameters, in the following social club:

  • The x-coordinate where the rectangle is located
  • The y-coordinate where the rectange is located
  • The rectangle's width
  • The rectangle'due south height

Y'all're probably wondering why we don't need to utilize ii 10- and y-coordinates similar we did when we were drawing lines. This is because even though nosotros only specified two points for the rectangle, Java volition figure out where the other 2 rectangle points are located through the width and height that we provided in the .drawRect() method.

  • Note-there is no separate .drawSquare() method in Java's Graphics class. If y'all wanted to draw a square, use the .drawRect() method. Later on all, when you lot think nigh information technology, a square is basically a modified rectangle.

At present, for fun, permit'due south try drawing another shape-allow's practice a circumvolve this fourth dimension (nosotros'll keep the rectangle we drew-all we're doing is simply adding a circle onto the screen):

                  import javax.swing.*; import java.awt.*; import javax.swing.JComponent;  class ShapeDrawing extends JComponent {        public void paint(Graphics g)     {         Graphics2D g2 = (Graphics2D) g;         g2.drawRect(100, 150, 60, 200);         g2.drawOval(185, 235, 80, 220);     } }  public class Graphics101 {      public static void main(Cord[] args) {         JFrame frame = new JFrame("My start JFrame");         frame.setSize(600, 600);           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           frame.getContentPane().add(new ShapeDrawing ());         frame.setVisible(true);       }      }                                  

In this instance, I added the .drawOval() method to the ShapeDrawing class's .paint() method. The .drawOval() method has the same 4 parameters as the .drawRect() method-shape's x-coordinate, shape's y-coordinate, shape'southward width, and shape'southward height-in the same order as the .drawRect() method.

  • Whether yous want to draw an oval or a circle onto the JFrame, employ the .drawOval() method.

Now, it'southward pretty cool that Java has congenital-in methods for drawing basic shapes such as squares, rectangles, and circles. However, Java has no built-in methods for drawing other polygons such equally triangles and hexagons.

Allow'southward say nosotros wanted to add together a triangle to our JFrame. Hither's the lawmaking we'll use:

                  import javax.swing.*; import java.awt.*; import javax.swing.JComponent;  class ShapeDrawing extends JComponent {        public void pigment(Graphics k)     {         Graphics2D g2 = (Graphics2D) g;         g2.drawRect(100, 150, 60, 200);         g2.drawOval(185, 235, fourscore, 220);         int x[] = {400, 400, 500};         int y[] = {100, 200, 200};         int numPoints = 3;         g.drawPolygon(x, y, numPoints);     } }  public class Graphics101 {      public static void principal(String[] args) {         JFrame frame = new JFrame("My showtime JFrame");         frame.setSize(600, 600);           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           frame.getContentPane().add together(new ShapeDrawing ());         frame.setVisible(true);       }      }                

How did I add the right triangle to the JFrame? Pay attention to the four lines of code in the .paint() method that follow the g2.drawOval() line. The lines of lawmaking that begin with int x[] and int y[] create arrays that store the polygon'southward x- and y-coordinates, respectively. Each point in the int 10[] array corresponds to the point in the same position in the int y[] assortment-for instance, the offset element in the int 10[] array (400) corresponds to the start chemical element in the int y[] assortment (100). This means that the kickoff signal in the traingle would exist (400, 100); likewise, the other two points would be (400, 200) and (500, 200).

  • Something to keep in mind when you lot're creating your x- and y-coordinate arrays is to go on them the same length. Also, only include as many elements in these arrays as there are points in the polygon yous plan to draw. In this case, since I'k drawing a traingle onto the JFrame, I shouldn't add more than iii elements to either the x-coordinate or y-coordinate arrays.

After creating my ten- and y-coordinate arrays, I also included a numPoints variable that simply indicates how many points I will include in the polygon-3 in this case, after all I'm cartoon a triangle. Concluding but not least, utilize the .drawPolygon() method to describe the traingle and pass in the x- and y-coordinate arrays along with the numPoints variable as this method'due south parameters.

  • One more thing to note about the .drawPolygon() method-both g and g2 have this every bit a method. Use the g version (which represents Java's Graphics class), as in chiliad.drawPolygon(x, y, numPoints). The g2 (which represents Coffee'southward Graphics2D class-Graphics2D is a subclass of the Graphics grade) version of this method won't work too.

Great! We managed to describe iii shapes onto our JFrame! However, they look clumsily wearisome. Permit'southward come across how to add some color to each shape:

                    import javax.swing.*; import java.awt.*; import javax.swing.JComponent;  class ShapeDrawing extends JComponent {        public void pigment(Graphics g)     {         Graphics2D g2 = (Graphics2D) g;         g2.setColor(Color.BLUE);         g2.drawRect(100, 150, sixty, 200);         g2.fillRect(100, 150, threescore, 200);                  g2.setColor(Color.Orange);         g2.drawOval(185, 235, lxxx, 220);         g2.fillOval(185, 235, 80, 220);                  thousand.setColor(Color.YELLOW);         int x[] = {400, 400, 500};         int y[] = {100, 200, 200};         int numPoints = iii;         m.drawPolygon(x, y, numPoints);         g.fillPolygon(x, y, numPoints);     } }  public class Graphics101 {      public static void chief(String[] args) {         JFrame frame = new JFrame("My get-go JFrame");         frame.setSize(600, 600);           frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);           frame.getContentPane().add(new ShapeDrawing ());         frame.setVisible(true);       }      }                  

Equally you can run into, we now accept a bluish rectangle, orange oval, and yellow right triangle on the JFrame. How did I accomplish this?

Well, for the rectangle, I used the .setColor() method and passed in Colour.Blueish as the parameter. Y'all might think this method alone would do the trick, however, this method merely set'south the shape'southward border color to blue-it doesn't actually fill in the shape. That's why nosotros need to use the .fillRect() method to make full the rectangle; like the .drawRect() method, this method also takes in four parameters. To fill in the rectangle, laissez passer in the same 4 integers that you used for the .drawRect() method in the same gild that they are listed in the .drawRect() method. In this case, I used the integers 100, 150, 60 and 200 for both the .drawRect() and .fillRect() methods.

  • With regards to the .fillRect() method, execute this after executing the .drawRect() method. However, nonetheless execute the .setColor() method earlier executing the .drawRect() method.

To make full in the oval and the triangle, I used the same logic I used to fill in the rectangle. However, to fill in the oval, I used the .fillOval() method and passed in the same` 4 points (in the same order) that I used for the .drawOval() method-185, 235, 80 and 220. I also chosen the .setColor() method to set the oval'due south color earlier I ran the .drawOval() method-much like I did when I set the color of the rectangle.

To fill in the triangle, I used the .fillPolygon() method and passed in the same three parameters (in the same social club) that I used for the .drawPolygon() method-ten, y, and numPoints. And, just like I did for the oval and rectangle, I executed the .setColor() method before running the describe and fill up methods.

Since this is my terminal 2021 post, thank you all for reading my content this twelvemonth (and every year)! I hope you lot had just as much fun learning new programming skills (or honing existing ones) as I did making this content. Tin can't wait to share all the amazing programming content I have planned with you all in 2022! In the meantime, have a very merry vacation season,

Michael