Java's Advanced User Interface Components - Canvases
(Page 4 of 4 )
Canvases are components that are primarily used as a place on an interface to display images and animation. Although you can draw on most AWT components, such as panels using the graphics methods we’ve learned about earlier, canvases do very little except let us to draw on them. Hence a
Canvas is a component that we can draw on. In order to use a canvas, we must create a subclass of the Canvas class. This subclass can handle any drawing that needs to take place on the canvas using the paint () method. Once the Canvas class has been created it can be called in the program by calling its constructor and adding the new Canvas object to the container. If we have a panel that doesn't need to do much except display images or animation, a canvas would be a preference as it makes a lighter-weight surface than a panel would.
To create a canvas, use the Canvas class and add it to a panel as you would any other component:
Canvas can = new Canvas(); add(can); The following example is an applet which helps to demonstrate a drawing on a canvas.
/*
<Applet code “CanvasTest.class”
Width = 20 Height = 200>
</applet>
*/
Import java.awt.*;
Public class CanvasTest extends java.applet.Applet
{
GridLayout gl = new GridLayout(1,1);
MyCanvas can = new MyCanvas();
Public void init()
{
setLayout(gl);
add(can);
}
Class MyCanvas extends java.awt.Canvas
{
public void paint(Graphic g)
{
g.setColor(Color.blue);
g.drawString(“Congratilations! We are seen a string drawn on a canvas”, 20, 20);
}
}
} Now we know how to paint a user interface onto a Java applet’s window and Java applications using the languages standard palette-the components of the Abstract Windowing toolkit. We will see a few more advanced UI components, like menus, popup menus, and dialogs, before we move into learning how to arrange these components together to form a whole interface.
| DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware. |