简体   繁体   中英

Java - Swing - Graphics 2D

public class Points extends JPanel {

  public void paintComponent(Graphics g) {
  super.paintComponent(g);

  Graphics2D g2d = (Graphics2D) g;

  g2d.drawLine(60, 20, 80, 90);
 }
}

I'm not really sure what's the Graphics2D g2d = (Graphics2D) g; supposed to do.

It's just a plain JPanel that's later added onto a JFrame.

It would be really helpfull if anyone could give me some advice as I'm stuck at this line of the code for a long time now.

It's a problem of compatibility with older Java code.

Graphics2D , as explained in documentation, is a class that inherits from Graphics and provides some additional graphic features: in short Graphics2D is a more powerful Graphics .

Now, the method paintComponent(Graphics g) exists from before Graphics2D so even if with current Java the Graphics which is under the hood of a JPanel is a Graphics2D , the signature hasn't been changed to break existing code.

At runtime the g passed is a Graphics2D but you need to cast it so that you will be allowed to call more advanced operations on it.

The statement

Graphics2D g2d = (Graphics2D) g;

just casts the Graphics object to a Graphics2D . It's used to access the methods provided by Graphics2D . In this case it is unnecessary as Graphics also has a drawLine method so if you don't have a requirement for the more advanced methods such as rotate and translate , you can use

@Override
public void paintComponent(Graphics g) {
   super.paintComponent(g);
   g.drawLine(60, 20, 80, 90);
}

It casts the graphics context into a Graphics2D object. This is useful because Graphics2D allows for rotations, transformations, antialiasing, etc not possible with a normal Graphics object. All of the methods available in Graphics are still available to you when you use Graphics2D .

您正在将g强制转换为Graphics2D以便可以使用Graphics2D类中的高级功能。

That just casts your Graphics object into a Graphics2D object. Graphics2D has a lot of features that Graphics doesn't provide that are very useful for painting 2D graphics. Check out the documentation for Graphics2D here:

http://docs.oracle.com/javase/7/docs/api/java/awt/Graphics2D.html

Also, according to this other question , that cast should always be safe to do.

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