banner



How To Draw More Than One Shape Java

Shapes and fills

terminal modified July 13, 2020

In this part of the Java 2d tutorial, nosotros create some basic and more avant-garde shapes. Nosotros fill shapes with solid colours, gradients, and textures.

Basic shapes

First we draw some basic Java second shapes.

com/zetcode/BasicShapes.java

packet com.zetcode;  import coffee.awt.Color; import java.awt.EventQueue; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.Ellipse2D; import javax.swing.JFrame; import javax.swing.JPanel;   class Surface extends JPanel {          private void doDrawing(Graphics g) {          Graphics2D g2d = (Graphics2D) g;          g2d.setPaint(new Color(150, 150, 150));          RenderingHints rh = new RenderingHints(                 RenderingHints.KEY_ANTIALIASING,                 RenderingHints.VALUE_ANTIALIAS_ON);          rh.put(RenderingHints.KEY_RENDERING,                RenderingHints.VALUE_RENDER_QUALITY);          g2d.setRenderingHints(rh);          g2d.fillRect(30, 20, 50, 50);         g2d.fillRect(120, 20, ninety, sixty);         g2d.fillRoundRect(250, 20, seventy, 60, 25, 25);          g2d.fill(new Ellipse2D.Double(10, 100, 80, 100));         g2d.fillArc(120, 130, 110, 100, v, 150);         g2d.fillOval(270, 130, fifty, 50);    }       @Override     public void paintComponent(Graphics thou) {                  super.paintComponent(g);         doDrawing(m);     }     }  public course BasicShapesEx extends JFrame {      public BasicShapesEx() {          initUI();     }          private void initUI() {                  add(new Surface());                  setTitle("Bones shapes");         setSize(350, 250);         setLocationRelativeTo(aught);                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }      public static void principal(Cord[] args) {          EventQueue.invokeLater(new Runnable() {                      @Override             public void run() {                 BasicShapesEx ex = new BasicShapesEx();                 ex.setVisible(true);             }         });     } }        

In this example, we draw vi basic shapes on the console: a square, a rectangle, a rounded rectangle, an ellipse, an arc, and a circle.

g2d.setPaint(new Color(150, 150, 150));        

The shapes will be drawn in a gray groundwork.

g2d.fillRect(20, 20, 50, 50); g2d.fillRect(120, 20, 90, lx);        

The fillRect() method is used to draw both a rectangle and a foursquare. The kickoff two parameters are 10, y coordinates of a shape to be drawn. The last 2 parameters are the width and the height of the shape.

g2d.fillRoundRect(250, twenty, seventy, lx, 25, 25);        

Here we create a rounded rectangle. The final 2 parameters are the horizontal and vertical diameters of the arc at the iv corners.

g2d.fill up(new Ellipse2D.Double(10, 100, lxxx, 100));        

The fill() method draws the interior of the given shape—an ellipse.

g2d.fillArc(120, 130, 110, 100, 5, 150);        

The fillArc() method fills a round or elliptical arc covering the specified rectangle. An arc is a portion of the circumference of a circle.

g2d.fillOval(270, 130, 50, fifty);        

A circle is drawn using the fillOval() method.

Basic shapes
Effigy: Bones shapes

General path

More circuitous shapes tin can be constructed with GeneralPath. It represents a geometric path constructed from straight lines, and quadratic and cubic Bézier curves.

The post-obit example creates a star shape with this grade.

com/zetcode/StarEx.java

package com.zetcode;  import java.awt.Color; import java.awt.EventQueue; import coffee.awt.Graphics; import coffee.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.geom.GeneralPath; import javax.swing.JFrame; import javax.swing.JPanel;  course Surface extends JPanel {      private final double points[][] = {          { 0, 85 }, { 75, 75 }, { 100, 10 }, { 125, 75 },          { 200, 85 }, { 150, 125 }, { 160, 190 }, { 100, 150 },          { 40, 190 }, { l, 125 }, { 0, 85 }      };          private void doDrawing(Graphics g) {                  Graphics2D g2d = (Graphics2D) g.create();          g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,                              RenderingHints.VALUE_ANTIALIAS_ON);          g2d.setRenderingHint(RenderingHints.KEY_RENDERING,                              RenderingHints.VALUE_RENDER_QUALITY);          g2d.setPaint(Color.gray);         g2d.translate(25, 5);          GeneralPath star = new GeneralPath();          star.moveTo(points[0][0], points[0][i]);          for (int m = one; yard < points.length; m++)             star.lineTo(points[chiliad][0], points[grand][1]);          star.closePath();         g2d.fill(star);                          g2d.dispose();     }      @Override     public void paintComponent(Graphics yard) {         super.paintComponent(g);                  doDrawing(1000);     } }  public class StarEx extends JFrame {          public StarEx() {          initUI();     }              individual void initUI() {                  add together(new Surface());                  setTitle("Star");         setSize(350, 250);         setLocationRelativeTo(null);                    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }          public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {                          @Override             public void run() {                 StarEx ex = new StarEx();                 ex.setVisible(true);             }         });     }     }        

We create a star from a series of points.

private final double points[][] = {      { 0, 85 }, { 75, 75 }, { 100, 10 }, { 125, 75 },      { 200, 85 }, { 150, 125 }, { 160, 190 }, { 100, 150 },      { forty, 190 }, { 50, 125 }, { 0, 85 }  };        

These are the coordinates of the star.

GeneralPath star = new GeneralPath();        

Here nosotros instantiate the GeneralPath class.

star.moveTo(points[0][0], points[0][1]);        

We move to the initial coordinate of the GeneralPath.

for (int grand = 1; k < points.length; k++)     star.lineTo(points[thousand][0], points[k][one]);        

Here we connect all the coordinates of the star.

star.closePath(); g2d.fill(star);        

We close the path and fill the interior of the star.

Star
Figure: Star

Areas

Another way to create complex shapes is to compose areas. Surface area stores and manipulates a resolution-contained description of an enclosed area of 2-dimensional space. Information technology can be manipulated by addition, subtraction, intersection, and exclusiveOr operations.

com/zetcode/AreasEx.java

package com.zetcode;  import java.awt.Colour; import java.awt.EventQueue; import coffee.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import coffee.awt.geom.Area; import coffee.awt.geom.Ellipse2D; import coffee.awt.geom.Rectangle2D; import javax.swing.JFrame; import javax.swing.JPanel;  class Surface extends JPanel {              public void doDrawing(Graphics g) {          Graphics2D g2d = (Graphics2D) m;                  RenderingHints rh = new RenderingHints(                 RenderingHints.KEY_ANTIALIASING,                 RenderingHints.VALUE_ANTIALIAS_ON);          rh.put(RenderingHints.KEY_RENDERING,                RenderingHints.VALUE_RENDER_QUALITY);             g2d.setRenderingHints(rh);          g2d.setPaint(Color.greyness);                  Surface area a1 = new Area(new Rectangle2D.Double(20, 20, 100, 100));         Area a2 = new Surface area(new Ellipse2D.Double(50, 50, 100, 100));                  a1.subtract(a2);         g2d.fill(a1);                  Area a3 = new Surface area(new Rectangle2D.Double(150, 20, 100, 100));         Surface area a4 = new Surface area(new Ellipse2D.Double(150, 20, 100, 100));                          a3.subtract(a4);         g2d.fill(a3);                  Surface area a5 = new Surface area(new Rectangle2D.Double(280, 20, 100, 100));         Area a6 = new Surface area(new Ellipse2D.Double(320, 40, 100, 100));                          a5.add(a6);         g2d.fill(a5);             }      @Override     public void paintComponent(Graphics thou) {                          super.paintComponent(one thousand);         doDrawing(g);     }            }  public class AreasEx extends JFrame {      public AreasEx() {          initUI();     }      individual void initUI() {                  add together(new Surface());                  setTitle("Areas");         setSize(450, 200);         setLocationRelativeTo(zilch);                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }      public static void principal(String[] args) {          EventQueue.invokeLater(new Runnable() {              @Override             public void run() {                 AreasEx ex = new AreasEx();                 ex.setVisible(true);             }         });     } }        

The case creates iii dissimilar shapes past manipulating areas.

Expanse a1 = new Expanse(new Rectangle2D.Double(xx, 20, 100, 100)); Area a2 = new Expanse(new Ellipse2D.Double(fifty, 50, 100, 100));  a1.subtract(a2); g2d.make full(a1);        

This code constructs a shape by subtracting an ellipse from a rectangle.

