分享
 
 
 

Java[tm] Programming FAQs

王朝厨房·作者佚名  2007-01-05
窄屏简体版  字體: |||超大  

Java[tm] Programming Clected FAQs

Java[tm] Programming FAQs

How can you sort an array of elements according to a specific ordering criteria?

How do you convert a string representation of a date to an instance of java.sql.Date?

Also how do you convert an instance from java.util.Date to java.sql.Date?

What are the most common reasons for a java.util.MissingResourceException being thrown when using java.util.ResourceBundle.getBundle(String s, Locale locale)?

How can an unsigned applet retrieve a file from the same web server that it was downloaded from?

How do you transfer a file between a server and client over TCP/IP using sockets?

mySQL will not accept strings with single quotes. How can I place a string with a single quote into a mySQL field?

How do you transfer an image from a server to an unsigned applet client over socket connection?

A container has several sub components. How can a subcomponent get the focus when the top-level container is first opened?

How do you make images appear on buttons?

How do you load an image into an unsigned applet from the same location as that from which the applet was downloaded?

I have a problem when casting arrays...

How do you explicitly load classes when you do not have the fully qualified name for those classes?

How do you use COM components in Java programs?

How does the server know when a client disconnects from the server socket?

How do you convert a string to a byte array and visa versa?

How do you remove all white space in a string?

What is the cause of the following error: "Failed to load Main-Class manifest attribute from my.jar" when using JDK version 1.2?

How do you print using AWT JDK version 1.1 and JDK version 1.2?

I am creating a query string to be executed by the underlying mySQL database...

When printed, the following arithmetic equation only prints one decimal place after the point. How can it print out more?

I am using Process.waitFor() to force my application written for the Java platform to wait until the native process has finished...

In a program developed in the Java[tm] programming language, how do you redirect any error messages to a file instead of standard output?

How do you pass form information between an HTML page and an applet using the JavaScript[tm] programming language?

Where are the sun.net.ftp.* classes and when should I use them?

How can I get Technical support?

We want to hear from you! Please send us your FEEDBACK.

The following responses to Frequently Asked Questions (FAQs) may contain actual software programs in source code form. This source code is made available for developers to use as needed, pursuant to the terms and conditions of this license.

1. How can you sort an array of elements according to a specific ordering criteria? For example the set of elements {123AA, AB123, A3123, 32JDS} should be sorted where elements beginning with letters are placed before those beginning with numbers.

The method Arrays.sort(Object o) from java.util library will sort any set of objects according to the object’s natural ordering. For the example given in the question, the objects to be sorted are strings. The natural ordering of strings is lexicographical. The comparison of two strings is achieved by comparing the corresponding characters at each character index. The unicode value of each character is used for comparison to determine if one character is ’less’ than, ’equal’ to or ’greater’ than the other. For example the string, lad would come before let because the unicode value of ’a’ (0x61) is less than the unicode value of ’e’ (0x61). Literals representing numbers have a lower unicode value than those representing alphabetical letters. Hence Arrays.sort(Object o) will place elements with leading numbers before letters. For the example given the elements will be sorted in the order: 123AA, 32JDS, A3123, AB123.

If you want to ’override’ the natural order and define a total order then you need to create a class that implements the Comparator interface, and pass this class as an argument to the method, Arrays.sort(Object o, Comparator c). A class that implements the Comparator interface must define one method, public int compare(Object o1, Object o2). Compare will return 1, if the first object o1 precedes o2, otherwise -1. If the two objects are equal then 0 is returned. Testing for equality should not contradict the semantics of the equals() method.

Back to Top

2. How do you convert a string representation of a date to an instance of java.sql.Date? Also how do you convert an instance from java.util.Date to java.sql.Date?

The following is a program that will take a string representation of a date and convert it to java.util.Date using SimpleDateformat.parse(String s). Java.util.Date is then converted into the time in milliseconds from Jan 1 1970 00:00GMT, using Date.getTime(). This time is passed to the constructor of java.sql.Date to produce a corresponding java.sql.Date object.

//Given a date convert this to sql.Date

public java.sql.Date convertDate2Sql(java.util.Date d){

long time = d.getTime();

return(new java.sql.Date(time));

}

//The parameter string must be compatiable with the format of df i.e.

//"yyyy/MM/dd" otherwise a java.text.ParseException thrown.

public java.sql.Date convertString2Date(String s) throws ParseException{

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

java.util.Date d = df.parse(s);

return(convertDate2Sql(d));

}

Dates can also be represented in databases by java.sql.Timestamp objects. The Java.sql.Timestamp class provides a wrapper around a java.util.Date object. Java.sql.Timestamp is the Java representation of the SQL TIMESTAMP type.

Public java.sql.Timestamp convertTimeStamp(String s) throws ParseException {

SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd");

java.util.Date d = df.parse(s);

long time = d.getTime();

return(new TimeStamp(time));

}

Back to Top

3. What are the most common reasons for a java.util.MissingResourceException being thrown when using java.util.ResourceBundle.getBundle(String s, Locale locale)?

Reason 1: You need to create a ResourceBundle class for each locale that you wish to support. You also need to provide a default ResourceBundle, which will be used if no appropriate ResourceBundle class for a locale can be found. For example, you have created the ResourceBundle classes: Meals_fr_FR, Meals_db and Meals_en with a default ResourceBundle class, Meals. A java.util.MissingResourceException is thrown if for a given locale, you cannot find the nearest matching resource bundle for that locale, and you have failed to define a default ResourceBundle class.

If a ResourceBundle does not exist for a specific locale, then getBundles will find the nearest match. For instance, if you want to find Meals_fr_FR_UNIX and the default locale is en_GB, then getBundle will look for ResourceBundles in the following order:

Meals_fr_FR_UNIX

Meals_fr_FR

Meals_fr

Meals_en_GB

Meals_en

Meals

GetBundle will look and use ResourceBundles in the default locale before using the default ResourceBundle class.

Reason 2: An exception will be thrown if you are working solely with property resource bundles (all bundles are represented by underlying text files) and you do not append .properties extension to the file names.

Reason 3: If you pass in the name of the bundle with the .properties extension in the string argument of java.util.ResourceBundle getBundle(String s, Locale l) method. That is, ResourceBundle.getBundle("Meals.properties", Locale.ENGLISH) a java.util.MissingResourceException will be thrown.

Back to Top

4. How can an unsigned applet retrieve a file from the same web server that it was downloaded from?

An unsigned applet can open a connection only to the server from which it was downloaded, otherwise security exceptions will occur.

The following code creates an applet with a text area that sends an HTTP request to the web server to establish a connection with the file resource. Java.io.BufferedReader reads the file one line at a time, and each line is displayed on the applet’s text area.

import java.io.*;

import java.net.*;

import java.awt.*;

import java.applet.*;

public class CommApplet extends Applet{

TextArea ta;

public void init() {

ta = new TextArea(200, 600);

add(ta, BorderLayout.CENTER);

uploadFile();

}

public void uploadFile() {

try{

//The url is the location of the file

URL urlbase = new URL("http://servername/file");

URLConnection uconn = urlbase.openConnection();

InputStream uc = uconn.getInputStream();

BufferedReader buffIn =

new BufferedReader(new InputStreamReader(uc));

String s;

while((s = buffIn.readLine())!= null){

ta.append(s);

}

}catch(Exception e){

e.printStackTrace();

}

}//End of uploadFile

}

The html file:

<applet code="CommApplet.class"

width=400

height=50>

</applet>

Back to Top

5. How do you transfer a file between a server and client over TCP/IP using sockets?

The file is broken down into bytes in order to be transferred. The server reads the file into a byte array, and it is this byte array that is transferred. In this instance, java.io.RandomAccessFile is used to manipulate the file, but java.io.FileInputStream could also be used. The filename and size are transferred initially so that the client can set up its input buffer before the file content is sent.

Back to Top

6. mySQL will not accept strings with single quotes. How can I place a string with a single quote into a mySQL field?

You need to replace the "’" with the escape sequence, "\’". Two backslashes are needed as the first escapes the second. The following will parse a string looking for any problem characters. These problem characters are replaced in the string by some corresponding characters. All problem characters and their replacement characters are stored in the hashMap, replacePhrases.

/**

SetUp.

*/

import java.util.*;

....

Map replacePhrases=new HashMap();

replacePhrases.put("’", "\’");

public String parse(String input){

Iterator entryIt = replacePhrases.entrySet().iterator();

//Each problem character is used as a delimiter

//If the problem character is present in input string>

//then the string will be tokenized.

String output;

while(entryIt.hasNext()){

Map.Entry entry = (Map.Entry) entryIt.next();

StringTokenizer s = >

new StringTokenizer(input, (String)entry.getKey());

//If string tokenized, take the token before the problem

//character, concat with the replacement character and then

//concat the next token.

if(s.countTokens() > 1){

output = s.nextToken();

while(s.hasMoreTokens()){

output += (String)entry.getValue() + s.nextToken();

}

}

}

return output;

}

Back to Top

7. How do you transfer an image from a server to an unsigned applet client over socket connection? The code should be compatable with JDK[tm] version 1.1.

Here you will find code that is split into three main sections. The server, the applet client and the utility class, MyCanvas, to display the transferred image in the applet. The server class, Server.java is as in Q5. The applet client, CommApplet.java has the same code as Client.java in Q5, for retrieving the transferred image, but it also has additional code. CommApplet.java will retrieve the image as an array of bytes, and translate this into the object java.awt.Image. CommApplet.java creates a canvas of type MyCanvas.java which will hold the image and which adds the canvas to its display area. MyCanvas.java will use java.awt.MediaTracker to load the image correctly, and then draws the image onto the canvas. The MediaTracker tool is recommended for image loading. While the image is downloading, MediaTracker monitors the image’s status, which indicates the presence of any errors. MediaTracker will only complete when the image has downloaded successfully.

Back to Top

8. A container has several sub components. How can a subcomponent get the focus when the top-level container is first opened?

JPanel is the enclosing container. In this example you will find code where a Jbutton called but2, will have the focus whenever the container is first opened. In order to request the focus, the heavyweight container is retrieved using a call to getTopLevelAncestor(). A window listener is then attached to the top-level container and windowOpened is defined to request the focus for button, but2.

This code must be placed in addNotify() which overrides the corresponding method in JComponent. AddNotify() is called by the AWT event thread only when a component’s parent is created. Hence, it is safe for a subcomponent to reference its parent component at this point. The first line of addNotify()must call the overridden addNotify() for the code to work.

Back to Top

9. How do you make images appear on buttons?

Unfortunately AWT Buttons do not support images nor mnemonics. Only javax.swing.Button supports these features. To create an image on a button, type:

ImageIcon imageIcon = new ImageIcon("filename.gif");

JButton button = new JButton("ButtonName", imageIcon);

Back to Top

10. How do you load an image into an unsigned applet from the same location as that from which the applet was downloaded?

Use java.applet.Applet.getCodeBase() to give the directory location of the image, and then java.applet.Applet.getImage(String dir, String filename) to retrieve the image. Use java.awt.MediaTracker to load in the image correctly, and override the applet’s repaint method in order to display the image onto the applet. This solution has been proven to work on IE browsers.

/**

ImageApplet.java

**/

import java.awt.*;

import java.applet.*;

public class ImageApplet extends Applet{

private Image image;

public void init() {

//Retrieve Image

image = getImage(getCodeBase(), "javalogo52x88.gif");

//Load Image

MediaTracker tracker = new MediaTracker(this);

tracker.addImage(image, 0);

try{>

tracker.waitForAll();

}catch(InterruptedException e){}

}

public void repaint(Graphics g){

g.drawImage(image, 0, 0, this);

}

}

Back to Top

11. I have a problem when casting arrays. The following piece of code compiles fine but at run-time a java.lang.ClassCastException is thrown at line 4:

1: Object [] op = new Object[2];

2: op[0] = new String("hello");

3: op[1] = new String("goodbye");

4: String [] strArray = (String [])op;

I know that all elements in op are of type String, so why can I not cast op to an array of strings using the cast operator

(String [])? Is there away around this?

No compile time error results when the type of source variable, strArray is compatible with the cast operator, (String []). A runtime error results because the runtime type of the op’s element is java.lang.Object, as stated in line 1. The JVM[tm] software only allows the assignment between compatible types, so assignment from an object to string would violate the type system. If this assignment was permissible, the array would no longer hold homogeneous type elements; both object and string types could be stored, and upon deferencing the array, the true type of each element could not be determined.

Note that the following will both compile and run without errors:

1: Object [] op2 = new String[2];

2: op2[0] = new String("hello");

3: op2[1] = new String("goodbye");

4: String [] strArray = (String [])op2;

Here are two ways around this:

1. Use a java.util.Collection type to store the values, for example, ArrayList, Set, etc, and then use Object [] toArray(Object []) method where the parameter is the runtime type of the array. The JVM software is informed to treat the underlying array as having a runtime type as given by the parameter, even if the actual type is an incompatible type.

List list = new ArrayList();

list.add(new String ("hello"));

list.add(new String ("Goodbye"));

String [] strArray = (String [])list.toArray(new String[toArray.size()]);

2. Alternatively, use java.lang.System.arraycopy():

String [] strArray = new String[list.size];

System.arraycopy(list.toArray(), 0, strArray, 0, list.size());

Back to Top

12. How do you explicitly load classes when you do not have the fully qualified name for those classes?

ClassLoader.defineClass(String name, byte[], int start, int end) will convert a byte array into an instance of java.lang.Class. The name of the class is not needed so the string parameter can be null. In order to use defineClass you need to subclass java.lang.ClassLoader. This program will take a Java [tm] class file, read it into a byte array, and create an instance of the class. You can then use all methods in java.lang.Class to retrieve information about the newly constructed class.

Back to Top

13. How do you use COM components in Java programs?

You can use bridging software to use other vendors’ COM classes in your programs written for the Java Platform and to interface with third-party software. The bridging software you choose will need to suit the JVM software version you are using, as well as the application that you want to interface with. Following is a listing of bridging software:

JavaBeans Bridge for ActiveX

The bridge is now part of the Java Plug-in [tm] product.

Bridge2Java

J-Integra, belonging to Intrinsyc Software, Inc.

Documentation on using J-Integra found at Linar

Back to Top

14. How does the server know when a client disconnects from the server socket?

If a client closes its connection to the server correctly by using java.net.Socket.close(), then any subsequent sending of data over the input stream will result in a java.io.IOException on the server side. However, should the client not close down correctly because of network, hardware or OS failure, then the client socket is still open, and from the server perspective the client can still receive information. A good way to handle this scenario is to set a timeout limit on the socket connection, and poll the client with test messages. If the client does not acknowledge these messages within the timeout period, then the server can assume that the client is down, and then disconnect. Your client will need to be programmed to automatically return acknowledgments for all data transfers from the server.

Here you will find what the server should include.

Back to Top

15. How do you convert a string to a byte array and visa versa?

Java.lang.String has certain utilities to convert a string into a byte array and visa versa. A string can be converted correctly and fully into a byte array by using a character encoding such as UTF-8, US-ASCII. All the overloaded String.getBytes() methods will convert a string into a byte array. Some of these methods take an encoding identifier as an argument, while others take no arguments and will use the platform’s default encoding to convert the string.

A byte array can be converted into a string using the string constructor methods. Some take an encoding identifier, while others take none and use the platform’s default encoding. A listing of appropriate encoding identifiers is found at Character Encodings.

The following program does string to byte array conversion using the default platform encoding, and the UTF-8 character encoding.

public void converting(){

String str = new String("A" +"\u00fe"+"\u00f3"+"e");

System.out.println("String is "+ str);

try{

//Encode using US-ASCII format

//Create a byte array of str using the encoding UTF-8

byte [] usAsciiBytes = str.getBytes("UTF-8");

//To convert the byte array back into its String representation, create a new String passing in the

//character encoding and the byte array.

String conversion = new Str(usAsciiBytes, "UTF-8");

System.out.println("Byte [] -> String with UTF-8" + conversion);

System.out.println();

//Encode using platform’s default encoding.

byte [] defaultEncodingBytes = str.getBytes();

String defaultBytes = new String(defaultEncodingBytes);

System.out.println("Byte [] -> String with

DefaultEncoding"+defaultBytes);

}catch(UnsupportedEncodingException e){

e.printStackTrace();

}

}

Every Java JVM software implementation has a default character encoding which is dependent upon its locale and the underlying operating system. A list of supported encodings should be given in the release documentation of the JVM software implementation. All JVM software implementations should support certain encodings including UTF-8, US-ASCII. In the above program, if the US-ASCII encoding was used then the unicode literals would be represented as question marks in the byte array. Question marks are used to represent characters that are not supported by a given character encoding.

Back to Top

16. How do you remove all white space in a string?

Java.lang.String.trim() will remove all preceding and following whitespace around a string. In order to remove any intermediate whitespace you can use the following code. It will tokenize the string with a space, ’ ’ as the delimiter, and then construct the result with the tokens.

public void removeWhiteSpace(String s){

System.out.println(s);

String newStr = s.trim();

// ’\u0020’ is the unicode value for space, ’ ’

StringTokenizer st = new StringTokenizer(s, "\u0020");

String result = "";

while(st.hasMoreElements()){

String token = st.nextToken();

System.out.println("token:"+ token);

result+= token;

}

System.out.println("Result is"+ result);

}

Back to Top

17. What is the cause of the following error: "Failed to load Main-Class manifest attribute from my.jar" when using JDK version 1.2?

When using JDK version 1.2 or higher, you need to include a manifest file with a Main-Class header correctly set in any JAR files. The ’Main-class’ header should point to a java class with a main method. In your manifest file include the line:

Main-Class: MainFileName

The .class extension is omitted from the MainFileName.

You then want to merge the manifest file and the Java class file which has a main method, into a JAR file. For example for a manifest file called, mymanifest and a Java class file called MainFileName.class, you create a JAR file called my.jar by executing the following:

jar cmf mymanifest my.jar MainFileName.class

Back to Top

18. How do you print using AWT JDK version 1.1 and JDK version 1.2?

AWT JDK version 1.1

AWT components are drawn onto a special graphics object which refers to a printer. All components have a print(Graphics) and printAll(Graphics) method. These should be implemented to render an image of the component into the graphics object. In order to print, you need to implement the print/printAll method of a component, and construct a graphics object to represent the output on a page to be printed.

STEPS:

Get a reference to the systems Toolkit.

Retrieve an instance of PrintJob by invoking getPrintJob on the Toolkit class. A printJob controls the painting. You need to provide a reference to the frame that holds the components you want to print, and a title. The getPrintJob invokes a standard printing dialog box. The method will only return once the user has selected an option: print / cancel. If the user wants to print, then a non-null PrintJob is returned.

Retrieve the graphics object associated with the PrintJob. Use the various graphics methods to generate output.

One graphics object is associated with one page, once all components have been drawn to constitute one page, call Graphics.dispose().

Once all pages are created, call PrintJob.end() to spool the output to the printer.

Follwing is an example:

import java.awt.*;

import javax.swing.*;

import java.awt.event.*;

public class AWTPrint{

public static void main(String args[]){

final JFrame frame = new JFrame("AWTPrint");

final JTextField text = new JTextField("hello", 45);

Button b = new Button("Print");

frame.getContentPane().add(b, BorderLayout.NORTH);

frame.getContentPane().add(text, BorderLayout.CENTER);

b.addActionListener(

new ActionListener(){

public void actionPerformed(ActionEvent e){

Toolkit kit = ((Component) (e.getSource())).getToolkit();

PrintJob job = kit.getPrintJob(frame,"Printing", null);

if(job != null){

Graphics g = job.getGraphics();

g.setClip(new Rectangle(6,6,80*3, 80*3));

text.print(g);

g.setFont(new Font("Serif", Font.BOLD , 18));

g.dispose();

}

job.end();

}

});

frame.setVisible(true);

}

}

AWT JDK version 1.2

Printing in AWT JDK version 1.1 is relatively simple. In AWT JDK version 1.2, more printing functionality is provided.

STEPS:

The new printing mechanisms are in java.awt.print, so first you need to import this into your applications.

The component that you wish to print must implement the Printable Interface. The printable interface defines one method: public void print(Graphics g, PageFormat f, int pageindex). The method will render the image of this object onto the graphic object. Like AWT JDK version 1.1, the graphics object represents all output to be printed. A PageFormat object contains information about the page including margins and orientation. The page index indicates whether the requested page exists or not.

java.awt.print.PrinterJob is similar to java.awt.PrintJob in that it controls one printing process. Unlike java.awt.PrinterJob, the graphic object is supplied to a PrinterJob using the method setPrintable. You retrieve a PrinterJob from the static method PrinterJob.getPrinterJob().

You then have the option to set up a print dialog box using the boolean printDialog() method of PrinterJob. With AWT JDK version 1.1 dismissing the print dialog box is not an option. PrintDialog() returns null, if the request to print is cancelled. Otherwise it returns true.

You then use PrinterJob.setPrintable(Printable object) to associate the object you want to render for this print job.

To complete, you need to invoke PrinterJob.print(), with no arguments, to render the objects associated with this printer job and to spool the output to the printer.

Here you will find code that uses the printing mechanisms of AWT JDK version 1.2 to produce the same result as preceding code for AWT JDK version 1.1.

For more information on printing in AWT JDK version 1.2 see:

Printing

Back to Top

19. I am creating a query string to be executed by the underlying mySQL database. The string is made up of string literals concatenated with string references, for example:

String word = "Jumper";

String retrieveGreetings = "SELECT Price FROM Stockroom WHERE Clothing = "+word;

However, this statement , fails to be executed. Why?

When using a mySQL database, strings are represented by the type VARCHAR. A VARCHAR literal is represented as a sequence of characters in single quotes, such as ’Hello’.

You need to enclose the string reference with single quotes:

String retrieveGreetings = "SELECT Price FROM Stockroom WHERE Clothing =

’"+word+"’";

If you do not do this, the string is dereferenced as a column name which could be invalid.

Back to Top

20. When printed, the following arithmetic equation only prints one decimal place after the point. How can it print out more?

float fl = 54/7;

System.out.println(fl); //Prints 7.0

7.0 is printed because of binary numeric promotion and no explicit formatting. The loss of precision is because the result of the division is narrowed to an int. The numeric promotion rule states that the result type of an arithmetic expression is the same as the broadest type of its operands which in this case is int. When the integer result is assigned to the float reference it is then promoted to a float type, and hence the single decimal point is printed out. To maintain precision, you must inform the JVM software to do float/double division by attaching either the ’f’ or ’d’ flag to the expression. For example, float fl = 54/7f or double do = 45/6d.

The DecimalFormat class allows the developer to determine what level of precision should be printed. The DecimalFormat constructor takes a pattern which determines how numbers should be formatted. For example, if you want three decimal places after the point, you could do the following:

DecimalFormat df = new DecimalFormat("###.##");

System.out.println(df.format(fl)); //Prints 7.71

Back to Top

21. I am using Process.waitFor() to force my application written for the Java platform to wait until the native process has finished. However this does not happen. Why?

In order to wait for a subprocess to finish before your application proceeds, you should place waitFor() in a try/catch block and test that the process has terminated. A terminated process will return an exit code of 0. For example:

try {

if(process.waitFor() == 0) {

//By placing this in a condition, the java program is forced to wait

}

else

throw new Exception("Process failed to terminated correctly");

}catch(InterruptedException e){

System.out.println(e.getMessage());

}

However, this code may fail to work for some processes. The following is an excerpt from the API documentation on class Process:

"The Runtime.exec methods may not work well for special processes on certain native platforms, such as native windowing processes, daemonprocesses, Win16/DOS processes on Win32, or shell scripts. The created subprocess does not have its own terminal or console. All its standard io (i.e.stdin, stdout, stderr) operations will be redirected to the parent process through three streams (Process.getOutputStream(), Process.getInputStream(),Process.getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platformsonly provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock. "

Back to Top

22. In a program developed in the Java[tm] programming language, how do you redirect any error messages to a file instead of standard output?

The method, java.lang.System.setErr(PrintStream newErrorStream) reassigns the underlying "standard" error output stream to the PrintStream, newErrorStream. The PrintStream wraps a FileOutputStream to an output file.

import java.io.*;

public class SendingError {

public static void main(String args[]){

File out = new File("output.log");

try{

FileOutputStream fileOut = new FileOutputStream(out);

PrintStream outPrintStream = new PrintStream(fileOut);

System.setErr(outPrintStream);

//A test

throw new Exception("Problem");

}catch(Exception e){

e.printStackTrace();

}

}

}

Back to Top

23. How do you pass form information between an HTML page and an applet using the JavaScript[tm] programming language?

The following steps are a quick guide to using the JavaScript[tm] programming language with applets:

Create some interface or a set of public methods that are to be implemented by an applet. These methods are the only members of the applet that are accessible to the enclosing HTML page.

Give the embedded applet a name using the NAME variable of the APPLET tag.

To access the applet’s methods, JavaScript technology will use document.NAME.method.

Associated with every html page are two objects, ’document’ which refers to the entire page, and ’form’ which refers to all the form information in the <FORM></FORM> tags. In order to refer to labelled HTML components in the form, you need to use the notation, form.LABEL.

All JavaScript functions are enclosed in <SCRIPT></SCRIPT> tags.

Here you will find an example of an applet that is embedded in an HTML page. This page has a form component with subcomponents. The applet has three methods: setFormName, and setFormNumber which takes the input from the form and sets the corresponding variables of the applet, and getFormNumber which returns an integer to be displayed in HTML. In the HTML page, there is a corresponding JavaScript programming language function for each of the applet’s accessor methods. The HTML page has one drop down list which when selected will call the setFormNumber method; a textfield which when given input will call setFormName; and a button which when clicked upon will call getAppletNumber(); getAppletNumber() will then display its result in the textarea of the form. The applet will also display two redundant buttons.

You may notice in the method, setFormNumber takes a float object as its argument. The reason is that all JavaScript programming language numbers, regardless of type are converted to float objects when passed to any code developed in the Java programming language. JavaScript programming language string and booleans map straight to Java programming language string and boolean objects.

JavaScript technology is a Netscape created language. LiveConnect is a netscape technology which enables JavaScript technology and applets to communicate. Liveconnect is fully supported by them for all Navigator versions since version 3. There is limited support on Internet Explorer. For details on setting up Liveconnect, refer to [ 收藏此页到 VIVI | Younote | 365Key | Blogchina | POCO | 人人 | 亿友 | 我摘 | 和讯 | 拇指 | 天极 ]

 
 
 
免责声明:本文为网络用户发布,其观点仅代表作者个人观点,与本站无关,本站仅提供信息存储服务。文中陈述内容未经本站证实,其真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
2023年上半年GDP全球前十五强
 百态   2023-10-24
美众议院议长启动对拜登的弹劾调查
 百态   2023-09-13
上海、济南、武汉等多地出现不明坠落物
 探索   2023-09-06
印度或要将国名改为“巴拉特”
 百态   2023-09-06
男子为女友送行,买票不登机被捕
 百态   2023-08-20
手机地震预警功能怎么开?
 干货   2023-08-06
女子4年卖2套房花700多万做美容:不但没变美脸,面部还出现变形
 百态   2023-08-04
住户一楼被水淹 还冲来8头猪
 百态   2023-07-31
女子体内爬出大量瓜子状活虫
 百态   2023-07-25
地球连续35年收到神秘规律性信号,网友:不要回答!
 探索   2023-07-21
全球镓价格本周大涨27%
 探索   2023-07-09
钱都流向了那些不缺钱的人,苦都留给了能吃苦的人
 探索   2023-07-02
倩女手游刀客魅者强控制(强混乱强眩晕强睡眠)和对应控制抗性的关系
 百态   2020-08-20
美国5月9日最新疫情:美国确诊人数突破131万
 百态   2020-05-09
荷兰政府宣布将集体辞职
 干货   2020-04-30
倩女幽魂手游师徒任务情义春秋猜成语答案逍遥观:鹏程万里
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案神机营:射石饮羽
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案昆仑山:拔刀相助
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案天工阁:鬼斧神工
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案丝路古道:单枪匹马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:与虎谋皮
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:李代桃僵
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案镇郊荒野:指鹿为马
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:小鸟依人
 干货   2019-11-12
倩女幽魂手游师徒任务情义春秋猜成语答案金陵:千金买邻
 干货   2019-11-12
 
推荐阅读
 
 
 
>>返回首頁<<
靜靜地坐在廢墟上,四周的荒凉一望無際,忽然覺得,淒涼也很美
© 2005- 王朝網路 版權所有