140 likes | 249 Views
Chapter 3. Section 65 – Manipulating Data Using Methods – Java Applet. Chapter Objectives. Implement an ActionListener to handle events Add interface components to an applet Use the init() and paint() methods to load the applet interface Use the actionPerformed() method
E N D
Chapter 3 Section 65 – Manipulating Data Using Methods – Java Applet
Chapter Objectives • Implement an ActionListener to handle events • Add interface components to an applet • Use the init() and paint() methods to load the applet interface • Use the actionPerformed() method • Run and test an interactive applet
Moving to the Web • Create a new Java Applet in NetBeans: • Right click on the bodymasscalculator package and select New > Java > Applet • Name the Applet BodyMassApplet
Moving to the Web • The applet version of the Body Mass Index Calculator has four kinds of objects • Image, Labels, TextFields, and Buttons • Import three packages • Java.applet.* • Java.awt.* • Java.awt.event.* • Implement an ActionListener interface in the class header • Informs the program to respond to user-driven events
Moving to the Web • Every event class has one or more associated listener interfaces
Adding Interface Components to an Applet • Label • Displays text in the applet window • TextField • Displays a text box for users to enter text • Buttons • Displays a command button for users to click
Label and Textfield Declarations • Construct the components to be displayed in the applet
The init() Method • Initializes the window color and graphic • Adds components to the applet window • Registers the Button’s ActionListener
The actionPerformed() Method • When a click event occurs, the ActionListener’s actionPerformed() method is triggered • Input values are retrieved with getText() • Calculations are performed • Output is sent to a label with setText()
The paint() Method • Draws the initialized image in the applet window
Creating an HTML Host Document for an Interactive Applet • Compile the applet • NetBeans creates an HTML Host Document to execute the applet • Uses the <APPLET> tag to specify the bytecode file, and width and height of the window (NetBeans uses defaults for width and height) • Use the same sample data to test the applet
Summary • Applet code is controlled by first defining Labels, TextFields and Buttons • Use the add method to place the items on in the web document • Create an actionPerformed method to be executed when a button is clicked
Rest of Today • Complete a Java Applet for the body mass calculator • Full list of the code can be found on page 190 of the book • Once built copy the logo.gif file to the “build” folder, edit the HTML file to change the height to 500 and open the HTML file.