Thursday, 14 May 2015

Canvases in Java

A canvas is an empty space-a starting point for complex interface elements such as a picture button. A canvas is a place to draw. You use it instead of just drawing to a panel, as in an applet, so you can take advantage of the Layout Manager's capability to keep your interface machine- independent.

Listing 17.25. Drawing to the screen and to a canvas.
import java.awt.*;
import java.applet.Applet;


public class canvas_example extends Applet
{
    drawing_area drawing;
    Graphics drawing_graphics;

    public void init()
    {
        //Don't need to do this but we don't want the Canvas
        //being resized by the
        //Layout Manager. Layout Managers are discussed later in this chapter.
        setLayout(null);
        drawing = new drawing_area();
        add(drawing);

    }
    public void paint(Graphics g)
    {
        //This is just here to show that you can combine direct drawing to
        //the applet panel with Canvases
        g.drawString("Hello, World!", 25, 125 );

    }
}
//Can't have more than one public class in a source file but
//you can have several
//non-public ones
class drawing_area extends Canvas {
    Font my_font;

    drawing_area() {
        //set up a font for this Canvas to use
        my_font = new Font("TimesRoman", Font.BOLD,16);
        //set the size of the Canvas
        resize(100,100);
    }

    public void paint(Graphics g) {
        //By overriding the paint method you can control what is
        //drawn in a canvas. If you want to avoid flicker you might
        //also want to override the update method as discussed in the
        //animation section.
        //Fill a rectangle with the default color, black
        g.fillRect(0,0,100,100);
        //set the foreground color to white so we can read the text
        g.setColor(Color.white);
        g.setFont(my_font);
        g.drawString("this is a test", 10,50);
        //Be careful and reset the color or the next time paint is called the
        //rectangle will be filled with white and the text will be invisible
        g.setColor(Color.black);
    }
}

No comments:

Post a Comment