240 likes | 418 Views
Applets. In the context of Java, the term Applet refers to a small app distributed on the internet as bytecode and run in a browser plug in that provides a JVM
E N D
Applets In the context of Java, the term Applet refers to a small app distributed on the internet as bytecode and run in a browser plug in that provides a JVM Java Applets are, from the programmer's point of view, a technically excellent way to write client-side apps, since a) bytecode normally runs faster than interpreted Javascript or Flash and b) Javascript is awkward once you get beyond the very small-scale tasks it was designed for. When Java was introduced in the mid 1990s, applets got a great deal of attention and were expected to be one of the core uses of Java. Even now, non-technical press articles often refer to "Java" when they mean "the Java plug in used for applets."
Applets Like all client-side executable code, applets can pose security problems for the client. In actual experience the Java plug in has a worse security record than Javascript. When you see warnings of security vulnerabilities in "Java," this is what they are talking about. Because of these problems, security software often interferes with the Java plug in. For these reasons, applets have never lived up to their technical potential. Oracle has introduced a security certificate system for applets, but my informed guess is that this problem is going to get worse, not better, and that applets will die out. The Horstmann textbook barely mentions them. For these reasons, I will discuss applets only briefly. Microsoft Silverlight works in a similar way and can be coded using C#, which is very similar to Java
Applets • Applets are embedded in web documents using the • HTML elements applet (deprecated), embed, or object. • Applets that don’t use GUI components extend Applet • Applets often use Swing and extend javax.swing.JApplet
Applets • Applets that don’t use Swing can use java.awt, which provides some GUI components • Applet life cycle: • initialize • start running. • stop running. • final cleanup, in preparation for being unloaded. • Source:http://docs.oracle.com/javase/tutorial/deployment/applet/lifeCycle.html • Applets will begin with the init() and start() methods if present, then paint(), which can be used to provide the graphic aspects of the applet. On close, they will execute stop() and destroy() if present
Applets import java.applet.Applet; import java.awt.Graphics; public class AppletDemo extends Applet { public void paint(Graphics g) { g.drawString("Hello, world!", 20, 10); // Draws a circle on the screen (x=40, y=30). g.drawArc(40, 30, 20, 20, 0, 360); } } Source: Wikipedia This needs to be compiled to bytecode using a JDK version compatible with your Java plug in version. Use Build Path/Configure Build Path to set the Java System Library To v. 1.7. Compile in Eclipse.
Applets <!DOCTYPE html> <html> <head> <title>Applet Example</title> </head> <body> <h1>Java Applet Example</h1> <object classid="java:AppletDemo.class" height="40" width="200" /> </body> </html> Put AppletDemo.class in the same directory as this html file. Use Windows Explorer, Mac Finder, etc., to find the .class file in the bin subdirectory of your Eclipse project.
import java.applet.Applet; import java.awt.Graphics; import javax.swing.JOptionPane; public class Simple extends Applet { StringBuffer buffer; public void init() { buffer = new StringBuffer(); addItem("initializing... "); } public void start() { addItem("starting... "); } public void stop() { addItem("stopping... "); } public void destroy() { addItem("preparing for unloading..."); } private void addItem(String newWord) { System.out.println(newWord); buffer.append(newWord); repaint(); } public void paint(Graphics g) { JOptionPane.showMessageDialog(null, "about to paint"); //Draw a Rectangle around the applet's display area. g.drawRect(0, 0, getWidth() - 1, getHeight() - 1); g.drawString(buffer.toString(), 5, 15); } } Applets
JApplets • JApplets should use invokeAndWait() with a Runnable • to be threadsafe. This makes sure the GUI completes • its initialization before the processing logic executes.
JApplets <!doctype html> <html> <meta http-equiv="Content-Type" content="text/html; charset=Cp1252"/> <head> <title>JApplet Demo</title> </head> <body> <object classid="java:JAppletDemo.class" width="200" height="200" /> </body> </html> Put JAppletDemo.class and all other classes created by the compiler (which will have names Like JAppletDemo$1.class)in the same directory as this html file.
import java.awt.Color; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import javax.swing.JApplet; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.SwingUtilities; public class JAppletDemo extends JApplet { //Called when this applet is loaded into the browser. public void init() { //Execute a job on the event-dispatching thread; creating this applet's GUI. try { SwingUtilities.invokeAndWait(new Runnable() { public void run() { JLabellbl = new JLabel("Click Me!"); lbl.setBackground(Color.gray); lbl.setOpaque(true); lbl.addMouseListener(new MouseListener(){ @Override public void mouseClicked(MouseEvent arg0) { JOptionPane.showMessageDialog(null, "Thanks!"); } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { }}); add(lbl); } }); } catch (Exception e) { System.err.println("createGUI didn't complete successfully"); } } } JApplets
Design Patterns You have noticed by now that there are many archetypal problems that arise over and over in programming • need to do the same kind of task using different algorithms in different situations • provide a new interface for an existing class so it can be used in a new context • access the objects in a collection one by one without giving client code access to implementation details • pool a group of objects so they can be reused by client code without the expense of instantiating new ones
Design Patterns • Definition from Wikipedia: Asoftware design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. • Patterns don’t consist of code or pseudocode, but of high-level descriptions of the solution and of the relationships between entities used in the pattern (classes and interfaces) • When you recognize a situation as one where a particular pattern would provide a good solution, you are only at the end of the beginning of creating the solution.
Design Patterns • Patterns help you recognize design issues in the first place • Patterns help you see solutions that other developers have already worked out • The second mouse gets the cheese • Patterns help to standardize programming practices, which makes it easier to understand, debug, or extend other programmers' code
Design Patterns • The patterns I describe in this lecture are chosen because they are easy to understand and because you have enough experience to recognize cases where these particular patterns are useful. There are several dozen other widely-recognized patterns. • You will probably learn additional patterns in various advanced programming classes, but I recommend that you read a book on this topic to get a general familiarity with a variety of patterns. Head First Design Patterns, which uses Java for its examples, is one good alternative. • The Bible of patterns is Design Patterns: Elements of Reusable Object-Oriented Software by Erich Gamma, Richard Helm, Ralph Johnson and John Vlissides, also known as the "Gang Of Four book." This book, however, is not especially easy to understand. • There is a good but very incomplete list of common patterns at http://refcardz.dzone.com/refcardz/design-patterns
Strategy Pattern • The Strategy pattern provides interchangeable algorithms for solving some problem by encapsulating them in objects. • In Java, Strategy is implemented using a Java interface with multiple implementations. Each implementing class can use a different algorithm. • A Strategy pattern can be set up so that the particular algorithm can be chosen at runtime based on characteristics of the actual data or other considerations. • Arrays.sort() implements the Strategy pattern; it chooses the particular type of sort to use, and this is transparent to client code. • An application that can save files in different file formats might use Strategy, deciding at runtime which implementation to use • You used Strategy in several of my labs without knowing it.
Strategy Pattern Source: http://www.journaldev.com/1754/strategy-design-pattern-in-java-example-tutorial
Strategy Pattern When a pattern has conventional terms for the classes and interfaces, use them in your code. Other developers will understand much of how your code works as soon as they see that you are using the pattern. • For example, in Strategy, use the word Strategy in the name of the interface, egPaymentStrategy, and in the names of the implementations, egCreditCardStrategy.
Template Method • Somewhat similar to Strategy, but implemented using inheritance rather than interface implementations • Definition from Wikipedia: the template method pattern is a behavioral design pattern that defines the program skeleton of an algorithm in a method, called template method, which defers some steps to subclasses. • Skeleton of an algorithm is coded in an abstract class, calling additional methods at various steps. Some of the additional methods may work the same way for all variants of the algorithm and may be coded in the abstract class. Different concrete subclasses implement other methods differently.
Template Method http://javapostsforlearning.blogspot.com/2013/03/template-method-design-pattern-in-java.html
Template Method http://javapostsforlearning.blogspot.com/2013/03/template-method-design-pattern-in-java.html
Template Method Vs. Strategy Java programmers typically prefer the more abstract approach of using interfaces, as in the Strategy pattern, over using inheritance, as in Template Method, because inheritance is more complex. Template Method code is hard to follow because it interleaves individual lines of code in the abstract class with calls to methods that are defined in the subclasses. The flip side of this is that the Template Method pattern reduces the amount of code necessary if the different variations of an algorithm have comparatively small differences. Because TM eliminates duplication, it is much easier to change the code if some fundamental aspect of the algorithm or interface has to change.
Adapter Pattern • The Adapter pattern connects a class to client code that requires a different interface. • Adapter is useful when a class or module already provides the functionality you need, but you can’t change it to provide the correct interface • Example: an existing class works with a database to create csv documents and makes them available though a getter, but your other code needs to get .xls documents. Solution: write an adapter that implements the interface you need, and that calls the getter in the existing class and then converts the csv to xls. • Adapter is particularly useful when two existing applications need to communicate; suppose the registrar and the financial aid office use systems with different Student classes, but each needs to get information from the other. • Adapter is also commonly used to help applications use libraries. • Suppose you find another graph library that you like better than JFreeChart, but want to minimize changes to your existing lab 6 code.Write a set of adapters with the interfaces you are already using, and which then use the new library in the background.
Adapter Pattern Source: http://refcardz.dzone.com/refcardz/design-patterns This shows Adapter as an interface. If there will be many types of adapters that are only slightly different from each other, Adapter could be an abstract class instead.