Results 1 to 3 of 3
  1. #1
    rocklikeits99 is offline Member
    Join Date
    Sep 2010
    Posts
    1
    Rep Power
    0

    Default graphics to graphics2d casting

    Hi, I'm sturagle with the graphics2D API.

    I dont understand the following:

    1) If graphics2D is an extension of graphics why do you cast graphics to graphics2D? downcasting won't add any new atributes and methoeds to the graphics object right??? so whats the point?

    2) Its seems that every exsampe regarding the graphics2D had this syntax:

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

    why should I overide the methode??? why can I just use her?

    Artur (-:

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,259
    Rep Power
    25

    Default

    I think that to preserve legacy code that uses Graphics objects, they pass Graphics2D objects to those methods. But the objects are now Graphics2D so you need to cast the passed object to be a Graphics2D object to be able to use the Graphics2D methods.
    If you are NOT using any Graphics2D methods, you do not need to cast.

  3. #3
    DarrylBurke's Avatar
    DarrylBurke is offline Member
    Join Date
    Sep 2008
    Location
    Madgaon, Goa, India
    Posts
    11,188
    Rep Power
    19

    Default

    Quote Originally Posted by rocklikeits99 View Post
    1) If graphics2D is an extension of graphics why do you cast graphics to graphics2D? downcasting won't add any new atributes and methoeds to the graphics object right??? so whats the point?
    You can't invoke Graphics2D methods on a Graphics reference. The point of downcasting is to obtain access to public methods (and/or public fields, but that's rare) defined in the subclass.

    In case you're concerned about the possibility of a ClassCastException, you needn't be. More on that here:
    Swing - setBackground()

    db

Similar Threads

  1. Graphics2D setRenderingHint not working
    By Crazy Caveman in forum Java 2D
    Replies: 2
    Last Post: 08-27-2010, 06:47 PM
  2. Casting
    By zzpprk in forum Advanced Java
    Replies: 13
    Last Post: 08-13-2009, 07:59 PM
  3. Replies: 3
    Last Post: 02-13-2009, 07:59 AM
  4. What does casting mean?
    By sev51 in forum New To Java
    Replies: 3
    Last Post: 01-27-2009, 04:31 PM
  5. Graphics2D: stack overflow error
    By rosh72851 in forum New To Java
    Replies: 11
    Last Post: 10-15-2008, 09:01 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •