Lab 1 CS &141 Lab #1—Introduction to Java Applets and Applications Objectives: Introduce Java’s two kinds of programs: applications and applets. Walkthrough the cycle of editing, compiling, debugging, and executing an application. Use the NetBeans IDE to create and execute a Java program. Note: Before you can compile and test your own Java applets you need two things: the Java j2se6.0 (or later) compiler and a Java-aware browser (Mozilla, Opera, Avant or IE will do). The Java compiler comes with quite a bit of documentation covering the language and the class hierarchies shipped with the language, and this documentation will be essential reference material for you. The compiler package also contains quite a bit of sample code that can also be useful. Problem Statement I: View an existing applet. 1. Locate with Windows Explorer the Fractal folder (you should have a copy of this folder and its content int Lab #1 Folder). 2. Open the Fractal folder (double-click on it or right-mouse it and select Open). 3. Double click on the example1.html file—voilá! Don’t worry at this stage what happened—all you need to know now is that the fractal applet written in Java is executing within a browser (Netscape, in this case—see below). For the curious, and impatient ones, Netscape is using its Java Virtual Machine program to interpret the bytecode of the compiled file CLSFractal.class. ECC 1 © Niko Čulevski Lab 1 CS &141 4. Select View and Page Source for the code. Again, don’t be concern about the details of this HTML file; just notice the <applet> and </applet> tags for including a Java *.class file. <html> <head> <title>Fractals 1.1</title> </head> <body> <h1>Fractals 1.1</h1> <hr> <applet codebase="." applet code="CLSFractal.class" width=500 height=120> <param name=level value="5"> <param name=rotangle value="45"> <param name=succ1 value="F-F++F-F"> <param name=delay value="1000"> <param name=axiom value="F"> <param name=normalizescale value="true"> <param name=incremental value="true"> <param name=pred1 value="F"> <param name=border value="2"> <param name=startangle value="0"> alt="Your browser understands the &lt;APPLET&gt; tag but isn't running the applet, for some reason." Your browser is completely ignoring the &lt;APPLET&gt; tag! </applet> <hr> <a href="CLSFractal.java">The source</a>. </body> </html> 5. Repeat steps 1-4 for the TicTacToe.html file. ECC 2 © Niko Čulevski Lab 1 CS &141 Problem Statement II: Create a Java application that displays “Hello World!” at the command prompt using a simple text editor. 1. Open Notepad (Start, Programs, Accessories, Notepad) or any other text editor and type the following code exactly as it appears below (pay attention to uppercase/lowercase, punctuation, etc.): public class HelloWorld { public static void main(String args[ ]) { System.out.println(“Hello, World!”); } } 2. Save your file with the name HelloWorld.java on drive C:\Temp or any other suitable drive. 3. Open a DOS command window (Start, Run, cmd). 4. Change the directory to C:\Temp (or whatever drive you chose in step #2). 5. Compile your program by typing javac HelloWorld.java 6. If the compilation goes well, the system should respond within few seconds with another prompt (and no errors!). Check your directory for the new file names HelloWorld.class. This is the bytecode that the JVM will use to execute the program. (Note that it is about four times the size of your source code.) 7. Execute the program by typing java HelloWorld 8. Troubleshooting. Here is a partial list of typical problems that prevent you from completing steps 1-7 successfully. ECC 3 © Niko Čulevski Lab 1 CS &141 • Syntax errors. You did not type the code exactly as specified. Check your code and pay attention to every character—this includes lower/upper case, punctuation, etc. Correct these errors, resave the file, recompile it and run it again. • Don’t copy and paste the code above—you will get an error about the quotes (they are not the same in Word and Notepad). • File errors. The file name containing the code must be the same as the class name with java extension, namely, HelloWorld.java (Java is case sensitive—pay aqttention to capital letters). Make sure that the file HelloWorld.class shows up in drive C:\Temp after the compilation. • Path errors. If the operating system cannot execute javac it could be that the OS does not know where it is installed (or the JDK was not installed correctly). You might need to modify your system PATH variable to include C:\Program Files\Java\jdk1.6.0_06\bin entry (or other version), assuming JDK was installed on the C drive. You can verify the PATH by typing path at the DOS prompt and you can add the C:\Program Files\Java\jdk1.6.0_06\bin to PATH by typing at the command prompt set path=C:\Program Files\Java\jdk1.6.0_06\bin;%path% Problem Statement III: Create a Java applet that displays “Welcome to Java Programming!” using the NetBeans IDE. 1. Create a java source file named Welcome.java and save it in a folder named Lab 1 in C:\Temp\Lab 1. Here is the content of that file: /** * * * */ A first program in Java Welcome.java @author nculevsk Created on April 4 27, 2009, 2:40 PM import java.applet.Applet; import java.awt.Graphics; // import Applet class // import Graphics class public class Welcome extends Applet { public void paint( Graphics g ) { g.drawString( "Welcome to Java Programming!",25,25); } } 2. Start the NetBeans IDE: Start, Programs, NetBeans 6.8, NetBeans IDE (you should also have a shortcut on the desktop). ECC 4 © Niko Čulevski Lab 1 CS &141 3. Create a new project named Welcome Applet (select New->New Project, then select Java in General Category and Java Project with Existing Sources in the Projects category). 4. Click on Next and name the project Welcome Applet and select location for project folder (C:\Temp\Lab 1 will do for now). Make sure the Set as Main Project check box is not selected selected (we will with other projects). Click on Next. 5. Click on Add Folder and specify the folder where your source file Welcome.java is located (for me, it’s in C:\Temp\Lab 1). ECC 5 © Niko Čulevski Lab 1 CS &141 6. Leave this at default. Just click Finish. ECC 6 © Niko Čulevski Lab 1 CS &141 7. Press Shift-F6 to run file (you have created a Main for this project, so you can’t run it as a main project). Voilà! 8. Here is the content of the html file that NetBeans generates for you. (Note the <APPLET> tag): <HTML> <HEAD> <TITLE>Applet HTML Page</TITLE> </HEAD> <BODY> <!-*** GENERATED applet HTML launcher - DO NOT EDIT IN 'BUILD' FOLDER *** If you need to modify this HTML launcher file (e.g., to add applet parameters), copy it to where your applet class is found in the SRC folder. If you do this, the IDE will use it when you run or debug the applet. Tip: To exclude an HTML launcher from the JAR file, use exclusion filters in the Packaging page in the Project Properties dialog. For more information see the online help. --> <H3><HR WIDTH="100%">Applet HTML Page<HR WIDTH="100%"></H3> <P> <APPLET codebase="classes" code="Welcome.class" width=350 height=200></APPLET> </P> <HR WIDTH="100%"><FONT SIZE=-1><I>Generated by NetBeans IDE</I></FONT> </BODY> </HTML> ECC 7 © Niko Čulevski Lab 1 CS &141 Problem Statement IV: Create a Java GUI application using NetBeans that provides the user usage of Ohm’s Law formula. In electrical circuits, Ohm's law states that the current through a conductor between two points is directly proportional to the potential difference or voltage across the two points, and inversely proportional to the resistance between them, provided that the temperature remains constant. The mathematical equation that describes this relationship is: I= V V or R = or V = I ⋅ R I R where V is the potential difference measured across the resistance in units of volts; I is the current through the resistance in units of amperes and R is the resistance of the conductor in units of ohms. More specifically, Ohm's law states that the R in this relation is constant, independent of the current. The law was named after the German physicist Georg Ohm, who, in a treatise published in 1827, described measurements of applied voltage and current through simple electrical circuits containing various lengths of wire. He presented a slightly more complex equation than the one above to explain his experimental results. The above equation is the modern form of Ohm's law. 1. Start the NetBeans IDE: Start, Programs, NetBeans 6.8, NetBeans IDE (you should also have a shortcut on the desktop). 2. Create a Java application project and name it Ohm’s Law. a. Select File ->New Project. b. In the New Project dialog, choose Java from Categories and Java Application from Projects. c. Name the project Ohm’s Law. Select C:\Temp for project location (or any other location you want—you can copy the entire project folder to any other location you want). Uncheck Create Main Class check box. Click on Finish. 3. NetBeans creates several folders and files for you (a build.xml and manifest.mf file). You want to place the source file for your main class in the src folder. So open the ECC 8 © Niko Čulevski Lab 1 CS &141 Source Package, highlight the <default package>, right-mouse on it, select New and JFrame form. 4. Name the Class Name OhmsLaw (note: no apostrophe or space in the name—it must be a valid Java identifier). Click on Finish. Java creates the source file names OhmsLaw.java and a GUI file OhmsLaw.form. 5. Build the form with controls from the Pallete so that it looks somewhat like this: a. You will need to bring a title JLabel from Swing Controls from the Palette. The JLabel has an icon of Ohm’s formula (a .png image to be provided). b. The GUI contains a number of other JLabels, JTextFields, a JPanel that contains 4 JButtons. There are a number of different naming conventions for naming controls. I prefer indicative name of the control followed by the type of control. For example, currentJTextField. 6. Name all controls as indicated in the following screen capture: Note that the GUI contains a JPanel named control JPanel which has a GridLayout with 2 rows and 2 columns and which contains the 4 JButtons. The Print JButton has been disabled (uncheck the enabled poperty) for later implementation. 7. Double-click on the Calculate JButton—this should take you in the Source code calculateJButtonActionPerformed method. Delete the comment line and type the following code: // Calculate the current given voltage and resistance DecimalFormat numberFormatter = new DecimalFormat("#,##0.0##"); float volts, resistance, current; volts = Float.parseFloat(voltsJTextField.getText()); resistance = Float.parseFloat(resistanceJTextField.getText()); current = volts/resistance; ECC 9 © Niko Čulevski Lab 1 CS &141 currentJTextField.setText(numberFormatter.format(current)); 8. Add the statement import java.text.DecimalFormat; on the top of the source code to enable the DecimalFormat class. 9. Double-click on the Clear button and add the following code: // Clear all text fields to reset the form voltsJTextField.setText(""); resistanceJTextField.setText(""); currentJTextField.setText(""); voltsJTextField.requestFocus(); 10. Double-click on the Quit button and add the following code: // Terminate teh application System.exit(0); 11. Run the application by selecting Run->Run Main Project (F6) and check your results with the following: 12. The program is not “goof-proof”. Try running it with illegal or missing input, for example. Verification and validation as well as printing comes later. Problem Statement V: Create a Java applet using a simple text editor that adds two integers (you could keep adding more than two) and is viewed with the appletviewer. 1. Open Notepad or any other text editor (Start, Programs, Accessories, Notepad) and type the following code exactly as it appears below (pay attention to uppercase/lowercase, punctuation, etc. and don’t worry at this stage what it all means): // Addition program import java.applet.Applet; import java.awt.*; // import the java.awt package import java.awt.event.*; // import the java.awt.event package public class Addition { Label prompt; TextField input; int number; int sum; extends Applet implements ActionListener // // // // message that prompts user to input input values are entered here variable that stores input value variable that stores sum of integers // setup the graphical user interface components // and initialize variables public void init() { prompt = new Label( "Enter integer and press Enter:" ); add( prompt ); // put prompt on applet input = new TextField( 10 ); add( input ); // put input TextField on applet sum = 0; // set sum to 0 // "this" applet handles action events for TextField input ECC 10 © Niko Čulevski Lab 1 CS &141 input.addActionListener( this ); } // process user's action in TextField input public void actionPerformed( ActionEvent e ) { // get the number and convert it to an integer number = Integer.parseInt( e.getActionCommand() ); sum = sum + number; // add number to sum input.setText( "" ); // clear data entry field showStatus( Integer.toString( sum ) ); // display sum } } 2. 3. 4. 5. 6. Save your file with the name Addition.java on drive C:\Temp. Open a DOS command window (Start, Programs, Command Prompt). Change the directory to C:\Temp. Compile your program by typing javac Addition.java If the compilation goes well, the system should respond within few seconds with another prompt (and no errors!). Check your directory for the new file names Addition.class. This is the bytecode that the JVM will use to execute the program. 7. Create the HMTL file in Notepad that contains the Addition.class applet and call it Addition.html: 8. View the applet with appletviewer: at the DOS prompt type appletviewer Addition.html. ECC 11 © Niko Čulevski Lab 1 ECC CS &141 12 © Niko Čulevski