开发者

Java - how to draw Graphics

开发者 https://www.devze.com 2023-04-02 08:12 出处:网络
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 parame

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. Ho开发者_如何学Cw can I use the metod fillPolygon(int[] xPoints, int[] yPoints, int nPoints) if I cannot create a Graphics object?


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.)


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消