Download Notes - People.cs.uchicago.edu

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Lesson 7
Applets
Jar files
Graphics
A little more Swing
Part I:
Very Basic Applets
Programs that run within web
browsers
What are applets?
 Applets are simply java programs that run in web
browsers.
 Created a big stir in mid-90’s when Netscape
agreed to embed jvm in Navigator web browswer.
 Great promise – applications automatically
distributed to anyone on any platform!
 Reality – non-uniform browswer support,
limitations imposed by security, easier ways to
accomplish same thing!
What are applets, cont.
 Still useful in just the right situation
– fancy, full-fledged client
– can make some assumptions/have some control over
client technology
 Also, very good for understanding issues in web
client-server programming
 Otherwise, server-heavy programming with html
or client-side scripting wins out.
 Also, Java WebStart new alternative
– can launch full applications remotely without need for
host browser
Applet inheritance tree
Object
Component
Container
Window
Panel
Frame
Applet
JFrame
JApplet
Use to access
Swing Components
Some Hello World Applets
 To see how applets work, we start with a
couple of versions of a HelloWorld program
– One uses the fact that an Applet is a Panel with
a graphics object
– The other uses a button label
 Soon, we will add full event-handling
capabilities and nice graphics. This is just a
start.
HelloWorldApplet1
import java.awt.*;
import javax.swing.*;
public class HelloWorldApplet1 extends JApplet{
public void init(){
getContentPane().add(new JLabel(
“Hello World”,
SwingConstants.CENTER));
}
}
• Note that all Applets are class that extend either
Applet or JApplet
• init() is called when the Applet is loaded
HelloWorldApplet2
import java.awt.*;
import javax.swing.*;
public class HelloWorldApplet1 extends JApplet{
public void painComponent(Graphics g){
g.drawString(“Hello World”, 50, 50);
}
}
• Since Applets are Panels, we can override PaintComponent
and get a Graphics Object
• This will become particularly handy when doing animations
Running Applets
 To run applets, do the following:
– Compile class file in regular way
– Create an html file that includes an applet tag pointing
to the applet
<applet code = “Appletname.class” width = 200 height =
50></applet> (width and height are pixel coords)
– Invoke browser or appletviewer on html file
 Note that applet tag can include other parameters,
some of which of used by browser automatically
(e.g. width).
 Also, Java2 plug-in required for browsers to
support applets. Good to test with appletviewer
first.
Life Cycle of Applet
 To write more sophisticated applets, a
number of other methods may need to be
overwritten.
–
–
–
–
void init()
void start()
void stop()
void destroy()
 We discuss the role of each next.
init() method
 The browswer calls the init method when the
applet is loaded for the first time.
 init() behaves much like a constructor.
 Typical uses:
–
–
–
–
parsing param values from html files
opening streams and sockets
creating GUI components
opening database connections
 Important: note that the refresh button doesn’t
necessarily reload applet. This is browserdependent. To guarantee reloading, browser needs
to be killed and restarted.
start() method
 called every time page is located
– this can mean moving off and back onto page, hitting
reload, etc.
 always called after init() when page is first loaded.
 Typical uses:
– starting animations
– anything else that needs to start anew with every
location of applet
– for simpler things this method can be ignored
stop() method
 called whenever user moves off the page
where applet sits
 always called after start
 typical uses
– ending animations
– stopping other time-consuming system activity
 often ignore this for simpler applets
destroy() method
 called once when browser shuts down
normally
 always called after stop()
 typical uses:
– close database connections
– close streams
– clean up any other resources
 often ignored for simpler applets
More on applet life-cycle
 It’s very import to be aware that some other
software, ie the host browser, is calling these
methods at certain times.
 You the program do not call these methods.
 This is classic OO framework: “don’t call us, we’ll
call you”.
 You write the class and specialize certain methods,
some other code calls your custorm versions of
those methods at specified times.
Other applet issues
 Security
– Horstmann pg. 499
 Pop-up windows
– Horstmann pg. 500
 Applet tags and attributes
– Horstmann pg. 502
 Passing info to applets
– Horstmann pg. 506
 Applets making socket connections
Jar Files
Packaging java applications
What is a jar file?
 JAR: Java Archive
– typical way of distributing java applications/libraries
 JARs are ZIP files containing
