Home > Articles > Programming > Graphic Programming

  • Print
  • + Share This
This chapter is from the book

Rendering on Components

Any object derived from the Component class has a Graphics object that can be used to render graphics onto it. This means that the developer can render high impact graphics on all types of buttons, canvases, and check boxes. Basically, all the user interface objects have an accessible Graphics object that can be cast as a Graphics2D object and used by Java 2D.

Scaling to the Component's Size

So far, the examples have been deficient because they don't take the component size into account when drawing. It is obviously good programming practice to determine the Component's width and height and then scale the drawing accordingly. This can be done by using the Component's getSize() method. Scaling is used in the comprehensive example at the end of this chapter.

As an example of the important concept of drawing on Components, let's go back to our BasicRecipeJ2D program. Here we will replace the inner class, myCustomCanvas, with myCustomButton, an inner class extending JButton. Also, note that we choose to use a GradientPaint object instead of the Color object. Nonetheless, the steps are the same and the result is a custom rendered button.

class myCustomButton extends JButton {
  public void paint(Graphics g) {
// step one of the recipe; cast Graphics object as Graphics2D
     Graphics2D g2d = (Graphics2D) g;

    //make a GradientPaint object going 
    //from blue to green across from top left to
    //bottom right

     GradientPaint gp = new GradientPaint(0, 0, Color.blue,
                       this.getSize().width/20,
                       this.getSize().height/20,     
                       Color.green, true);

     // step two-set the graphics context
    g2d.setPaint(gp); //setting context

    //step three-render something--
      g2d.fill(new Rectangle2D.Float(0.0f,0.0f,75.0f,75.0f));
   } //end paint() method
} //end myCustomButton class
  • + Share This
  • 🔖 Save To Your Account