Confusion with Graphics2d, canvas and shapes

I am learning the basics of java game programming and I am confused about a few things. I know you are using the canvas class to create an empty canvas, and then use the paint method to create the material.

But what does it do Graphics2D

? I have seen people using the grahpics2d class to create a canvas like

Graphics2D g2d = (Graphics2D) g; 
g2d.setColor(Color.BLACK);

      

Now why are they using grahpics2d and not canvas?

Also I've seen people create shapes like rectangle using:

Rectangle r = new Rectangle();

      

but some people created them like:

Shape shape = new Rectangle2D.Double(value1,valu2,valu3,valu4);

      

What's the difference between the two?

Thanks in advance.

Respectfully,

+3


source to share


2 answers


First, no, I would not use a Canvas object, but a JPanel, and I would use the paintComponent method, not the paint method. Think of JPanel as if it were paint, and Graphics and Graphics2D as the brush you used to paint. In other words, you will need it to create your drawing as well.

As for Rectangle vs. Rectangle2D, then 2D shapes are part of a new addition to Graphics when Graphics2D came along. They are based on the Shape interface, which allows you a little more flexibility and OOP for your drawing.

For more details, please take a look at:


Edit
To your questions:

Q: So, you have to use JPanel as my blank canvas and Graphics2D g2d = (Graphics2D) g; create a brush that you can use to modify the JPanel. Hence, this is g2d.setColor (Color.BLACK); changes the background color of our JPanel. Is it correct?

Yes. And you can even change the Graphics2D Stroke object via



g2d.setStroke(new BasicStroke(...));

      


Q: Also can you explain to me what "Form" is and what do you use it for?

Take a look at the second tutorial I linked above as it will go into detail on what Shape represents and how to use it. In summary, it is the interface used by all Xxxxx2D classes such as Rectangle2D and Ellipse2D. And it allows them all to share certain properties, including being fillable, accessible, recyclable, etc.


Edit 2
For example:

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.geom.AffineTransform;
import java.awt.geom.Path2D;

import javax.swing.*;

@SuppressWarnings("serial")
public class RotateFoo extends JPanel {

   private static final int PREF_WIDTH = 800;
   private static final int PREF_HEIGHT = 600;
   private static final Color STAR_COLOR = Color.red;
   private static final int ROTATE_TIMER_DELAY = 20;
   private static final int POINTS = 5;
   private static final int RADIUS = 50;
   private static final String TITLE = "Press \"r\" to rotate";
   private static final float TITLE_POINTS = 52f;

   private Path2D star = new Path2D.Double(); 
   private Timer rotateTimer = new Timer(ROTATE_TIMER_DELAY, new RotateTimerListener());

   public RotateFoo() {
      double x = 0.0;
      double y = 0.0;
      double theta = 0.0;
      for (int i = 0; i <= POINTS; i++) {
         x = RADIUS + RADIUS * Math.cos(theta);
         y = RADIUS + RADIUS * Math.sin(theta);
         if (i == 0) {
            star.moveTo(x, y);            
         } else {
            star.lineTo(x, y);
         }
         theta += 4 * Math.PI / POINTS;
      }

      double tx = (getPreferredSize().getWidth() - star.getBounds().getWidth()) / 2;
      double ty = (getPreferredSize().getHeight() - star.getBounds().getHeight()) / 2;
      AffineTransform at = AffineTransform.getTranslateInstance(tx, ty);
      star.transform(at );

      int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
      InputMap inputMap = getInputMap(condition);
      ActionMap actionMap = getActionMap();
      String rotateOn = "rotate on";
      String rotateOff = "rotate off";
      inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0, false), rotateOn);
      actionMap.put(rotateOn, new AbstractAction() {

         public void actionPerformed(ActionEvent arg0) {
            if (rotateTimer != null && !rotateTimer.isRunning()) {
               rotateTimer.start();
            }
         }
      });
      inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_R, 0, true), rotateOff);
      actionMap.put(rotateOff, new AbstractAction() {

         public void actionPerformed(ActionEvent arg0) {
            if (rotateTimer != null && rotateTimer.isRunning()) {
               rotateTimer.stop();
            }
         }
      });
      //rotateTimer.start();

      JLabel titleLabel = new JLabel(TITLE, SwingConstants.CENTER);
      titleLabel.setFont(titleLabel.getFont().deriveFont(Font.BOLD, TITLE_POINTS));
      add(titleLabel);
   }

   @Override
   public Dimension getPreferredSize() {
      return new Dimension(PREF_WIDTH, PREF_HEIGHT);
   }

   @Override
   protected void paintComponent(Graphics g) {
      super.paintComponent(g);
      Graphics2D g2 = (Graphics2D)g;
      g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
      g2.setColor(STAR_COLOR);

      if (star != null) {
         g2.draw(star);
      }
   }

   private class RotateTimerListener implements ActionListener {
      private static final double BASE_THETA = Math.PI / 90;

      @Override
      public void actionPerformed(ActionEvent e) {
         double anchorx = getPreferredSize().getWidth() / 2;
         double anchory = getPreferredSize().getHeight() / 2;
         AffineTransform at = AffineTransform.getRotateInstance(BASE_THETA, anchorx, anchory);
         star.transform(at);
         repaint();
      }
   }

   private static void createAndShowGui() {
      RotateFoo mainPanel = new RotateFoo();

      JFrame frame = new JFrame("RotateFoo");
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.getContentPane().add(mainPanel);
      frame.pack();
      frame.setLocationByPlatform(true);
      frame.setVisible(true);
   }

   public static void main(String[] args) {
      SwingUtilities.invokeLater(new Runnable() {
         public void run() {
            createAndShowGui();
         }
      });
   }
}

      

+3


source


you need to make a definite difference:

  • Canvas (or maybe a panel or JPanel or Frame) are objects that represent a GUI object! such an object is required to capture input events, or perhaps to compose it. it can be set active and disabled, all that.
  • Graphics are what is inside the canvas. he is responsible for the clean drawing! it can use special drawing functions that have strokes and fonts and colors ...


so you have two different classes for different purposes! It took me a while to realize that ...

Excuse my drunken English ...

+2


source







All Articles