Last time, we mastered some basic UI components and worked on how to add them to panels, organize their layout, and manage their events. Having covered all the basic techniques that we’ll need to get started with Java interface programming in our first article, Java's Basic User Interface Components, we will move on to some advanced UI components. Today, I’ll be covering scrolling lists, scrollbars, and canvases, and their functionality. It is amazing to see how many of complex tasks are simplified with the help of these advanced user interface components.
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.
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.