The init() Method. Browser Calling Applet Methods

Similar documents
G51PRG: Introduction to Programming Second semester Applets and graphics

An applet is a program written in the Java programming language that can be included in an HTML page, much in the same way an image is included in a

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

Graphical User Interfaces 2

GUI in Java TalentHome Solutions

Programming graphics

Lecture 19 GUI Events

CSE 331 Software Design & Implementation

Java & Graphical User Interface II. Wang Yang wyang AT njnet.edu.cn

Essential Series. Springer-Verlag London Ltd.

Graphical User Interfaces 2

C ONTENTS PART I FUNDAMENTALS OF PROGRAMMING 1. and Java 3. Chapter 1 Introduction to Computers, Programs,

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

Graphical User Interfaces 2

Overview. Applets. A Java GUI inside your browser! Important methods Drawing images Playing audio Getting input parameters Double buffering

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Java Applet & its life Cycle. By Iqtidar Ali

Introduction to the JAVA UI classes Advanced HCI IAT351

CONTENTS. Chapter 1 Getting Started with Java SE 6 1. Chapter 2 Exploring Variables, Data Types, Operators and Arrays 13

Java Applets This is not a Java course! (You re supposed to know about Java.)

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

OBJECT ORIENTED PROGRAMMING. Course 8 Loredana STANCIU Room B613

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

AP Computer Science Unit 13. Still More Graphics and Animation.

Graphic User Interfaces. - GUI concepts - Swing - AWT

Java Foundations John Lewis Peter DePasquale Joe Chase Third Edition

Table of Contents. Chapter 1 Getting Started with Java SE 7 1. Chapter 2 Exploring Class Members in Java 15. iii. Introduction of Java SE 7...

PESIT Bangalore South Campus

CS 251 Intermediate Programming GUIs: Event Listeners

(Refer Slide Time: 02:01)

Page 1 of 7. public class EmployeeAryAppletEx extends JApplet

Abstract Classes and Interfaces

PROGRAMMING LANGUAGE 2

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

Outline. More on the Swing API Graphics: double buffering and timers Model - View - Controller paradigm Applets

Road Map. Introduction to Java Applets Review applets that ship with JDK Make our own simple applets

GUI Components: Part 1

Supporting Materials

Java Programming Lecture 6

BASICS OF GRAPHICAL APPS

Module 5 Applets About Applets Hierarchy of Applet Life Cycle of an Applet

Java Applets. Last Time. Java Applets. Java Applets. First Java Applet. Java Applets. v We created our first Java application

GUI Event Handlers (Part II)

Sri Vidya College of Engineering & Technology

CS 251 Intermediate Programming GUIs: Components and Layout

Programmierpraktikum

ASSIGNMENT NO 14. Objectives: To learn and demonstrated use of applet and swing components

Introduction... xv SECTION 1: DEVELOPING DESKTOP APPLICATIONS USING JAVA Chapter 1: Getting Started with Java... 1

Programming Languages and Techniques (CIS120)

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Programming Languages and Techniques (CIS120)

The AWT Event Model 9

Java Applets / Flash

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

2IS45 Programming

Command-Line Applications. GUI Libraries GUI-related classes are defined primarily in the java.awt and the javax.swing packages.

Chapter 7 Applets. Answers

Graphical User Interface (GUI) components in Java Applets. With Abstract Window Toolkit (AWT) we can build an applet that has the basic GUI

Solutions to Chapter Exercises. GUI Objects and Event-Driven Programming

GUI 4.1 GUI GUI MouseTest.java import javax.swing.*; import java.awt.*; import java.awt.event.*; /* 1 */

Programming Languages and Techniques (CIS120)

Java Application Development

Which of the following syntax used to attach an input stream to console?

Part 3: Graphical User Interface (GUI) & Java Applets

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

The JFrame Class Frame Windows GRAPHICAL USER INTERFACES. Five steps to displaying a frame: 1) Construct an object of the JFrame class

Java: Graphical User Interfaces (GUI)

Contents 8-1. Copyright (c) N. Afshartous

Lecture 5: Java Graphics

Java Programming Unit 6. Inner Classes. Intro to Apples. Installing Apache Tomcat Server.

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

SELF-STUDY. Glossary

CS506 Web Programming and Development Solved Subjective Questions With Reference For Final Term Lecture No 1

Contents Introduction 1

CS 112 Programming 2. Lecture 14. Event-Driven Programming & Animations (1) Chapter 15 Event-Driven Programming and Animations

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

Come & Join Us at VUSTUDENTS.net

