Sunday 28 February 2016

The paintComponent() Method

The source for our HelloComponent class defines a method, paintComponent(), that overrides the paintComponent() method of the JComponent class:

 public void paintComponent( Graphics g ) {  
 g.drawString( "Hello, Java!", 125, 95 );  
 }  
The paintComponent() method is called when it’s time for our example to draw itself on the screen. It takes a single argument, a Graphics object, and doesn’t return any type of value (void) to its caller. Modifiers are keywords placed before classes, variables, and methods to alter their accessibility, behavior, or semantics. paintComponent() is declared as public, which means it can be invoked (called) by methods in classes other than HelloComponent. In this case, it’s the Java windowing environment that is calling our paintComponent() method. A method or variable declared as private is accessible only from its own class. The Graphics object, an instance of the Graphics class, represents a particular graphical drawing area. (It is also called a graphics context.) It contains methods that can be used to draw in this area, and variables that represent characteristics such as clipping or drawing modes. The particular Graphics object we are passed in the paintCompo nent() method corresponds to our HelloComponent’s area of the screen, inside our frame. The Graphics class provides methods for rendering shapes, images, and text. In Hello Component, we invoke the drawString() method of our Graphics object to scrawl our message at the specified coordinates. As we’ve seen earlier, we access a method of an object by appending a dot (.) and its name to the object that holds it. We invoked the drawString() method of the Graphics object (referenced by our g variable) in this way:
 g.drawString( "Hello, Java!", 125, 95 ); 
It may be difficult to get used to the idea that our application is drawn by a method that is called by an outside agent at arbitrary times. How can we do anything useful with this? How do we control what gets done and when? These answers are forthcoming. For now, just think about how you would begin to structure applications that respond on command instead of by their own initiative.

0 comments:

Post a Comment