Skip to Main Content

Java SE (Java Platform, Standard Edition)

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

What is the getGraphics() method used for?

camickrNov 5 2007 — edited Nov 5 2007
We (hopefully) all know that custom painting should always be done in the paintComponent() method. If you attempt to use the getGraphics() method to do custom painting you will lose all the painting the next time the RepaintManager decides the component needs to be repainted.

However, what happens if you try to use the getGraphics() method inside the paintComponent() method. Well the answer is it doesn't work either. I just answered a question on the forum relating to this and am curious as to why it doesn't work.

First of all I noticed that the two graphics object are different.

Secondly I noticed that the Graphics object from the getGraphics() method doesn't have a clip bounds set. However, setting the clip bounds doesn't do anything either.

I also noticed that if you drag the frame width as small as you can and then continue to drag it wider (without releasing the mouse) the second two messages will paint.

So, if you can't use the getGrapics() method outside the paintComponent() method and you can't use it inside, what is it used for? Anybody have any ideas?
import java.awt.*;
import javax.swing.*;

public class GraphicsTest extends JFrame
{
    public GraphicsTest() {

        JPanel p = new JPanel()
        {
            public void paintComponent(Graphics g)
            {
                super.paintComponent(g);

                Graphics g2 = getGraphics();

                System.out.println( g == g2);

                System.out.println("before: "
                    + g.getClipBounds() + " : " + g2.getClipBounds());

                g.drawString("This works", 0, 50);

                g2.drawString("This doesn't work", 0, 100);

                g2.setClip(0, 0, getSize().width, getSize().height);
                System.out.println("after : "
                    + g.getClipBounds() + " : " + g2.getClipBounds());
                g2.drawString("This doesn't work either", 0, 150);
            }
        };
        p.setPreferredSize(new Dimension(200, 200));
        getContentPane().add( p );
    }

    public static void main(String[] args)
    {
        GraphicsTest frame = new GraphicsTest();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.pack();
        frame.setLocationRelativeTo( null );
        frame.setVisible(true);
    }
}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Dec 3 2007
Added on Nov 5 2007
3 comments
710 views