What is Widget Layout? Laying Out Components. Resizing a Window. Hierarchical Widget Layout. Interior Design for GUIs

Graphical User Interface (GUI)

GUI, Events and Applets from Applications, Part III

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Method Of Key Event Key Listener must implement three methods, keypressed(), keyreleased() & keytyped(). 1) keypressed() : will run whenever a key is

Lab 4. D0010E Object-Oriented Programming and Design. Today s lecture. GUI programming in

CSSE 220 Day 19. Object-Oriented Design Files & Exceptions. Check out FilesAndExceptions from SVN

11/6/15. Objec&ves. RouleQe. Assign 8: Understanding Code. Assign 8: Bug. Assignment 8 Ques&ons? PROGRAMMING PARADIGMS

Datenbank-Praktikum. Universität zu Lübeck Sommersemester 2006 Lecture: Swing. Ho Ngoc Duc 1

IT101. Graphical User Interface

John Cowell. Essential Java Fast. How to write object oriented software for the Internet. with 64 figures. Jp Springer

Outline. Announcements. Feedback. CS1007: Object Oriented Design and Programming in Java. Java beans Applets

Graphical User Interface (GUI)

User interfaces and Swing

OOP Assignment V. For example, the scrolling text (moving banner) problem without a thread looks like:

Module 5 The Applet Class, Swings. OOC 4 th Sem, B Div Prof. Mouna M. Naravani

Transcription:

Chapter 12 Applets and Advanced GUI The Applet Class The <applet> HTML Tag Passing Parameters to Applets Conversions Between Applications and Applets Running a Program as an Applet and as an Application Handling the Mouse Event Handling the Keyboard Event Model dynamic behavior using sequence diagrams and statecharts diagrams Advanced Layout (CardLayout and GridBagLayout and using No Layout Manager) (Optional) The Applet Class public class MyApplet extends JApplet { public void init() {... } public void start() {... } public void stop() {... } public void destroy() {... } //your other methods } Browser Calling Applet Methods The init() Method Invoked when the applet is first loaded and again if the applet is reloaded. reload enters web page init after init return to the page start stop Common functions implemented in this method include creating threads, loading images, setting up user-interface components, and getting parameters from the <applet> tag in the HTML page. exit leave the page

The start() Method Invoked after the init() method is executed; also called whenever the applet becomes active again after a period of inactivity (for example, when the user returns to the page containing the applet after surfing other Web pages). Functionality might include restarting threads (for example, to resume an animation) or simply telling the applet to run again. The stop() Method The opposite of the start() method, which is called when the user moves back to the page containing the applet; the stop() method is invoked when the user moves off the page. When the user leaves the page, any threads the applet has started but not completed will continue to run. The destroy() Method Invoked when the browser exits normally to inform the applet that it is no longer needed and that it should release any resources it has allocated. Usually, you will not need to override this method unless you need to release specific resources, such as threads that the applet created. Example 12.1 Using Applets Objective: Compute mortgages. The applet enables the user to enter the annual interest rate, the number of years, and the loan amount. Click the Compute Mortgage button, and the applet displays the monthly payment and the total payment. MortgageApplet Run Applet Viewer

Writing Applets Always extends thejapplet class, which is a subclass of Applet for Swing components. Overrideinit(), start(), stop(), and destroy() if necessary. By default, these methods are empty. Add your own methods and data if necessary. Applets are always embedded in an HTML page. The <applet> HTML Tag <applet code=classfilename.class width=applet_viewing_width_in_pixels height=applet_viewing_height_in_pixels [archive=archivefile] [codebase=applet_url] [vspace=vertical_margin] [hspace=horizontal_margin] [align=applet_alignment] [alt=alternative_text] > <param name=param_name1 value=param_value1> </applet> Running Applets in Java Plug-In (optional) Why to Use Java Plug-In? Java Plug-in enables Web browsers to run Java applets consistently on all the platforms. How to Use Java Plug-In (optional) Convert the HTML file to a new HTML file using the HTMLConverter Utility. The new HTML file contains the tags for invoking the Java Plug-In. If the Plug-In is not installed, the new HTML file automatically downloads it from the Sun JavaSoft Web site.

Passing Parameters to Applets <applet code = "DisplayMessage.class" width = 200 height = 50> <param name=message value="welcome to Java"> <param name=x value=20> <param name=y value=20> alt="you must have a Java-enabled browser to view the applet" </applet> Example 12.2 Passing Parameters to Java Applets Objective: Display a message at a specified location. The message and the location (x, y) are obtained from the HTML source. DisplayMessage Run Applet Viewer Applications vs. Applets Similarities Since they both are subclasses of the Container class, all the user interface components, layout managers, and event-handling features are the same for both classes. Differences Applications are invoked by the Java interpreter, and applets are invoked by the Web browser. Applets have security restrictions Web browser creates graphical Security Restrictions on Applets Applets are not allowed to read from, or write to, the file system of the computer viewing the applets. Applets are not allowed to run any programs on the browser s computer. Applets are not allowed to establish connections between the user s computer and another computer except with the server where the applets are stored.

Conversions Between Applications and Applets Conversions between applications and applets are simple and easy. You can always convert an applet into an application. You can convert an application to an applet as long as security restrictions are not violated. Example 12.3 Running a Program as an Applet and as an Application Objective: Modify MortgageApplet to enable it to run both as an applet and as an application. Run as Application DisplayMessageApp Run as Applet Handling Mouse Events Java provides two listener interfaces, MouseListener andmousemotionlistener, to handle mouse events. The MouseListener listens for actions such as when the mouse is pressed, released, entered, exited, or clicked. The MouseMotionListener listens for actions such as dragging or moving the mouse. Example 12.4 Moving Message Using Mouse Objective: Create a program to display a message in a panel. You can use the mouse to move the message. The message moves as the mouse drags and is MoveMessageDemo Run as Application always displayed at Run as Applet

Example 12.5 Handling Complex Mouse Events Objective: Create a program for drawing using a mouse. Draw by dragging with the left mouse button pressed; erase by dragging with the right button pressed. ScribbleDemo Run as Application Run as Applet Handling Keyboard Events To process a keyboard event, use the following handlers in the KeyListener interface: keypressed(keyevent e) Called when a key is pressed. keyreleased(keyevent e) Called when a key is released. keytyped(keyevent e) Called when a key is pressed and then released. The KeyEvent Class Methods: getkeychar() method getkeycode() method Keys: Home VK_HOME End VK_End Page Up VK_PGUP Page Down VK_PGDN etc... Objective: Display a user-input character. The user can also move the character up, down, left, and right using the arrow keys. Example 12.6 Keyboard Events Demo KeyboardEventDemo Run as Application Run as Applet

Sequence diagrams Sequence diagrams describe interactions among objects by depicting the time ordering of method invocations. Class role anobject: TheClass anotherobject: TheOtherClass Sequence diagrams, cont. : ButtonDemo messagepanel: MessagePanel setxcoordinate Activation amethod() Method Invocation repaint Method Invocation anothermethod() Statechart diagrams Statechart diagrams describe flow of control of the object. Statechart diagrams, cont. init() Indicate Initial State State1 start() Started Initialized stop() stop() Stopped Transition start() destroy() State2 Destroyed

Example 12.7 The TicTacToe Game Example 12.7, cont. JApplet JPanel MouseListener TicTacToe -whoseturn: char -cell Cell[][] = new Cell[3][3] -JLabel jlblstatus: JLabel +init(): void +isfull(): boolean +iswon(): boolean 1 9 -token: char Cell +gettoken():char +settoken(token: char): void +paintcomponet(g: Graphics): void +mouseclicked(e: MouseEvent): void TicTacToe Run as Application Run as Applet Advanced Layout (Optional from here on) Event Adapters (Optional) CardLayout GridBagLayout Using No Layout Manager

Event Adapters (Optional) Standard adapters Anonymous adapters CardLayout (Optional from here on) The CardLayout manager arranges components in a queue of cards. You can only see one card at a time. To construct a CardLayout, simply use the constructor CardLayout(). To add a component in the CardLayout container, use the following method: void add(component com, String name) CardLayout View Components void first(container) void last(container) void next(container) void previous(container) void show(container, String name) Example 12.10 Testing CardLayout Manager Objective: Create two panels in a frame. The first panel holds named components. The second panel uses buttons and a choice box to control which component is shown. ShowCardLayout Run

GridBagLayout The GridBagLayout manager is the most flexible and the most complex. It is similar to the GridLayout manager in the sense that both layout managers arrange components in a grid. The components can vary in size, however, and can be added in any order in GridBagLayout. Example 12.11: Using GridBagLayout Manager ShowGridBagLayout Run Using No Layout Manager You can place components in a container without using any layout manager. In this case, the component must be placed using the component s instance method setbounds(). Example 12.12: Using No Layout Manager This example shows a program that places the same components in the same layout as in the preceding example, but without using a layout manager. ShowNoLayout Run