Getting the Graphics2D?

感情迁移 提交于 2020-01-30 09:09:06

问题


public void paint(Graphics g){
    Graphics2D g2 = (Graphics2D)g; //

    double r = 100; //the radius of the circle

    //draw the circle

    Ellipse2D.Double circle = new Ellipse2D.Double(0, 0, 2 * r, 2 * r);
    g2.draw(circle);

This is part of a class within my program, my question lies in the

Graphics2D g2 = (Graphics2D)g;

Why must you include the "g" after the (Graphics2D), and what exactly does the "Graphics2D" Within the parenthesis mean, i am learning out of a book and neither of these were ever fully explained.


回答1:


You are casting Graphics2D to the Graphics context g. Read more about casting here in Inheritance in the Casting section.

What this ultimately does is allot you use the available methods of Graphics2D with the Graphics context of the passed to the paintComponent method. Whitout the casting, you'd only be limited to the methods of the Graphics class

Graphics2D is a subclass of Graphics so by using Graphics2D you gain all the methods of Graphics while taking advantage of the methods in the Graphics2D class.


Side Notes

  • You shouldn't be override paint. Also if you are, you shouldn't be painting on top level containers like JApplet.

  • Instead paint on a JPanel or JComponent and override paintComponent instead of paint and call super.paintComponent. Then just add the JPanel to the parent container.

    public DrawPanel extends JPanel {
        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
        }
    }
    

See more at Custom Painting and Graphics2D




回答2:


Yes, you must include the g.

When you enter your paint method you have an object g of type Graphics.

Then you are typecasting your Graphics object, g to a type of Graphics2D which is a type that extends Graphics.

You have to include the g so you have something to typecast. If you don't include object there you will get a compilation error because the statement isn't complete.

The reason you are typecasting g to a Graphics2D object is because you are telling the compiler, "This Graphics object is actually a Graphics2D object." that way you can perform functions that the Graphics2D Object has that the the Graphics object does not.

This stackoverflow answer explains casting variables in Java very well if you have more questions about that. And this stackoverflow answer explains why it is safe to cast from Graphics to Graphics2D



来源:https://stackoverflow.com/questions/21710323/getting-the-graphics2d

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!