简体   繁体   中英

Java - how to draw Graphics

I tried looking around, but can't understand how to draw graphics in java. Let me make an example.

Let's say I want to create a custom method to fill a triangle, and it takes three points as parameters. How can I use the metod fillPolygon(int[] xPoints, int[] yPoints, int nPoints) if I cannot create a Graphics object?

You need a surface to draw on. Generally this can be done by creating your own component (by extending, for example JPanel in swing) and then overriding the various drawing update methods there. The main relevant one to implement is paintComponent which gets a Graphics object passed in as a parameter.

You can usually also cast your Graphics object to Graphics2D , which gives you a much richer set of drawing primitives.

First thing you should understand (maybe you already know it) is that Graphics is where you write to , not where you write from. It is you computer screen most of the time, such as when you use Swing.

You can also draw directly to an empty image by writing in the Graphics obtained from BufferedImage.getGraphics :

Image myImage = new BufferedImage(...);
Graphics graphImage = myImage.getGraphics();
graphImage.setColor(Color.BLUE);
graphImage.fillPolygon(...);  // set some blue pixels inside the BufferedImage

You could then convert that image to any image format.

A stupid example now, which you should not do (see below for true Swing procedure): you can draw your image in a Swing component

public class MyJPanel extends Panel {

   @Override
   public void paintComponent(Graphics g) { // g is your screen
       ... 
       g.drawImage(myImage,...);  // draw your image to the screen
       ...
   }
}

The standard Swing procedure is to write directly to the screen:

public class MyJPanel extends Panel {

   @Override
   public void paintComponent(Graphics g) { // g is your screen
       ... 
       g.fillPolygon(...); // directly writes your pixels to the screen buffer
       ...
   }
}

(Comment for the nitpickers: It is not quite true that you write directly to the screen buffer since Swing is double-buffered.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM