Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In swing-java, where does the Graphics instance come from?

When an update request is delivered to swing (either system triggered e.g. because of a resize or a block by another window, or app-triggered e.g. by a call to repaint() method), how is this request actually handled? What procedure takes place in that RepaintManager thing?

like image 643
Untitled Avatar asked May 11 '12 16:05

Untitled


People also ask

What is Graphics in Java Swing?

A Graphics object encapsulates state information needed for the basic rendering operations that Java supports. This state information includes the following properties: The Component object on which to draw. A translation origin for rendering and clipping coordinates.

How is a Graphics object created in Java?

You get the graphics object from a component via Component#getGraphics() method. In your particular case I think repaint() is all you need!! Show activity on this post. You don't, you use getGraphics, but, if you really want to initialize it, then type new Graphics(){}; And have fun filling all the abstract methods.

How does Graphics work in Java?

You don't have to create an instance of Graphics in order to draw something in your applet; in your applet's paint() method , you are given a Graphics object. By drawing on that object, you draw onto your applet and the results appear on screen. The Graphics class is part of the java.

How do you create a new instance of a Graphics class?

Because the Graphics class is an abstract base class, it cannot be instantiated directly. An instance is typically created by a component, and handed to the program as an argument to a component's update() and paint() methods. These two methods, along with the repaint() method, are discussed in the next section.


1 Answers

From your comment:

Do you know what happens in peer.getGraphics()?

That depends on which peer implementation is used.

One implementation is WComponentPeer (used when running on Windows), which seems to use two ways for getting the Graphics object:

  1. If the component has a parent of type Window (or is one itself) which in turn has a back buffer immage associated, that image's Graphics object is returned. This depends on the type of image but is most likeley a SunGraphics2D instance, created in createGraphics().

  2. Otherwise a ScreenUpdateManager instance is retrieved and createGraphics(...) is called on it which in turn returns a new SunGraphics2D instance.

Please note that this is just one possible way and it highly depends on the OS, the JVM and UI toolkit used.

like image 115
Thomas Avatar answered Oct 28 '22 14:10

Thomas