Java Applets Chapter 15. Overview A Java Applet allows us to run a Java program from a web browser. Usually, just the.class file is sent to the client.

Slides:



Advertisements
Similar presentations
2D Graphics Drawing Things. Graphics In your GUI, you might want to draw graphics E.g. draw lines, circles, shapes, draw strings etc The Graphics class.
Advertisements

Made with love, by Zachary Langley Applets The Graphics Presentation.
Web Design & Development Lecture 19. Java Graphics 2.
Graphics You draw on a Graphics object The Graphics object cannot directly be created by your code, instead one is generated when the method paintComponent.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Chapter 5 Programming Graphics. Chapter Goals To be able to write simple applications To display graphical shapes such as lines and ellipses To use colors.
Multithreading : animation. slide 5.2 Animation Animation shows different objects moving or changing as time progresses. Thread programming is useful.
Chapter 5 Programming Graphics. Chapter Goals To be able to write applications with simple graphical user interfaces To display graphical shapes such.
Java Graphics Section 1 - Multi-File Graphics Programs Section 2 - The Coordinate System and Graphics Context g Section 3 - The Java Drawing and Painting.
Java Applets. An applet is a Panel that allows interaction with a Java program. A applet is typically embedded in a Web page and can be run from a browser.
Applets An applet is similar to a Java program, but it runs within a Web-browser on a client machine. For security, you cannot change anything on a client.
Graphics Programming With Applets Feb 23, Applets There are three different types of executable java code. –Standalone application, which has main()
Java Applets A lab course by Dr. Junaid Ahmed Zubairi SUNY Fredonia.
1 Applets Chapter 1 To understand:  why applets are used to extend the capabilities of Web pages  how an applet is executed and know about the restrictions.
1 Recitation 11. Applet Applets. An applet is a Java program that is started by a browser (e.g. netscape or internet explorer) when an html file has a.
1 L44 Introduction to Java Applets. 2 OBJECTIVES  To differentiate between applets and applications.  To observe some of Java's exciting capabilities.
Applets. An applet is a Panel that allows interaction with a Java program A applet is typically embedded in a Web page and can be run from a browser You.
Chapter 3 - Introduction to Java Applets Outline 3.1Introduction 3.2Thinking About Objects 3.4A Simple Java Applet: Drawing a String 3.5Two More Simple.
28-Jun-15 Applets. 2 An applet is a program that is typically embedded in a Web page and can be run from a browser You need special HTML in the Web page.
Chapter 13: Advanced GUIs and Graphics J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design, Second Edition.
Object Oriented Programming (OOP) LAB # 5 TA. Maram & TA. Mubaraka TA. Kholood & TA. Aamal.
Java Review Structure of a graphics program. Computer Graphics and User Interfaces Java is Object-Oriented A program uses objects to model the solution.
Java Applets. Lecture Objectives  Learn about Java applets.  Know the differences between Java applets and applications.  Designing and using Java.
Chapter 9: Applets Jim Burns Fall Outline Learn about applets Learn about applets Write an HTML doc to host an applet Write an HTML doc to host.
Applets Java API.
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
Chapter 12 Applets and Advanced Graphics  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets.
Chapter 13 Advanced GUIs and Graphics. Chapter Objectives Learn about applets Explore the class Graphics Learn about the class Font Explore the class.
JAVA APPLETS By: Ms. Humaira Siddiqui. Java and the Internet Java is considered to be a language well suited to be used in the internet. In contrast with.
Applets Chapter 17.  Java’s big splash onto the scene came in the mid 90’s. The people at Sun Microsystems had managed to work java programs into Web.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 12 Advanced GUIs and Graphics.
© Copyright by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Outline 20.1 Test-Driving the Screen Saver Application.
JAPPLET.
Applets and Frames CS 21a: Introduction to Computing I First Semester,
Chapter 17: Applets, Images, and Sound. Objectives Learn about applets Write an HTML document to host an applet Use the init() method Work with JApplet.
CSE 219 Computer Science III Images. HW1 Has been posted on Blackboard Making a Game of Life with limited options.
Chapter 12 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
tiled Map Case Study: Rendering with JPanel © Allan C. Milne v
Chapter 10: Applets and Advanced Graphics The Applet Class The Applet Class The HTML Tag The HTML Tag Passing Parameters to Applets Passing Parameters.
Canvas and Graphics CS 21a. 9/26/2005 Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L17: Canvas.
Java Applets. An applet is a Panel that allows interaction with a Java program. A applet is typically embedded in a Web page and can be run from a browser.
1 Applets and Course Evaluation Applet Example - Sailing Applet UML Diagrams Applet Web Page Encoding (HTML) Applet Java Coding – Hello World Course Evaluation.
Applets. What is an applet? Why create applets instead of applications? – Applets are Java programs that can be embedded in an HTML document – In contrast,
1 CSC Computer Education (P) Ltd. DESIGNED BY K PRAKASH,
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Lec.10 + (Chapter 8 & 9) GUI Java Applet Jiang (Jen) ZHENG July 6 th, 2005.
Program that runs in appletviewer (test utility for applets) Web browser (IE, Communicator) Executes when HTML (Hypertext Markup Language) document containing.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Review of Graphics in Java,
Creating Your Own Widgets CompSci 230 S Software Construction.
Applets and Frames. Copyright 2005, by the authors of these slides, and Ateneo de Manila University. All rights reserved L14: GUI Slide 2 Applets Usually.
(C) 2010 Pearson Education, Inc. All rights reserved.  Class Graphics (from package java.awt) provides various methods for drawing text and shapes onto.
Chapter 14 Applets and Advanced GUI  The Applet Class  The HTML Tag F Passing Parameters to Applets F Conversions Between Applications and Applets F.
Intro to Applets. Applet Applets run within the Web browser environment Applets bring dynamic interaction and live animation to an otherwise static HTML.
1 GUIs, Layout, Drawing Rick Mercer. 2 Event-Driven Programming with Graphical user Interfaces  Most applications have graphical user interfaces (GUIs)
Creating Applets. What is an applet? What is an applet? A Java program that runs in a web browser. A Java program that runs in a web browser. An applet.
Field Trip #23 Hangman By Keith Lynn. JApplet A JApplet is a top-level container An applet is a small Java program that is executed by another program.
1 Applets. 2 Design of Applets 3 Sun wrote Java to be executable within a hosting application browser The applications are applets. An applet is downloaded.
Applets Java code is compiled into byte code instead of machine language –Languages like C, C++, Pascal and others are compiled into machine language so.
1 Applets. 2 What is an applet? Applet: a Java program that can be inserted into a web page and run by loading that page in a browser brings web pages.
Introduction to Applets Chapter 21. Applets An applet is a Java application that is intended to be invoked and executed through a Web browser. Click Here.
CHAPTER Agenda Applets Servelets Browsers HelloWorld.
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
1 Applets Programming. Introduction Java programs are divided into two main categories, applets and applications. An application is an ordinary Java program.
Chapter 13: Advanced GUIs and Graphics
Distributed Computing, M. L. Liu
Distributed Computing, M. L. Liu
Applets.
Introduction to Computing Using Java
Advanced GUIs and Graphics
Presentation transcript:

Java Applets Chapter 15

Overview A Java Applet allows us to run a Java program from a web browser. Usually, just the.class file is sent to the client. In order for this to work, the client must also have a Java Virtual Machine (JVM) installed. We will show how to write Java applets and HTML files that use them. We will show an example of a Tic-Tac-Toe Java applet.

HTML Stands for HyperText Markup Language. It is the de facto standard for creating web pages. It contains both the text to display and markup information that tells us how to format the text. Can be automatically generated by NetBeans. Applet HTML Page Applet HTML Page

HTML (cont'd) Starts with and ends with. Every section starts with and ends with It has a section and a section. The section can contain a section. This is the text that will be displayed at the top of the web browser window when the web page is opened. section can contain several sections. H stands for header. H1 displays the biggest header and H6 - the smallest. Font point size cannot be directly specified. section can be used to describe a new paragraph. section can be used to describe a JAVA applet to be inserted here. width and height variables can be specified in pixels. codebase is the name of the directory that contains the.class file.

Writing a Java Applet Remove the main method. Create a class that extends JApplet. This will be the applet's window. Add to this class the init method. This will be the first method to execute. The setVisible method should not be called on the JApplet window because it is always visible. The setTitle and setSize methods should not be called on the JApplet window because the title and the size of the applet are determined by the HTML file that opens the applet. Remove any code that exits the program. An applet does not have a close button. Similarly, remove any reference to the setDefaultCloseOperation method for the applet window. An applet can create additional JFrame objects (i.e., windows), but the applet window itself is not a JFrame object.

import java.awt.*; import javax.swing.*; public class MyApplet extends JApplet { MyPanel p = new MyPanel(); public void init() { p.setS("Initializing..."); p.repaint(); add(p); } public void start() { p.setS("Starting..."); p.repaint(); } public void stop() { p.setS("Stopping..."); p.repaint(); }

public void destroy() { p.setS("Destroying..."); p.repaint(); } class MyPanel extends JPanel { String s; int i = 0; public void setS(String s) { this.s = s; i++; } public void paintComponent(Graphics g) { super.paintComponent(g); g.drawString(s + " " + i, 10, 10); }

JApplet Methods init: called first at the beginning start: called after init and every time the applet is started. stop: called every time the applet is stopped and before the applet is killed. destroy: called when the applet is destroyed. The web browser decides when to start or stop an applet. For example, a heavy applet that displays moving graphics may be stopped by the web browser as we navigate to a new web page.

Creating Popup Windows Sometimes, we want to create Java applets in their own windows. For example, we can create a button in the webpage. When this button is pressed, a new windows can open. The next slide shows an example of a calculator app. When the button is pressed, a new window with a calculator is displayed. When the button is pressed again, the window is hidden.

import java.awt.event.*; import javax.swing.*; public class MyApplet extends JApplet { public void init(){ JButton calcButton = new JButton("Calculator"); final JFrame frame = new JFrame(); frame.setTitle("Calculator"); frame.setSize(200,200); frame.add(new CalculatorPanel()); calcButton.addActionListener(new ActionListener(){ public void actionPerformed(ActionEvent e){ frame.setVisible(!frame.isVisible()); }}); add(calcButton); }

The Tic-Tac-Toe Game We will create a Java applet for the Tic-Tac-Toe game. The game will be embedded inside a web browser and no new window will be opened. The shapes to be displayed for X and O will be from images. Our Artificial Intelligence (AI) will play good, but it will be possible to beat the game. Our board will consist of nine squares. We will start by writing a Square class that will be responsible for displaying and changing a square. In other words, our design will be bottom-up.

import java.awt.*; import java.awt.geom.*; class Square extends Rectangle2D.Double { private boolean isX = false; private boolean isO = false; public boolean isCharacter(char c) { if (c == 'x') { return isX; } if (c == 'o') { return isO; } return false; } public void placeCharacter(char c) { if (c == 'x') { isX = true; isO = false; }

if (c == 'o') { isO = true; isX = false; } public void clear() { isX = false; isO = false; } public boolean hasValue() { return (isX || isO); } public Square(double x, double y, double dx, double dy) { super(x, y, dx, dy); }

public void draw(Graphics2D g2, Image xImage, Image oImage) { g2.draw(super.getBounds2D()); if (isX) { g2.drawImage(xImage, (int) getX()+1,(int) getY()+1, (int) getWidth()-2, (int) getHeight()-2, null); } if (isO) { g2.drawImage(oImage, (int) getX()+1,(int) getY() +1, (int) getWidth()-2, (int) getHeight()-2, null); }

Notes on the Square Class isX and isO variables tells us if the square is an X or an O. Note that it is impossible that both of them are true. We cannot have a single Boolean variable because we have three possibilities: cell empty, cell X, cell O. The class inherits from Rectangle2D.Double. This is the surrounding rectangle. A square is drawn by drawing the surrounding rectangle and the image inside it. For the drawImage method, second and third arguments are top left corner. Fourth and fifth arguments are width and height of image! Last argument is null.

import java.awt.*; import java.net.*; import java.util.*; import javax.imageio.*; import javax.swing.*; public class TicTacToe extends JApplet { private ArrayList squares = new ArrayList<>(); private Image xImage, oImage; public void initBoard() { squares = new ArrayList<>(); Dimension d = getSize(); double dx = d.getWidth() / 3.0; double dy = d.getHeight() / 3.0; for (int x = 0; x < 3; x++) { for (int y = 0; y < 3; y++) { squares.add(new Square(x * dx, y * dy, dx, dy)); } repaint(); }

public void init() { try { xImage = ImageIO.read(new URL(getCodeBase(), "images/x.jpg")); oImage = ImageIO.read(new URL(getCodeBase(), "images/o.jpg")); } catch (Exception exception) { } initBoard(); addMouseListener(new MyMouseListener()); }... } The geSize method gives us the size of the applet. We divide it in a 3x3 grid. The ImageIO.read method reads the image. The images must be stored in the image subdirectory of the codebase directory. The URL class takes as input the name of the main directory and a relative file name. The getCodeBase method gets the value of the codeBase variable.

Painting Inside an Applet We need to use the method paint instead of paintComponent. The reason is that we are inside a JApplet and not a JPanel. In our case, we will just call the method draw on each square. public void paint(Graphics g) { super.paint(g); Graphics2D g2 = (Graphics2D) g; g2.setColor(Color.RED); for (Square r : squares) { r.draw(g2, xImage, oImage); }

Responding to Mouse Clicks When the user presses a mouse button, we will check which square the mouse is over. We will use the method contains of Rectangle2D to do so. If the square has no value, we will place an X in it. If the game is not over, we will compute the computer move and also place it on the board. If at any point the game is over, we will exit the method.

class MyMouseListener extends MouseAdapter { public void mousePressed(MouseEvent e) { for (Square r : squares) { if (r.contains(e.getPoint())) { if (!r.hasValue()) { r.placeCharacter('x'); repaint(); if (isGameOver()) { return; } computerMove(); repaint(); if (isGameOver()) { return; }

Checking for Win Win is when there is vertical, horizontal, or diagonal line with the character X or O. We will create a method that check if the character c wins. It will call a method isLine that checks if the specified line is all filled with the same input character.

public boolean isLine(int i, int j, int k, char c) { return (squares.get(i).isCharacter(c) && squares.get(j).isCharacter(c) && squares.get(k).isCharacter(c)); } public boolean wins(char c) { for (int i = 0; i < 3; i++) { if (isLine(3 * i, 3 * i + 1, 3 * i + 2, c) ||// hr line isLine(i, i + 3, i + 6, c))) { //vertical line return true; } if (isLine(0, 4, 8, c) || isLine(2, 4, 6, c)){//diagonal return true; } return false; }

isBoardFull Method Checks to see if the board is full. If there is a square that does not have a value, then the method returns false. If all squares have a value, then the method returns true. isGameOver method is shown on next slide. It simply checks if X wins, if Y wins, or if the board is full.

public boolean isGameOver() { if (wins('o')) { JOptionPane.showMessageDialog(this, "I win!"); initBoard(); //restart game return true; } if (wins('x')) { JOptionPane.showMessageDialog(this, "You win!"); initBoard(); //restart game return true; } if (isBoardFull()) { JOptionPane.showMessageDialog(this, "It's a tie!"); initBoard(); //restart game return true; } return false; } //JOPtionPane.showMessageDialog displays text in modal //dialog, 1st parameter is parent window

computerMove method If middle is empty, we always play there Otherwise, we go through all the squares and check their score. We place O at the square with the highest score.

public void computerMove() { if (!squares.get(4).hasValue()) { // if middle is empty squares.get(4).placeCharacter('o'); return; } Square bestRectangle = squares.get(0); int best = computeScore(bestRectangle); for (Square r : squares) { if (computeScore(r) > best) { best = computeScore(r); bestRectangle = r; } bestRectangle.placeCharacter('o'); }

computeScore Method If the square is not empty, score is 0. Placing a character on a full square is a terrible choice. If we can win with our next move, then we should play it. This is our best option. Score = 4. If we can prevent the human from winning with their next move, this is the second best option. Score = 3. In all other cases, we will set Score = 2.

public int computeScore(Square r) { if (r.hasValue()) { return 0; } if (winsWithNextMove(r, 'o')) { return 4; } if (winsWithNextMove(r, 'x')) { return 3; } return 2; }

winsWithNextMove method We will place a character on the board (but don't display the board). We will check if this is a winning move for the user with the input character. After we figure out if the moves wins or not, we will undo our board modification by removing the character from the square. public boolean winsWithNextMove(Square r, char c) { r.placeCharacter(c); if (wins(c)) { r.clear(); return true; } r.clear(); return false; }

Summary In order for a Java applet to work, we also need to create an HTML file. The HTML file contains the size of the window, the title, and the name of the code base directory. In order to write a Java applet, remove the main method. Create a class that inherits from the JApplet class and override the init method.