– java class files
– possibly other resource files (images, audio, text, etc.)
– optional manifest file: describes certain attributes of
JAR file.
 Applets, beans, applications typically all
distributed as single of collection of JAR files.
Creating JAR Files
 Either use commandline tool like
– jar cvf whatever.jar *.class
or API
– see java.util.jar docs
 No name restrictions for jar file – whatever is
legal on a given platform
 Can jar directories as well as files. In that case,
contents are added recursively
 Syntax similar to tar. See
http://java.sun.com/docs/books/tutorial/jar
for more details
Self-running JAR files
 jars can get quite complex when using with J2EE.
– Manifest files can be used to specify security attributes,
versioning, extensions, services, etc.
 Also, for better performance multi-class applets
can be packaged as jar files.
 Course web page contains links to more detailed
info on creating sophisticated JARs
 Here were present executable JAR files as a
simple example.
Steps to making executable jar
 To make an executable jar, take the following
steps:
– create a .jar of all class files in your application using
jar cvf Whatever.jar *.class
(packages and nested directories work fine here).
– create a manifest file with any name (say manifest.mf).
manifest.mf must at least contain a line pointing to the
main class, e.g.:
Main-Class: com/mypackage/MainAppClass
– finally, add manifest using the update flag u
jar uvfm Whatever.jar manifest.mf
– run as “java –jar Whatever.jar”
Gotchas
 Manifest file must contain linefeed as last
character or else won’t be parsed properly.
 You should always use packages with jar
files.
– be careful to put full pathname to Main-Class.
Other issues
 Launching a jar from an icon
– System dependent. See Horstmann.
 Locating Resources
– See URL class
 Sealing JARs
– Sealed: true attribute in manifest file
 Signing JARs
– can give trusted permission to trusted parties.
– See web link above for more details
Overriding Object Methods
The Object Class
 Every java class has Object as its superclass and
thus inherits the Object methods.
 Object is a non-abstract class
 Many Object methods, however, have
implementations that aren’t particularly useful in
general
 In most cases it is a good idea to override these
methods with more useful versions.
 In other cases it is required if you want your
objects to correctly work with other class libraries.
Some Object class methods
 Object methods of interest:
– clone
– equals
– hashcode
– toString
– finalize
 Other object methods
– getClass
– wait, notify, notifyAll (relevant for threaded
programming)
Clone method
 Recall that the “=“ operator simply copies Object
references. e.g.,
>> Student s1 = new Student(“Smith”, Jim, 3.13);
>> Student s2 = s1;
>> s1.setGPA(3.2);
>> System.out.println(s2.getGPA());
3.2
 What if we want to actually make a copy of an
Object?
 Most elegant way is to use the clone() method
inherited from Object.
Student s2 = (Student) s1.clone();
Subtleties of clone() method
 First, note that the clone method is
protected in the Object class.
 This means that it is protected for
subclasses as well.
 Hence, it cannot be called from within an
Object of another class and package.
 To use the clone method, you must override
in your subclass and upgrade visibility to
public.
More subtleties of clone
 Also, any class that uses clone must
implement the Cloneable interface.
 This is a bit different from other interfaces
that we’ve seen.
 There are no methods; rather, it is used just
as a marker of your intent.
 The method that needs to be implemented is
inherited from Object.
More clone() issues
 Finally, clone throws a
CloneNotSupportedException.
 This is thrown if your class is not marked
Cloneable.
 This is all a little odd but you must handle
this in subclass.
Steps for cloning
 To reiterate, if you would like objects of
class C to support cloning, do the following:
– implement the Cloneable interface
– override the clone method with public access
privileges
– call super.clone()
– Handle CloneNotSupported Exception.
 This will get you default cloning, but more
subtleties still lurk.
Shallow Copies
 We haven’t yet said what the default clone()
method does.
 By default, clone makes a shallow copy of all iv’s
in a class.
 Shallow copy means that all native datatype iv’s
are copied in regular way, but iv’s that are objects
are not recursed upon – that is, references are
copied.
 This is not what you typically want.
 Must override clone explicitly clone object iv’s!
Immutable Objects
 A special class of Objects are called immutable
because their state cannot be changed once set.
 Common examples are String, Integer, etc.
 Immutable object simplify programming in certain
instances, such as when writing thread safe code.
 They also simplify cloning, since an object that