Area a5 = new Area(new Rectangle2D.Double(280, 20, 100, 100)); Area a6 = new Area(new Ellipse2D.Double(320, xl, 100, 100));          a5.add(a6); g2d.make full(a5);        

These lines construct a shape by adding a rectangle to an ellipse.

Areas
Figure: Areas

Colours

The Color course is used to work with colours in Java 2D. To fill rectangles with the current colour, nosotros utilize the fillRect() method.

com/zetcode/ColoursEx.coffee

package com.zetcode;  import coffee.awt.Color; import java.awt.EventQueue; import coffee.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel;  grade Surface extends JPanel {              public void doDrawing(Graphics g) {          Graphics2D g2d = (Graphics2D) g;          g2d.setColor(new Color(125, 167, 116));         g2d.fillRect(ten, 10, 90, 60);          g2d.setColor(new Color(42, 179, 231));         g2d.fillRect(130, 10, xc, lx);          g2d.setColor(new Color(70, 67, 123));         g2d.fillRect(250, 10, 90, 60);          g2d.setColor(new Color(130, 100, 84));         g2d.fillRect(10, 100, 90, sixty);          g2d.setColor(new Colour(252, 211, 61));         g2d.fillRect(130, 100, xc, threescore);          g2d.setColor(new Colour(241, 98, 69));         g2d.fillRect(250, 100, 90, 60);          g2d.setColor(new Color(217, 146, 54));         g2d.fillRect(10, 190, ninety, lx);          g2d.setColor(new Color(63, 121, 186));         g2d.fillRect(130, 190, xc, lx);          g2d.setColor(new Color(31, 21, 1));         g2d.fillRect(250, 190, 90, threescore);     }      @Override     public void paintComponent(Graphics thousand) {                          super.paintComponent(one thousand);         doDrawing(g);     }            }  public class ColoursEx extends JFrame {      public ColoursEx() {          initUI();     }      private void initUI() {                  add(new Surface());                  setTitle("Colours");         setSize(360, 300);         setLocationRelativeTo(null);                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }      public static void chief(Cord[] args) {          EventQueue.invokeLater(new Runnable() {              @Override             public void run() {                 ColoursEx ex = new ColoursEx();                 ex.setVisible(true);             }         });     } }        

In the example we draw nine coloured rectangles.

Graphics2D g2d = (Graphics2D) g;        

At that place is no demand to create a re-create of the Graphics2D class or to reset the value when nosotros change the colour property of the graphics context.

g2d.setColor(new Color(125, 167, 116));        

A new colour is created with the Color form. The parameters of the constructor are the crimson, green, and blue parts of the new colour. The setColor() method sets the graphics context's current colour to the specified color value. All subsequent graphics operations use this colour value.

g2d.fillRect(x, 15, xc, sixty);        

To make full the rectangle with a color, we use the fillRect() method.

Colours
Figure: Colours

Gradients

In estimator graphics, slope is a smoothen blending of shades from light to dark or from one colour to some other. In 2D cartoon programs and paint programs, gradients are used to create colorful backgrounds and special furnishings every bit well as to simulate lights and shadows. (answers.com)

com/zetcode/GradientsEx.java

package com.zetcode;  import coffee.awt.Color; import java.awt.EventQueue; import coffee.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import javax.swing.JFrame; import javax.swing.JPanel;  grade Surface extends JPanel {          private void doDrawing(Graphics m) {                  Graphics2D g2d = (Graphics2D) g.create();          GradientPaint gp1 = new GradientPaint(five, 5,              Color.red, 20, 20, Color.black, true);          g2d.setPaint(gp1);         g2d.fillRect(20, 20, 300, 40);          GradientPaint gp2 = new GradientPaint(5, 25,              Color.yellow, twenty, 2, Colour.black, true);          g2d.setPaint(gp2);         g2d.fillRect(20, 80, 300, 40);          GradientPaint gp3 = new GradientPaint(5, 25,              Color.dark-green, 2, 2, Colour.blackness, true);          g2d.setPaint(gp3);         g2d.fillRect(20, 140, 300, forty);          GradientPaint gp4 = new GradientPaint(25, 25,              Color.bluish, 15, 25, Color.black, true);          g2d.setPaint(gp4);         g2d.fillRect(20, 200, 300, twoscore);          GradientPaint gp5 = new GradientPaint(0, 0,               Colour.orange, 0, 20, Color.black, truthful);          g2d.setPaint(gp5);         g2d.fillRect(xx, 260, 300, 40);                     g2d.dispose();     }      @Override     public void paintComponent(Graphics thousand) {                  super.paintComponent(one thousand);         doDrawing(g);     } }  public class GradientsEx extends JFrame {          public GradientsEx() {          initUI();     }              individual void initUI() {                  add(new Surface());                  setTitle("Gradients");         setSize(350, 350);         setLocationRelativeTo(null);                     setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }          public static void primary(String[] args) {          EventQueue.invokeLater(new Runnable() {                      @Override             public void run() {                 GradientsEx ex = new GradientsEx();                 ex.setVisible(true);             }         });     }     }        

