Casting Graphics to Graphics2D objects

It is declared in the API that the class Graphics2D extends from Graphics class. In an example given in the tutorials on java.sun.com, i came accross a code that is as follows:
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D) g;
Can anyone explain how? what i learnt is that casting to a Sub class from a Base clase is not legal.
thanks in advance,
vanchinathan

it's like
Object obj=new Object();
String str=(String)obj;
you can't do that in java ? try to compile this
code;
HimerusYes you can, you simply get a ClassCastException at runtime.
The reason it is valid to cast from Graphics to Graphics2D, is because Sun have said that all Graphics objects returned by the API in Java 1.2 or above will be a subclass of Graphics2D.

Similar Messages

  • How to make a Graphics2D object from a Graphics object?

    Hallo !
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;I get an Exception as follows:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Is there an other possibility to to make a Graphics2D Object ? Or can I repair the error on an other way?
    Thank you Wolfgang

    Yes JBuilder makes a reference to this line.
    pj is a PrintJob.
    The only lines in this method for test are
    PrintJob pj = Toolkit.getDefaultToolkit().getPrintJob(p,"PrintWindow",null);
    Graphics g = pj.getGraphics();
    Graphics2D g2 = (Graphics2D) g;
    pj.end();Exception occurred during event dispatching:
    java.lang.ClassCastException: sun.awt.windows.WPrintGraphicsWrapper
    Wolfgang

  • Jpanel holding a Graphics2d object

    hi!
    Im trying to properly extend JPanel to display a Graphics2d Object that already exists. So what I have done is extended JPanel, and in the constructor, I send the graphics2d object that i would like displayed on the jpanel object.
    Then in paintComponent, I cast the graphics object to a graphics2d object and set the value equal to the graphics2d object already created.
    The problem is that when I use the component, all I get is a blank jpanel. I dont know what the problem is... code follows, please let me know what you think
    Thanks.
    public class JPanelGraphics2d extends JPanel{
         Graphics2D m_g2d;
         JPanelGraphics2d (Graphics2D g){
              m_g2d = g;
              setPreferredSize(new Dimension(450, 450));
         public void paintComponent(Graphics g) {
              super.paintComponent(g);
              Graphics2D g2 = (Graphics2D)g;
              g2 = m_g2d;
    }

    It looks a bit like you don't understand the nature of Java's method parameters.
    Setting g2 = m_g2d does nothing outside your paintComponent method - it simply changes the reference that g2 holds within your paintComponent.
    However, there's also something else wrong about your approach. A Graphics object is simply a toolkit and context for drawing graphics - it doesn't maintain any image of what's been drawn. An Image is what contains imagery and graphics - a Graphics is what's used to draw this.
    Therefore you're probably after creating an Image, passing that your your panel and drawing that in the paintComponent method.
    Hope this helps a bit.

  • Merging Two Graphics2D objects into one

    Is it possible to accomplish this:
    1) have a method in class A that returns a Graphics2D object
    2) have a method in class B that returns a Graphics2D object
    3) have class C call both class A's and class B's methods that return Graphics2D objects
    4) lay those two Graphics2D objects into a new Graphics2D object within a component's paint(Graphic g) method
    What I am trying to do is a lot like a Viso diagram, that is drag a graphic onto another graphic x numberof times and perform some kind of layering technique.
    Thanks

    Why don't you pass a graphics 2D into each method, and get method to draw onto that. Then it becomes very simple to combine each.
    MArk

  • Changing a Graphics2D object into a BufferedImage

    Well subject says it all really. At some point in my code I extract a Graphics2D object from another object, and I'd like to store it as a BufferedImage. The code below does almost what i want, but not quite.
    BufferedImage img;
    GraphicsConfiguration gc = this.getGraphicsConfiguration();
    this.img = gc.createCompatibleImage(getWidth(), getHeight(), BufferedImage.OPAQUE);
    Graphics2D g2d = img.createGraphics();
    This is the only hint I've been finding around the forums, and it works well if you just want to draw new drawings on a BufferedImage. However, I have a Graphics2D object that already contains alot of graphics, and I want to copy this into a BufferedImage. I can't seem to find a way to do this no matter where i look.
    Any help would be appreciated.

    reading through alot of code will be alot more work than a simple explanation of the problemA good SSCCE is many times easier to understand than a description.
    That said, if I understand what you are trying, I assume you have a paintComponent override in nr1 that has a drawImage statement, and you want to obtain a part of that image in nr2 which is in a different class, to a BufferedImage in the same class as nr2.
    If that's it, you can construct a BufferedImage of appropriate size and call the paintComponent method of nr1 with the Graphics reference of the BufferedImage, translated or otherwise transformed if necessary, to paint the panel's painting on the BufferedImage. Something like (in the class containing nr2)
    BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
    Graphics2D g = bi.createGraphics());
    g.translate(x, y); // optional
    g.setClip(x1, y1, w1, h1); // optional
    nr1.paintComponent(g);Note that you need a reference to panel nr1 in the class containing nr2.
    Now (even if this is not what you needed) which was easier to understand -- the description above or the code? So if that's not it, don't expect anything more without a SSCCE which only demonstrates the problem faced -- not 500 lines of code that have nothing to do with the problem.
    luck, db

  • Scaling a Graphics2D object

    hi there! i have this drawing in a Graphics2D object and if I render it it takes around 2 seconds to load. if i scale it before I render it takes like 4 seconds to show up? is there anyway to speed this up?
    heres some of my code:
      public void paint(Graphics g){
            Graphics2D g2d = (Graphics2D) g; 
            g2d.scale(0.5, 0.5); //// heres the line that slows down the system!
            for (int y = 0; y < 256; y++) {
                for (int x = 0; x < 256; x++) {
                    g2d.setPaint(new Color((int) Mod.mod(tree[0].evaluate(v), 255), (int) Mod.mod(tree[1].evaluate(v), 255), (int) Mod.mod(tree[2].evaluate(v), 255)));
                    g2d.drawRect(x, y, 0, 0);
        }Mind the drawing method, Im actually evulating an expression tree for each pixel on the canvas (256x256) so it produces a random pattern.

    Something I forgot earlier: if you apply transforms to your Graphics context, you need to undo those when your done. I.e. the paint method should actually look like this:public void paint(Graphics g){
      Graphics2D g2d = (Graphics2D) g;
      AffineTransform oldTransform = g2d.getTransform();
      // apply whatever transforms you need
      // calculate the position of the image's upper left corner
      int x = ...;
      int y = ...;
      g2d.drawImage(image, x, y, null);
      g2d.setTransform(oldTransform);
    }If you modify the Graphics context in other ways (e.g. setting a Color, Stroke, etc), too, it might be easier to work on a copy though:public void paint(Graphics g){
      Graphics2D g2d = (Graphics2D) ((Graphics2D) g).create();
      // apply whatever transforms you need
      // calculate the position of the image's upper left corner
      int x = ...;
      int y = ...;
      g2d.drawImage(image, x, y, null);
      g2d.dispose();
    }

  • How can I stack Graphics2D objects

    How can I stack two or more Graphics2D objects on the same BufferedImage.

    I am trying to create layers. Here is an example I have started with. The problem is the remarked code. The effect is correct but it is applied to the complete image. I would like to separate the effect to only the shadow text. I would appreciate any help. I am new to Java so still fumbling around with concepts.
    import java.awt.*;
    import java.awt.font.*;
    import java.awt.image.*;
    import java.io.*;
    import javax.imageio.*;
    import java.awt.geom.*;
    import java.util.*;
    public class ShadowText {
    static Rectangle2D.Double Rectangle;
    static BufferedImage image;
    static Graphics graphics;
    static Graphics2D g2d;
    static TextLayout textLayout;
    public ShadowText() {
    public static void main(String[] args) {
    BufferedImage image = new BufferedImage(500,120,BufferedImage.TYPE_INT_RGB);
    Rectangle2D Rectangle = new Rectangle2D.Double(0,0,500,120);
    graphics = image.getGraphics();
    g2d = (Graphics2D) graphics;
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    g2d.setPaint(Color.white);
    g2d.fill(Rectangle);
    g2d.draw(Rectangle);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    //g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, .5f));
    textLayout = new TextLayout("Shadow Text", new Font("Serif", Font.BOLD, 70), g2d.getFontRenderContext());
    g2d.setPaint(Color.black);
    textLayout.draw(g2d, 12, 102);
    //float ninth = 1.0f / 9.0f;
    //float[] kernel = {ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth, ninth};
    //biop = new ConvolveOp(new Kernel(3, 3, kernel));
    //op = (BufferedImageOp) biop;
    //image = op.filter(image,null);
    g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING,RenderingHints.VALUE_ANTIALIAS_ON);
    textLayout = new TextLayout("Shadow Text", new Font("Serif", Font.BOLD, 70), g2d.getFontRenderContext());
    g2d.setPaint(Color.black);
    textLayout.draw(g2d, 10, 100);
    Write("C:/JavaTraining/Filters/images/ShadowText.jpg",image);
    public static void Write(String file, BufferedImage image){
    //Check for file exsist
    StringTokenizer tokens = new StringTokenizer(file,".");
    if(tokens.countTokens()>0){
    String filename = tokens.nextToken().trim();
    String type = tokens.nextToken().trim();
    try{
    if(type.equalsIgnoreCase("gif")) type = "png";
    ImageIO.write(image, type, new File(file));
    }catch (IOException e){
    System.out.println("Invalid file name or path! "+file);
    }else{
    System.out.println("Invalid file name! "+file);
    }

  • Ordering Graphics2D objects

    Is there anyway to handle the z axis' ordering of Graphics2D objects? I'm developing a graphic tool wich provides support for specifying component based applications for a digital tv framework and i'm representing these components both with JLabels and Graphics2D. I can easily set the z order for the JLabel with the setComponentZOrder method but when i'm dealing with Graphics2D rectangles i don't know how to get it working... any hints?
    10x in advance...

    What i'm actually trying to do is to suport user interaction so he could drag away graphics2d rectangles. So the only way would be draw the component being dragged later? I'll try this ... i didn't think about it LOL ... sorry to bother

  • Problem: Mulitple panels, one Graphics2d object?!?!

    Help!
    My application contains one main JPanel, called DrawingPanel. DrawingPanel contains many different Graphics2D objects that it periodically repaints and redraws. When a user clicks on one of these objects, the listener pops up a different JPanel (a list of these new Panels is a member variable of DrawingPanel). In this JPanel I want to draw some new Graphics2D objects. The problem is that when I call paint or paintComponent in the new JPanel (i've tried both) the Graphics2D object contains all the objects from DrawingPanel also. How do I get rid of this extra garbage? I've tried using the dispose function after painting the graphics in both places, but this doesn't work...ideas?
    (sorry, for the cross post to java swing if anyone noticed...I'm desperate and figured that maybe I put this in the wrong forum originally...thanks)

    your query is difficult to understand, if ur problem is related to painting to the specific panel try
    painting
    component.paintComponent()
    or if ur panels are a differnet classes then try to override the paint method in each place.
    and if u do not want a paint method at all
    then create a graphics object with
    component.getGraphics() method and dispose ur
    graphics object inside finalize() method.

  • CASTING AN ARRAY OF OBJECTS

    Hi guys, How I need do to cast an array of objects to a String array??!?!
    I am using
    String array[] = (String[]) getObjects();
    //getObjects() return a Object[]Thanks.
    Giscard

    And what? You get a ClassCastException? If so, you're attempting to change the type of reference that points to the object to a type that isn't the same as the class of the object instance, or a class that the class of the object instance extends, or an interface that the class of the object instance implements.

  • Can objects returned from web services be cast to strongly typed objects?

    Can objects returned from web services be cast to strongly
    typed objects?
    Last I tried this was with one of the beta of Flex2 and it
    did not work. You had to use ObjectProxy or something like that...
    Thanks

    Please post this question in the CRM On Demand Integration Development forum.

  • Is there anyway I can have a graphic track an object in a video?

    Is there anyway I can have a graphic track an object in a video?

    In FCE it can be done, but it's a rather tedious process.  Load the graphic from the Timeline into the Viewer, then click on the Motion tab.  Keyframe the movement as needed to follow the subject in the video (while watching the Canvas window).
    -DH

  • Drawing an oval with a Graphics2D object

    Can someone help me use the Graphics2D API more effectively? I'm trying to draw a slanted oval into a Canvas. Here is my code:
    class MyCanvas extends Canvas {          
         public MyCanvas() {
              super();
         public void paint(Graphics g) {          
              Graphics2D g2 = (Graphics2D) g;          
              Ellipse2D.Float e = new Ellipse2D.Float(70.0f, 20.0f, 89.0f, 50.0f);
              BasicStroke bStroke = new BasicStroke(1.5f);          
              g2.setStroke(bStroke);          
              g2.rotate(Math.toRadians(10.00));          
              g2.draw(e);
         } // end Paint
    } // end MyCanvas
    It seems that 'rotate' is rotating the entire coordinate system instead of just the oval. Also, I would like the oval to be drawn smoothly. Do I need to adjust the "antialiasing" property, or something else?
    Thanks,
    Eric

    >
    Can someone help me use the Graphics2D API more
    effectively? I'm trying to draw a slanted oval into a
    Canvas. Here is my code:
    class MyCanvas extends Canvas {          
         public MyCanvas() {
              super();
         public void paint(Graphics g) {          
              Graphics2D g2 = (Graphics2D) g;          
    Ellipse2D.Float e = new Ellipse2D.Float(70.0f,
    , 20.0f, 89.0f, 50.0f);
              BasicStroke bStroke = new BasicStroke(1.5f);          
              g2.setStroke(bStroke);          
              g2.rotate(Math.toRadians(10.00));          
              g2.draw(e);
         } // end Paint
    } // end MyCanvas
    It seems that 'rotate' is rotating the entire
    coordinate system instead of just the oval. Also, I
    would like the oval to be drawn smoothly. Do I need to
    adjust the "antialiasing" property, or something
    else?
    Thanks,
    EricLook at AfineTransform instead of Rotate.

  • How can I make ANY vector  graphics with graphics2D and save on clipboard?

    I am at my wits end here, and need some help. Simply put, I have a program that creates a basic x-y graph, drawn in a jpanel. I want to create the graph as a vector (emf, eps, svg, I don't care anymore, any of them would be good). But, all I get is a jpg or bitmap.
    I tried using the infamous FreeHEP programs, but it won't recognize the output as anything but "image" which means bitmap/jpg.
         The user enters x/y data, clicks a button, which crreates a jpanel thusly:
    public class GraphMaker extends JPanel {
    static BufferedImage image = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    GraphMaker(double[] xVals, double[] yVals, double[] sems){
    setPreferredSize(new Dimension (600,500));     
    symSize = 10;
    XminV = 0;
    XmaxV = 0;
    // code here just converts input x and y's to pixel coordinates, spacing of ticks, etc...
    for (int i =0;i < ArLn; i++){
    gX[i] = xO + (gX[i] * xRat);
    gX[i] -= xStart;
    gY[i] = gY[i] * yRat;
    gY[i] = yEnd - gY;
    semVal[i] = semVal[i]*yRat;
         Ymin = yEnd - (Ymin*yRat);
         Ymax = yEnd - (Ymax*yRat);
    BufferedImage anImage = new BufferedImage(600, 500, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = anImage.createGraphics();
    g2.setBackground(white);
    g2.setColor( Color.WHITE );
    g2.fillRect(0,0,600,500);
    g2.setStroke(stroke);
    // here I use the values to draw lines and circles - nothing spectacular:
              g2.setPaint(Color.blue);
              int ii = 0;
              for ( int j = 0; j < ArLn[ii]; j++ ) {
    g2.fill(new Ellipse2D.Float(LgX[ii][j] - symOffst, gY[ii][j]-symOffst, symSize,symSize));
    g2.draw(new Line2D.Float(LgX[ii][j],(gY[ii][j]-semVal[ii][j]),LgX[ii][j],(gY[ii][j]+semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]-semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]-semVal[ii][j])));
    g2.draw(new Line2D.Float(LgX[ii][j]-2.0f,(gY[ii][j]+semVal[ii][j]),LgX[ii][j]+2.0f,(gY[ii][j]+semVal[ii][j])));
                        g2.draw(new Line2D.Float(xLoVal[ii],yLoVal[ii],xHiVal[ii],yHiVal[ii]));
    image = anImage;
    And, when the user clicks on the "copy" button, invokes this:
    public class Freep implements Transferable, ClipboardOwner {
         public static final DataFlavor POSTSCRIPT_FLAVOR = new DataFlavor("application/postscript", "Postscript");
         private static DataFlavor[] supportedFlavors = {
              DataFlavor.imageFlavor,
              POSTSCRIPT_FLAVOR,
              DataFlavor.stringFlavor
         private static JPanel chart;
         private int width;
         private int height;
         public Freep(JPanel theGraph, int width, int height) {
              this.theGraph = Graphs;
              this.width = width;
              this.height = height;
    //******This is the key method right here: It is ALWAYS imageFlavor, never anything else. How do I make this an EPS flavor?
         public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
    if (flavor.equals(DataFlavor.imageFlavor)) {
    return GraphMaker.image;
    else if (flavor.equals(POSTSCRIPT_FLAVOR)) {
                   return new ByteArrayInputStream(epsOutputStream().toByteArray());
    else if (flavor.equals(DataFlavor.stringFlavor)) {
                   return epsOutputStream().toString();
              } else{
                   throw new UnsupportedFlavorException(flavor);
         private ByteArrayOutputStream epsOutputStream() throws IOException {
    EPSDocumentGraphics2D g2d = new EPSDocumentGraphics2D(false);
    g2d.setGraphicContext(new org.apache.xmlgraphics.java2d.GraphicContext());
    ByteArrayOutputStream out = new ByteArrayOutputStream();
         public DataFlavor[] getTransferDataFlavors() {
              return supportedFlavors;
         public boolean isDataFlavorSupported(DataFlavor flavor) {
              for(DataFlavor f : supportedFlavors) {
                   if (f.equals(flavor))
                        return true;
              return false;
         public void lostOwnership(Clipboard arg, Transferable arg1) {
    The same happens with FreeHEP - I want the flavor to be EMF, but the program sees an image so it is always imageFlavor. I know I am missing something, but what, I don't know.
    thanks for your help.

    I don't think there's a built-in solution. One workaround I've seen is to create a dummy graphics class that overrides the desired drawing functions. Instead of actually drawing pixels, the object writes postscript commands to a buffer. There also seems to be commercial code that does exactly this.

  • Graphics2D Objects What am I doing wrong?

    I have a Graphics object of JPanel and that is working fine:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JPanel;
    public class GraphicsTest extends JPanel
        private Graphics2D g2d;
        private String state;
        private int x, y;
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g2d = (Graphics2D) g;
            g2d.setClip(0, 0, getWidth(), getHeight());
            g2d.setColor(Color.BLACK);
            g2d.drawString("STATE: " + state, 5, 15);
            g2d.drawString("Mouse Position: " + x + ", " + y, 5, 30);
            g2d.setColor(Color.red);
            Rectangle2D r2d = new Rectangle2D.Double(x,y,10,10);
            g2d.draw(r2d);
            Test t = new Test();
            super.add(t);
            repaint();
        public void setState(String state) { this.state = state; }
        public String getState() { return state; }
        public void setX(int x) { this.x = x; }
        public void setY(int y) { this.y = y; }
    }I was experimenting with a new Graphics component and when I instantiate a new Test and add it in GraphicsTest nothing happens. What is it that I am doing wrong?
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JComponent;
    public class Test extends JComponent
        private Graphics2D g2d;
        private String state;
        private int x, y;
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g2d = (Graphics2D) g.create();
            g2d.setColor(Color.GREEN);
            g2d.fill(new Rectangle2D.Double(60, 60,
                    10, 10));
            repaint();
        public void setState(String state) { this.state = state; }
        public String getState() { return state; }
        public void setX(int x) { this.x = x; }
        public void setY(int y) { this.y = y; }
    }Thanks!

    Here is latest code:
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import java.awt.geom.Rectangle2D;
    import javax.swing.JPanel;
    public class GraphicsTest extends JPanel
        private Graphics2D g2d;
        private String state;
        private int x, y;
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            g2d = (Graphics2D) g;
    super.add(new Test());
            g2d.setColor(Color.BLACK);
            g2d.drawString("STATE: "  +state, 5, 15);+
    +        g2d.drawString("Mouse Position: "+  x  +", "+  y, 5, 30);
            g2d.setColor(Color.red);
            Rectangle2D r2d = new Rectangle2D.Double(x,y,10,10);
            g2d.draw(r2d);
            g2d.dispose();
        public void setState(String state) { this.state = state; }
        public String getState() { return state; }
        public void setX(int x) { this.x = x; repaint(); }
        public void setY(int y) { this.y = y; repaint(); }
    import java.awt.Color;
    import java.awt.Graphics;
    import java.awt.Graphics2D;
    import javax.swing.JComponent;
    public class Test extends JComponent
        @Override
        public void paintComponent(Graphics g)
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g.create();
            g2d.setColor(Color.BLUE);
            g2d.drawString("TEST", 50, 50);
            g2d.dispose();
    }Is there a reason why it's not getting added? I have the Filthy Rich Clients book and do not remember it covering this topic at all. If it does can anyone point to the right direction on what I am doing wrong here?

Maybe you are looking for