Scrigroup - Documente si articole

     

HomeDocumenteUploadResurseAlte limbi doc
AccessAdobe photoshopAlgoritmiAutocadBaze de dateCC sharp
CalculatoareCorel drawDot netExcelFox proFrontpageHardware
HtmlInternetJavaLinuxMatlabMs dosPascal
PhpPower pointRetele calculatoareSqlTutorialsWebdesignWindows
WordXml

AspAutocadCDot netExcelFox proHtmlJava
LinuxMathcadPhotoshopPhpSqlVisual studioWindowsXml

Creating windows and applets

java



+ Font mai mare | - Font mai mic



Creating windows
and applets

The original design goal of the graphical user interface (GUI) library in Java 1.0 was to allow the programmer to build a GUI that looks good on all platforms.

That goal was not achieved. Instead, the Java 1.0 Abstract Window Toolkit (AWT) produces a GUI that looks equally mediocre on all systems. In addition it's restrictive: you can use only four fonts and you cannot access any of the more sophisticated GUI elements that exist in your operating system (OS). The Java 1.0 AWT programming model is also awkward and non-object-oriented.



Much of this situation has been improved with the Java 1.1 AWT event model, which takes a much clearer, object-oriented approach, along with the introduction of Java Beans, a component programming model that is particularly oriented toward the easy creation of visual programming environments. Java 1.2 finishes the transformation away from the old Java 1.0 AWT by adding the Java Foundation Classes (JFC), the GUI portion of which is called "Swing." These are a rich set of easy-to-use, easy-to-understand Java Beans that can be dragged and dropped (as well as hand programmed) to create a GUI that you can (finally) be satisfied with. The "revision 3" rule of the software industry (a product isn't good until revision 3) seems to hold true with programming languages as well.

One of Java's primary design goals is to create applets, which are little programs that run inside a Web browser. Because they must be safe, applets are limited in what they can accomplish. However, they are a powerful tool in supporting client-side programming, a major issue for the Web.

Programming within an applet is so restrictive that it's often referred to as being "inside the sandbox," since you always have someone - the Java run-time security system - watching over you. Java 1.1 offers digital signing for applets so you can choose to allow trusted applets to have access to your machine. However, you can also step outside the sandbox and write regular applications, in which case you can access the other features of your OS. We've been writing regular applications all along in this book, but they've been console applications without any graphical components. The AWT can also be used to build GUI interfaces for regular applications.

In this chapter you'll first learn the use of the original "old" AWT, which is still supported and used by many of the code examples that you will come across. Although it's a bit painful to learn the old AWT, it's necessary because you must read and maintain legacy code that uses the old AWT. Sometimes you'll even need to write old AWT code to support environments that haven't upgraded past Java 1.0. In the second part of the chapter you'll learn about the structure of the "new" AWT in Java 1.1 and see how much better the event model is. (If you can, you should use the newest tools when you're creating new programs.) Finally, you'll learn about the new JFC/Swing components, which can be added to Java 1.1 as a library - this means you can use the library without requiring a full upgrade to Java 1.2.

Most of the examples will show the creation of applets, not only because it's easier but also because that's where the AWT's primary usefulness might reside. In addition you'll see how things are different when you want to create a regular application using the AWT, and how to create programs that are both applets and applications so they can be run either inside a browser or from the command line.

Please be aware that this is not a comprehensive glossary of all the methods for the described classes. This chapter will just get you started with the essentials. When you're looking for more sophistication, make sure you go to your information browser to look for the classes and methods that will solve your problem. (If you're using a development environment your information browser might be built in; if you're using the Sun JDK then you use your Web browser and start in the java root directory.) Appendix F lists other resources for learning library details.

Why use the AWT?

One of the problems with the "old" AWT that you'll learn about in this chapter is that it is a poor example of both object-oriented design and GUI development kit design. It throws us back into the dark ages of programming (some suggest that the 'A' in AWT stands for "awkward," "awful," "abominable," etc.). You must write lines of code to do everything, including tasks that are accomplished much more easily using resources in other environments.

Many of these problems are reduced or eliminated in Java 1.1 because:

The new AWT in Java 1.1 is a much better programming model and a significant step towards a better library. Java Beans is the framework for that library.

GUI builders" (visual programming environments) will become de rigeur for all development systems. Java Beans and the new AWT allow the GUI builder to write code for you as you place components onto forms using graphical tools. Other component technologies such as ActiveX will be supported in the same fashion.

So why learn to use the old AWT? "Because it's there." In this case, "there" has a much more ominous meaning and points to a tenet of object-oriented library design: Once you publicize a component in your library, you can never take it out. If you do, you'll wreck somebody's existing code. In addition, there are many existing code examples out there that you'll read as you learn about Java and they all use the old AWT.

The AWT must reach into the GUI components of the native OS, which means that it performs a task that an applet cannot otherwise accomplish. An untrusted applet cannot make any direct calls into an OS because otherwise it could do bad things to the user's machine. The only way an untrusted applet can access important functionality such as "draw a window on the screen" is through calls in the standard Java library that's been specially ported and safety checked for that machine. The original model that Sun created is that this "trusted library" will be provided only by the trusted vendor of the Java system in your Web browser, and the vendor will control what goes into that library.

But what if you want to extend the system by adding a new component that accesses functionality in the OS? Waiting for Sun to decide that your extension should be incorporated into the standard Java library isn't going to solve your problem. The new model in Java 1.1 is "trusted code" or "signed code" whereby a special server verifies that a piece of code that you download is in fact "signed" by the stated author using a public-key encryption system. This way, you'll know for sure where the code comes from, that it's Bob's code and not just someone pretending to be Bob. This doesn't prevent Bob from making mistakes or doing something malicious, but it does prevent Bob from shirking responsibility - anonymity is what makes computer viruses possible. A digitally signed applet - a "trusted applet" - in Java 1.1 can reach into your machine and manipulate it directly, just like any other application you get from a "trusted" vendor and install onto your computer.

But the point of all this is that the old AWT is there. There will always be old AWT code floating around and new Java programmers learning from old books will encounter that code. Also, the old AWT is worth studying as an example of poor library design. The coverage of the old AWT given here will be relatively painless since it won't go into depth and enumerate every single method and class, but instead give you an overview of the old AWT design.

The basic applet

Libraries are often grouped according to their functionality. Some libraries, for example, are used as is, off the shelf. The standard Java library String and Vector classes are examples of these. Other libraries are designed specifically as building blocks to build other classes. A certain class of library is the application framework, whose goal is to help you build applications by providing a class or set of classes that produces the basic behavior that you need in every application of a particular type. Then, to customize the behavior to your own needs you inherit from the application class and override the methods of interest. The application framework's default control mechanism will call your overridden methods at the appropriate time. An application framework is a good example of "separating the things that change from the things that stay the same," since it attempts to localize all the unique parts of a program in the overridden methods.

Applets are built using an application framework. You inherit from class Applet and override the appropriate methods. Most of the time you'll be concerned with only a few important methods that have to do with how the applet is built and used on a Web page. These methods are:

Method

Operation

init( )

Called when the applet is first created to perform first-time initialization of the applet

start( )

Called every time the applet moves into sight on the Web browser to allow the applet to start up its normal operations (especially those that are shut off by stop( )). Also called after init( ).

paint( )

Part of the base class Component (three levels of inheritance up). Called as part of an update( ) to perform special painting on the canvas of an applet.

stop( )

Called every time the applet moves out of sight on the Web browser to allow the applet to shut off expensive operations. Also called right before destroy( ).

destroy( )

Called when the applet is being unloaded from the page to perform final release of resources when the applet is no longer used

Consider the paint( ) method. This method is called automatically when the Component (in this case, the applet) decides that it needs to update itself - perhaps because it's being moved back onto the screen or placed on the screen for the first time, or perhaps some other window had been temporarily placed over your Web browser. The applet calls its update( ) method (defined in the base class Component), which goes about restoring everything, and as a part of that restoration calls paint( ). You don't have to override paint( ), but it turns out to be an easy way to make a simple applet, so we'll start out with paint( ).

When update( ) calls paint( ) it hands it a handle to a Graphics object that represents the surface on which you can paint. This is important because you're limited to the surface of that particular component and thus cannot paint outside that area, which is a good thing or else you'd be painting outside the lines. In the case of an applet, the surface is the area inside the applet.

The Graphics object also has a set of operations you can perform on it. These operations revolve around painting on the canvas, so most of them have to do with drawing images, shapes, arcs, etc. (Note that you can look all this up in your online Java documentation if you're curious.) There are some methods that allow you to draw characters, however, and the most commonly used one is drawString( ). For this, you must specify the String you want to draw and its starting location on the applet's drawing surface. This location is given in pixels, so it will look different on different machines, but at least it's portable.

With this information you can create a simple applet:

//: Applet1.java

// Very simple applet

package c13;

import java.awt.*;

import java.applet.*;

public class Applet1 extends Applet

} ///:~

Note that applets are not required to have a main( ). That's all wired in to the application framework; you put any startup code in init( ).

To run this program you must place it inside a Web page and view that page inside your Java-enabled Web browser. To place an applet inside a Web page you put a special tag inside the HTML source for that Web page to tell the page how to load and run the applet. This is the applet tag, and it looks like this for Applet1:

<applet

code=Applet1

width=200

height=200>

</applet>

The code value gives the name of the .class file where the applet resides. The width and height specify the initial size of the applet (in pixels, as before). There are other items you can place within the applet tag: a place to find other .class files on the Internet (codebase), alignment information (align), a special identifier that makes it possible for applets to communicate with each other (name), and applet parameters to provide information that the applet can retrieve. Parameters are in the form

<param name=identifier value = 'information'>

and there can be as many as you want.

For simple applets all you need to do is place an applet tag in the above form inside your Web page and that will load and run the applet.

Testing applets

You can perform a simple test without any network connection by starting up your Web browser and opening the HTML file containing the applet tag. (Sun's JDK also contains a tool called the appletviewer that picks the <APPLET> tags out of the HTML file and runs the applets without displaying the surrounding HTML text. ) As the HTML file is loaded, the browser will discover the applet tag and go hunt for the .class file specified by the code value. Of course, it looks at the CLASSPATH to find out where to hunt, and if your .class file isn't in the CLASSPATH then it will give an error message on the status line of the browser to the effect that it couldn't find that .class file.

When you want to try this out on your Web site things are a little more complicated. First of all, you must have a Web site, which for most people means a third-party Internet Service Provider (ISP) at a remote location. Then you must have a way to move the HTML files and the .class files from your site to the correct directory (your WWW directory) on the ISP machine. This is typically done with a File Transfer Protocol (FTP) program, of which there are many different types freely available. So it would seem that all you need to do is move the files to the ISP machine with FTP, then connect to the site and HTML file using your browser; if the applet comes up and works, then everything checks out, right?

Here's where you can get fooled. If the browser cannot locate the .class file on the server, it will hunt through the CLASSPATH on your local machine. Thus, the applet might not be loading properly from the server, but to you it looks fine because the browser finds it on your machine. When someone else logs in, however, his or her browser can't find it. So when you're testing, make sure you erase the relevant .class files on your machine to be safe.

One of the most insidious places where this happened to me is when I innocently placed an applet inside a package. After uploading the HTML file and applet, it turned out that the server path to the applet was confused because of the package name. However, my browser found it in the local CLASSPATH. So I was the only one who could properly load the applet. It took some time to discover that the package statement was the culprit. In general, you'll want to leave the package statement out of an applet.

A more graphical example

The example above isn't too thrilling, so let's try adding a slightly more interesting graphic component:

//: Applet2.java

// Easy graphics

import java.awt.*;

import java.applet.*;

public class Applet2 extends Applet

} ///:~

This puts a box around the string. Of course, all the numbers are hard-coded and are based on pixels, so on some machines the box will fit nicely around the string and on others it will probably be off, because fonts will be different on different machines.

There are other interesting things you can find in the documentation for the Graphic class. Any sort of graphics activity is usually entertaining, so further experiments of this sort are left to the reader.

Demonstrating
the framework methods

It's interesting to see some of the framework methods in action. (This example will look only at init( ), start( ), and stop( ) because paint( ) and destroy( ) are self-evident and not so easily traceable.) The following applet keeps track of the number of times these methods are called and displays them using paint( ):

//: Applet3.java

// Shows init(), start() and stop() activities

import java.awt.*;

import java.applet.*;

public class Applet3 extends Applet

public void start()

public void stop()

public void paint(Graphics g)

} ///:~

Normally when you override a method you'll want to look to see whether you need to call the base-class version of that method, in case it does something important. For example, with init( ) you might need to call super.init( ). However, the Applet documentation specifically states that the init( ), start( ), and stop( ) methods in Applet do nothing, so it's not necessary to call them here.

When you experiment with this applet you'll discover that if you minimize the Web browser or cover it up with another window you might not get calls to stop( ) and start( ). (This behavior seems to vary among implementations; you might wish to contrast the behavior of Web browsers with that of applet viewers.) The only time the calls will occur is when you move to a different Web page and then come back to the one containing the applet.



It is assumed that the reader is familiar with the basics of HTML. It's not too hard to figure out, and there are lots of books and resources.

Because the appletviewer ignores everything but APPLET tags, you can put those tags in the Java source file as comments:
// <applet code=MyApplet.class width=200 height=100></applet>
This way, you can run 'appletviewer MyApplet.java ' and you don't need to create tiny HTML files to run tests.



Politica de confidentialitate | Termeni si conditii de utilizare



DISTRIBUIE DOCUMENTUL

Comentarii


Vizualizari: 608
Importanta: rank

Comenteaza documentul:

Te rugam sa te autentifici sau sa iti faci cont pentru a putea comenta

Creaza cont nou

Termeni si conditii de utilizare | Contact
© SCRIGROUP 2024 . All rights reserved