cannot be changed doesn’t really need to be deepcopied.
 See ShallowCopy2.java in course examples
Deep Copies
 For deep copies that recurse through the
object iv’s, you have to do some more work.
 super.clone() is first called to clone the first
level of iv’s.
 Returned cloned object’s object fields are
then accessed one by one and clone method
is called for each.
 See DeepClone.java example
Additional clone() properties
 Note that the following are typical, but not
strictly required:
–
–
–
x.clone() != x;
x.clone().getClass() == x.getClass();
x.clone().equals(x);
 Finally, though no one really cares,
Object does not support clone();
toString() method
 The Object method
String toString();
is intended to return a readable textual
representation of the object upon which it is
called. This is great for debugging!
 Best way to think of this is using a print statement.
If we execute:
System.out.println(someObject);
we would like to see some meaningful info about
someObject, such as values of iv’s, etc.
default toString()
 By default toString() prints total garbage that no
one is interested in
getClass().getName() + '@' + Integer.toHexString(hashCode())
 By convention, print simple formatted list of field
names and values (or some important
subset).
 The intent is not to overformat.
 Typically used for debugging.
 Always override toString()!
equals() method
 Recall that boolean == method compares when
applied to object compares references.
 That is, two object are the same if the point to the
same memory.
 Since java does not support operator overloading,
you cannot change this operator.
 However, the equals method of the Object class
gives you a chance to more meaningful compare
objects of a given class.
equals method, cont
 By default, equals(Object o) does exactly
what the == operator does – compare object
references.
 To override, simply override method with
version that does more meaningful test, ie
compares iv’s and returns true if equal, false
otherwise.
 See Equals.java example in course notes.
equals subtleties
 As with any method that you override, to do
so properly you must obey contracts that go
beyond interface matching.
 With equals, the extra conditions that must
be met are discussed on the next slide:
equals contract
 It is reflexive: for any reference value x, x.equals(x)
should return true.
 It is symmetric: for any reference values x and y,
x.equals(y) should return true if and only if
y.equals(x) returns true.
 It is transitive: for any reference values x, y, and z, if
x.equals(y) returns true and y.equals(z) returns true,
then x.equals(z) should return true.
 It is consistent: for any reference values x and y,
multiple invocations of x.equals(y) consistently return
true or consistently return false, provided no
information used in equals comparisons on the object
is modified.
 For any non-null reference value x, x.equals(null)
should return false.
hashcode() method
 Java provides all objects with the ability to
generate a hash code.
 By default, the hashing algorithm is
typically based on an integer representation
of the java address.
 This method is supported for use with
java.util.Hashtable
 Will discuss Hashtable in detail during
Collections discussion.
Rules for overriding hashcode
 Whenever invoked on the same object more than once, the
hashCode method must return the same integer, provided no
information used in equals comparisons on the object is modified.
 If two objects are equal according to the equals(Object) method,
then calling the hashCode method on each of the two objects
must produce the same integer result.
 It is not required that if two objects are unequal according to the
equals(java.lang.Object) method, then calling the hashCode
method on each of the two objects must produce distinct integer
results. However, the programmer should be aware that producing
distinct integer results for unequal objects may improve the
performance of hashtables.
finalize() method
 Called as final step when Object is no longer used,
just before garbage collection
 Object version does nothing
 Since java has automatic garbage collection,
finalize() does not need to be overridden reclaim
memory.
 Can be used to reclaim other resources – close
streams, database connections, threads.
 However, it is strongly recommended not to rely
on this for scarce resources.
 Be explicit and create own dispose method.
A little more Swing
MVC Pattern
More graphics
Graphics
 See course examples
– applets/BrownianMotionApplet.java
• shows how to do a simple animation with some basic drawing
in the start() method
– graphics/Mandelbrot.java
• shows how to create an image from raw data and draw to an
applet by overriding paintComponent.
– graphics/Shapes.java
• A great example of how to architect a simple GUI that seems
more complex when poorly designed.
– graphics/Painter.java
• Classic example of how to paint on a Panel
– graphics/Bounce.java
• Classic example of why one needs threads.
Miscellaneous
Some how-to snippets
 See the following codes in the course
examples
– GetProperties.java
• How to query various system properties
– ProcessTest.java
• An example spawning an OS executable
– NumberFormat.java
• An example formatting a double
– TimeTest.java
• An example using simple System timers.