Results 1 to 2 of 2
  1. #1
    carl is offline Member
    Join Date
    Jul 2007
    Posts
    35
    Rep Power
    0

    Default Draw on JPanel, Help

    Hi, I'm trying to draw using Graphics2D on a Java JPanel. Actually its a ImagePanel - a class I've extended from a JPanel, which just loads a jpeg into the panel. This part works fine....but then I want to draw on top of the JPanel, and its not showing what I'm drawing. Here is the code for the paint in the jpanel

    Java Code:
    protected void paintComponent(Graphics g)
        {
            System.out.println("in paintstuff");
            super.paintComponent(g);
            if(text)
            {
                System.out.println("Here");
                Graphics2D g2 = (Graphics2D)image.getGraphics();
                g2.drawString(textString, lastX, lastY);
                text = false;
            }
    
            if (image == null) return;
    
            switch (style)
            {
                case TILED:
                    drawTiled(g);
                    break;
    
                case SCALED:
                    Dimension d = getSize();
                    g.drawImage(image, 0, 0, d.width, d.height, null);
                    break;
    
                case ACTUAL:
                    drawActual(g);
                    break;
            }
    
    
        }
    Its definitely getting into the if(text) clause, and I've tried writing directly to the g Graphics, but that doesn't work either. "image" is just a BufferedImage storing the JPEG and whatever else I want to have drawn.

    Thanks.

  2. #2
    hardwired's Avatar
    hardwired is offline Senior Member
    Join Date
    Jul 2007
    Posts
    1,576
    Rep Power
    9

    Default

    Here you are drawing on the image
    Java Code:
    Graphics2D g2 = (Graphics2D)image.getGraphics();
    g2.drawString(textString, lastX, lastY);
    To draw on the JPanel, use the panels graphic context,
    not the graphic context of the image as you did above.
    Java Code:
    protected void paintComponent(Graphics g)
        {
            super.paintComponent(g);
            Graphics2D g2 = (Graphics2D)g;
            g2.drawString(textString, lastX, lastY);

Similar Threads

  1. Trying to use Graphics draw methods
    By Lang in forum SWT / JFace
    Replies: 5
    Last Post: 03-26-2008, 06:49 AM
  2. Draw an arrow
    By Albert in forum SWT / JFace
    Replies: 3
    Last Post: 02-01-2008, 09:11 AM
  3. help me draw... please...
    By kureikougaiji in forum New To Java
    Replies: 1
    Last Post: 01-28-2008, 01:22 PM
  4. how to draw in Java
    By Heather in forum AWT / Swing
    Replies: 2
    Last Post: 07-12-2007, 12:01 PM
  5. How to draw a thick line
    By johnt in forum Java 2D
    Replies: 1
    Last Post: 05-31-2007, 05:27 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
  •