Our lawmaking example presents 5 rectangles with gradients.

GradientPaint gp4 = new GradientPaint(25, 25,      Colour.blue, 15, 25, Color.black, true);        

To piece of work with gradients, we employ the GradientPaint class. By manipulating the colour values and the starting and catastrophe points, we can get different results.

g2d.setPaint(gp4);        

The gradient is activated by calling the setPaint() method.

Gradients
Figure: Gradients

Textures

A texture is a bitmap prototype practical to a shape. To work with textures in Java 2D, we employ the TexturePaint grade. A texture is practical with the setPaint() method.

com/zetcode/TexturesEx.coffee

parcel com.zetcode;  import java.awt.EventQueue; import coffee.awt.Graphics; import coffee.awt.Graphics2D; import coffee.awt.Rectangle; import java.awt.TexturePaint; import java.awt.image.BufferedImage; import java.io.File; import coffee.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.imageio.ImageIO; import javax.swing.JFrame; import javax.swing.JPanel;  grade Surface extends JPanel {      private BufferedImage slate;     private BufferedImage coffee;     individual BufferedImage pane;     individual TexturePaint slatetp;     individual TexturePaint javatp;     private TexturePaint panetp;      public Surface() {          loadImages();     }      private void loadImages() {          try {              slate = ImageIO.read(new File("slate.png"));             java = ImageIO.read(new File("java.png"));             pane = ImageIO.read(new File("pane.png"));          } catch (IOException ex) {              Logger.getLogger(Surface.class.getName()).log(                     Level.Astringent, goose egg, ex);         }     }      private void doDrawing(Graphics thou) {          Graphics2D g2d = (Graphics2D) k.create();          slatetp = new TexturePaint(slate, new Rectangle(0, 0, ninety, 60));         javatp = new TexturePaint(java, new Rectangle(0, 0, ninety, 60));         panetp = new TexturePaint(pane, new Rectangle(0, 0, xc, 60));          g2d.setPaint(slatetp);         g2d.fillRect(ten, fifteen, xc, threescore);          g2d.setPaint(javatp);         g2d.fillRect(130, xv, 90, 60);          g2d.setPaint(panetp);         g2d.fillRect(250, xv, ninety, 60);                  g2d.dispose();     }      @Override     public void paintComponent(Graphics k) {          super.paintComponent(thousand);         doDrawing(g);     } }  public form TexturesEx extends JFrame {      public TexturesEx() {          initUI();     }          private void initUI() {                  add(new Surface());          setTitle("Textures");         setSize(360, 120);         setLocationRelativeTo(nix);                 setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);     }      public static void principal(Cord[] args) {          EventQueue.invokeLater(new Runnable() {                      @Override             public void run() {                 TexturesEx ex = new TexturesEx();                 ex.setVisible(true);             }         });     } }        

In the code example, we fill up 3 rectangles with three unlike textures.

slate = ImageIO.read(new File("slate.png"));        

Using the ImageIO class, we read an image into a buffered image.

slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));        

We create a TexturePaint form out of the buffered image.

g2d.setPaint(slatetp); g2d.fillRect(10, xv, 90, 60);        

We fill up a rectangle with a texture.

Textures
Figure: Textures

In this part of the Java 2D tutorial, we have covered some bones and more than avant-garde shapes of the Java 2D library.

Source: https://zetcode.com/gfx/java2d/shapesandfills/

Posted by: howardtheirch.blogspot.com

0 Response to "How To Draw More Than One Shape Java"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel