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.

Similar Messages

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

  • Which SD Table holds the Technical Object Information?

    I am writing a report in SQ01 and can't find an SD table holding the technical objects information from the Sales contracts or orders. Can anyone suggest a table or which tables to joins I need. .
    Thanks
    Jen

    .... also:
    inner join with sales ordem item:
    VBPM-VBELN = VBAP-VBELN
    VBPM-POSNR = VBAP-POSNR
    Available fields:
    Technical reference object type
    Technical reference object
    Serial number

  • 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

  • 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

  • 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

  • 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?

  • Blend Mode doesn't hold in Smart Object

    Here's the scenario:
    I'm building a web page, lot's of layers and groups. I want to clean things up by converting some groups into smart objects.
    Here's the Problem:
    Within some of the group folders are layers with a blend mode assigned, like Darken. When I convert the group to a Smart Object the blend mode on those layers doesn't hold.
    Screen grabs:
    Hopefully these will make it clear in cas I haven't explained it well.
    Original with layers
    Group converted to Smart Object
    Bland mode applied to Smart Object
    I figured out why it happens, I want to know if there's a way around it other then don't do it.
    TIA,
    Mike

    Yep, another understandable feature by few who understand, but created by many users -  toy feature for web and print. It can either mean money or murder when handed these files from your bone head customer who assumes anything that can be created shall work with the greatest of ease because marketing told you so.
    Now that's progress intelligently planned.
    sweet~!

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

  • Painting Graphics2D objects

    Hello,
    I'm trying to learn some graphics apps as a hobby, and am running into a problem. As you can tell by the code posted below, I'm trying to create 4 walls of random lengths that will fit in a room. I need the walls to be Line2D objects, b/c later I need to be able to call some methods such as intersectsLine().
    When I run this code, I receive an error that reads:
    draw(java.awt.Shape) in java.awt.Graphics2D cannot be applied to (java.awt.geom.Line2D[]) g2.draw(walls);
    Then, how do I paint java.awt.geom objects?
    The part of the code I'm having trouble with is below:
    public void paint (Graphics g) {
              super.paint(g);
              g.translate((int)(.25 * roomWidth), (int)(.25 * roomHeight));
              //draw room
              g.drawRect(0, 0, roomWidth, roomHeight);
              Graphics2D g2 = (Graphics2D)g;
              //draw walls
              Line2D[] walls = new Line2D [4];
              for (int i = 0; i <= 4; i ++ ) {
                   walls = new Line2D.Double((int) (Math.random() * roomWidth), (int) (Math.random() * roomHeight),
                        (int) (Math.random() * roomWidth), (int) (Math.random() * roomHeight));
                        g2.draw(walls);
    Thanks for your help.

    draw(java.awt.Shape) in java.awt.Graphics2D
    cannot be applied to (java.awt.geom.Line2D[])this tells you that you can't pass an array of Line2D objects to the draw method. It accepts only one shape at a time.
    Maybe instead of
    g2.draw(walls);you meant
    g2.draw(walls[index]);

  • How to turn a graphics2D object into a BufferedImage

    Is there a simple way to take a Graphics 2D I have
    drawn and turn it into a BufferedImage?
    MArk

    OK, I understand now. First of all, a subimage has to be rectangular. You can't get a subimage that's an irregular shape. If you want a transparent background, we'll approach that later. First:
    // Create a BufferedImage for your original image.
    BufferedImage wholeImage = new BufferedImage(x, y, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = offScreen.createGraphics();
    // Set the clip region to draw in.
    g2.setClip(...);
    // Draw your entire picture to the offscreen image.
    g2.draw(...);
    // Now we want a bounding box for your clipped region.
    Rectangle clipRect = g2.getClipBounds();
    // Get a subimage from your original image that contains the clipped region.
    BufferedImage clippedImage = wholeImage.getSubimage(clipRect.getX(), clipRect.getY(), clipRect.getWidth(), clipRect.getHeight());Now you have a subimage that has the proper bounds to contain your clipped image in the smallest rectangle possible. The second image can be written to disk. The TYPE_INT_ARGB implies an alpha channel that gives you a transparent background so there's no bounding "square" wherever you decide to draw your subimage. Does this help?
    Michael Bishop

  • Uusing Beans to hold Database connection objects

    Hi,
    I am kind of new to Java. I wanted to create a db connection object and use the same in the rest of the pages within the session.
    In the first page I got the connection object and along with other values I created a bean with scope session and stored the connection object using the setProperty method.
    In the next page I retrieve the values using the getProperty method and pass the connection object to a method which updates the database.
    When I execute this I get a Runtime error pointing to the method invoked. When I execute the method in standlone mode calling from main method it executes fine.
    Can anyone tell me if there is a problem when storing and retrieving objects using the setProperty and getProperty methods.
    Regards
    VM

    For application listeners, see http://www.onjava.com/pub/a/onjava/2001/04/12/listeners.html and also JavaDocs at sun.( ServletContextListener class is in javax.servlet package )
    You should do the initialization and putting the instance in application scope in public void contextInitialized(...) method of your listener, by for example block of code like,
    public void contextInitialized( ServletContextEvent sce ) {
         // Gettin' your servlet context object for current web application
         ServletContext application = sce.getServletContext();
         // instanciate your DB bean
         MyDataPool db = MyDataPool.getInstance();
         // puttin' instance in scope for later use
         application.setAttribute( "db", db );
    This causes you when needed, use ServletContext's getAttribute( "db" ) method to retrieve your database.
    for now you just need to add to your "web.xml" <listener> element for your listener class.
    <listener>
         <listener-class>mypackage.MyServletContextListener</listener-class>
    </listener>
    i hope these helps ;)

Maybe you are looking for

  • Duplicating the set-up of iTunes stored on an external hard drive to a new computer

    I need some help setting up iTunes on my new computer.  Currently I run iTunes off my hard drive with my itunes folder on an external hard disk(E:) (to save space on my main hard disk).  The itunes >Advanced>iTunes media folder location setting = E:\

  • Problem in executing the adobe form

    Hi, Using the SFP tcode i have createda an interface and a form for that interface. i have to import parameters from vbap table which i have mapped in the form..there is no problem while executing and activating the form... but while i am executing t

  • Any temporary solutions to the washed out colors issue?

    **Note: I posted this in the Boot Camp forum, but I received no response. So, I'll give this forum a try.** I have a question about Windows XP and washed out colors on the display. I hear that there are some display driver issues with the new unibody

  • Can I have parts of my iTunes library in different places?

    I'm thinking about upgrading to the new Retina MacBook Pro and the 256GB of storage isn't enough for me.  I'm going to get an external hard drive to put my iTunes media and keep backups on and I was wondering if I can have the movies (at least most o

  • Fixed sequence of columns in ALV

    Hi, I am using FM 'REUSE_ALV_GRID_DISPLAY' to display ALV output. There are 20 fields in report output. User wants that after display of ALV report, the sequence of first 2 columns should never be changed. However sequenece of other columns can be ch