Given by Nancy McCracken at CPS616 spring 1997 on Feb 3 1997. Foils prepared 4 February 97
Abstract * Foil Index for this file
Secs 79.2
See also color IMAGE
AWT Components , Actions and Layout Managers |
Skip over Thread Details |
Important Java Classes including Object class |
I/O and File Operations |
Security Concerns in Applets |
URL's and Networking |
This table of Contents Abstract
Instructor: Nancy McCracken |
teamed with Meryem Ispirli, Geoffrey Fox, |
Tom Scavo, John Yip |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
AWT Components , Actions and Layout Managers |
Skip over Thread Details |
Important Java Classes including Object class |
I/O and File Operations |
Security Concerns in Applets |
URL's and Networking |
In Java, the GUI (Graphical User Interface) is built hierarchically in terms of Components -- one Component nested inside another starting with the smallest Buttons, including Menus, TextFields etc. and ending with full Window divided into Frames, MenuBars etc. |
Not all useful Classes are inherited from Component. For instance Menu inherits from MenuComponent (interface) --> MenuItem --> Menu |
One also needs a set of methods and classes to define the layout of the Components in a particular Panel |
LayoutManager is a java.awt interface with several particular layout strategies implemented as classes under this interface |
The Container class has methods to interact with LayoutManager classes |
In the simplest use of AWT, one could add a Button to an Applet (grandchild of Container) using in the init() method for Applet
|
The various added Components are put in the panel by the LayoutManager using order in which they were added |
A Final critical part of the AWT is the actions generated by these components which are processed by overriding the action() method in Component
|
We define extra events -- such as those connected with scrolling or selecting buttons to those of basic mouse/keyboard |
This is incomplete! |
add(new Label("aligned left")); // default alignment |
produces a text string using constructor Label of Label class |
add(new Button("Grade is A")); |
add(new Button("Grade is B")); // surely this is lowest grade for a course on such an easy language? |
Checkbox's are on-off toggles implemented as |
add(new Checkbox("Red")); |
add(new Checkbox("Green")); |
add(new Checkbox("Blue"),null, true); |
The first two are initially set to "false" as the optional third argument is not given. The last one is initially set to "true". |
The state of a checkbox, i.e. whether it is checked, is given by the method, getState: |
Checkbox cb = new Checkbox("Red"); |
add (cb); |
. . . |
if (cb.getState()) . . .; |
Radiobuttons are identical to Checkbox's but grouped so that only one checkbox in a group can be on at a time. They use same class for buttons but add CheckboxGroup class |
CheckboxGroup cbg = new CheckboxGroup(); |
cb1 = new Checkbox("Red", cbg, false)); |
cb2 = new Checkbox("Green", cbg, false)); |
cb3 = new Checkbox("Blue", cbg, true)); |
add(cb1); add(cb2); add(cb3); |
In addition to checking the state of checkboxes in a group, the method getCurrent returns the one checkbox which is on:
|
Choice is a class that gives a menu where you choose from various items |
TextField is a simple class where user can enter information into fields |
TextArea is a somewhat more sophisticated text entry area which are scrollable and so useful where amount of data to be entered is unlimited |
List is another child of Component that is similar in use to Choice but gives a fixed size list which can be scrolled and where you can select one or more entries |
Scrollbar is a class that defines a horizontal or vertical scrollbar. Note this is distinct from scrollbars that come with TextArea and List |
To add a text field for display or input one line of text (in this case, 30 characters wide):
|
The text which is displayed can be changed:
|
If the user can type input into the text field, it can be obtained:
|
Or you can disallow the user to type:
|
The TextArea class also has these methods, but it can display multiple lines. |
Canvas is a simple class which are used to draw on as in artist's canvas. They cannot contain other components. This is the class on which you use the graphics methods. |
Upto now, we have described how to build typical Applet panels inside browser window. There are classes that allow one to generate complete windows separately from the browser window |
Window Class has subclasses Frame and Dialog |
Frame("TitleofWindow"); // creates a window with memubar and given title
|
A Frame has a set of classes to define MenuBars and Menus:
|
Another type of separate window is the Dialog box, which is not so elaborate as a frame.
|
Dialog boxes are used for transient data
|
We already discussed handling Mouse and Keyboard Events. These AWT components come with new actions which need to be handled with an action() method in your applet |
Put action ( a method of class Component) in Container instance that is at lowest possible level so you can customize action to things in that Container |
action(Event evt, Object arg)'s are looked for in same fashion as exceptions. Scan up Containers looking for a method of this name. Scanning stops when you find an action and that method returns true |
evt.target holds the object that caused the Event |
Object Arg returned depends on particular Component invoked |
There are further evt.id's associated with the various peculiar Components -- see description of class Event for current detailed description. |
Suppose we have a bunch of buttons in a particular Container saying Red, Green, Blue as we illustrated earlier. Then an action method would be
|
In general, declare names for all components such as labels, buttons and textfields, and use the variable evt.target to distinguish which component generated the action. |
Suppose we have a bunch of buttons in a particular Container saying Red, Green, Blue as we illustrated earlier. Then an action method would be
|
The various panels in a container are laid out separately in terms of their subcomponents |
One can lay components out "by hand" with positioning in pixel space |
However this is very difficult to make machine independent. Thus one tends to use general strategies which are embodied in 5 LayoutMangers which all implement the LayoutManager Interface. One can expect further custom LayoutManager's to become available on the Web |
setLayout(new FlowLayout()); // creates a basic flow layout in your panel -- actually unnecessary as default |
Other available LayoutManager's are GridLayout(), BorderLayout() (default for Frame's), CardLayout() (Used for dynamic layouts) and GridBagLayout() (the most flexible) |
BorderLayout has five cells called North South East West Center and components are assigned to these cells with the add method. As used in a window, one would naturally use:
|
Remember this is default for a Frame Container |
FlowLayout is a one dimensional layout where components are "flowed" into panel in order they were defined. When a row is full up, it is wrapped onto next row |
GridLayout is a two dimensional layout where you define a N by M set of cells and again the components are assigned sequentially to cells starting at top left hand corner -- one component is in each cell |
GridBagLayout uses a new class GridBagConstraints to customize positioning of individual components in one or more cells |
CardLayout lays out in time not space and each card (Displayed at one time) can be laid out with one of spatial layout schemes above |
This simple layout manager starts putting components in the window from the top left, continues across the row until there is no more room, starts the next row, and so on. The components can be aligned, and space between them given by the arguments hgap and vgap. |
setLayout(new FlowLayout(FlowLayout.LEFT, 5, 1); |
setLayout(new FlowLayout(FlowLayout.CENTER); |
setLayout(new FlowLayout(FlowLayout.RIGHT); |
Layout's can be made very sophisticated using an hierarchical approach |
setLayout(new GridLayout(1,3,10,5));
|
subpanel1 = new MysubpanelClass(); // Add arguments to make subpanel1 special |
subpanel2 = new MysubpanelClass(); |
add(Some Simple Component such as a Button); |
add(subpanel1); |
add(subpanel2); |
. . . . . |
Class MysubpanelClass extends panel { // has constructor |
MysubpanelClass() { // that includes another layout such as |
setLayout(new GridLayout(2,2,5,5); // etc. |
A simple example of using the Abstract Windowing Toolkit divides the applet space into two components. One is a Canvas for drawing graphics or images; one is a Panel which has three buttons. We choose to draw the Canvas within the Applet and to create the Panel in another class. |
The initialization of the Canvas was done in the applet init method; the other method for painting the Canvas simply changes the background color. About the only thing a Canvas can do is explicit drawing and graphics. |
This class does not need to be a subclass of Applet - like all components except Canvas, you don't need to paint, just add components and handle events and actions. |
The Button component generates an action whenever the button is clicked on. In this example, we call the method that changes the color of the Canvas in another part of the layout. |
Instructors: Geoffrey Fox , |
Nancy McCracken |
Syracuse University |
111 College Place |
Syracuse |
New York 13244-4100 |
public class Object is the root of the Class hierarchy. Every java class has Object as its ultimate parent and so any object (object with a small o is any instance of any class) can use methods of Object |
Methods of Object (used as object.Method()) include: |
clone() Creates a clone of the object |
equals(another object) compares two objects returning boolean answer |
getClass() returns a descriptor of type Class (a child of Object) defining class of object |
toString() returns a String which represents "value" of object. It is expected that each subclass will override this method |
wait() in various forms is used to cause threads to wait |
finalize() contains code to perform when object is deleted by system (I.e. garbage collected) |
Suppose an object is called obj , then we get Class of obj by |
Class itsclass = obj.getClass(); // and the name of this class by: |
String name = itsclass.getName(); |
One can also use instanceof in following fashion |
"foo" instanceof String // is evaluated to true but |
mPoint pt = new mPoint(x,y); |
pt instanceof String // is evaluated to false |
"types" such as int char float etc. are NOT classes |
Thus one cannot use methods such as |
int var; |
var.toString |
Thus ALL types have associated wrappers used like |
Character wrappedchar = new Character(char); |
now wrappedchar has lots of good methods you can use such as: |
wrappedchar.equals(anotherobject); |
wrappedchar.toString(); |
There are also static (class) functions such as: |
toUppercase(char ch); |
isUpperCase(char ch); |
This class provides the standard mathematical functions, using types int, long, float and double as appropriate. |
It is a static class, meaning that you only use the methods, never creating objects from this class. |
The methods include
|
This class exists to provide an implementation of "date" structures. As is typical of data encapsulation classes, it has methods to create dates, obtain and set the parts of dates, and convert dates to other data types. |
The constructor either creates today's date or any other day (and time) that you provide:
|
Strings are fixed length collections of Unicode characters stored as an instance of the class. |
Most commonly, a string is created from a string literal or by using the constructor on an array of characters:
|
or
|
Once created, individual characters of a string cannot be changed in place. This example shows using the methods of indexing, catenation (+), and substring to create a new string with one character changed:
|
String comparison can be done with the methods equals and equalsIgnoreCase. Note that == tests if two strings are the same string instance, while equals tests if two different strings have the same characters. |
Other methods include length, CharAt and toString. |
The StringBuffer class has mutable strings, but is created with a fixed maximum size. It has methods such as append to extend the length of the string. |
This class returns object of class String which reverses order of characters in input object source which is also an instance of class String |
class ReverseString {
|
In Java, while you can give the size of arrays at run time, you cannot dynamically change the size of an array during the computation. The vector class provides a data structure with this property - the restriction is that all of the elements must be of type Object.
|
A vector is created with an "initial capacity" and a "capacity increment". It always starts with 0 elements. As you add elements, if the initial capacity is exceeded, then more memory is automatically allocated in the size of the capacity increment. The default is an initial capacity of 10 and an increment which doubles each time.
|
Elements are created with the addElement method:
|
The object missouri of type Order is automatically converted to an Object in vector instance orders defined on previous foil. |
There are methods for indexing vectors. Like arrays, the indexing is zero-based.
|
The length of the Vector can be obtained:
|
This class is similar to the Perl associative array (or hash array with {} brackets). It can store a set of key and value pairs, neither of which can be null.
|
Values are retrieved by indexing with a key. Like Vectors, Hashtables only store things of type Object and you must cast the result.
|
If there was no entry, a null is returned. |
Performance of the Hashtable can also be affected by giving an initialCapacity and a loadFactor for reallocation. |
Streams are an abstraction of a sequence of bytes. |
The sources and destinations of these sequences can be
|
That is, all of these types of I/O are treated in the same way. |
The most basic I/O streams are InputStream and OutputStream. These classes have methods that can read or write a byte from the stream:
|
There are also methods for reading and writing arrays of bytes. |
These methods all "block" on the read or write during the data transfer. |
The subclasses of InputStream offer more methods that can read the stream in a more structured way or provide other functionality. |
Standard UNIX file I/O methods are available |
FileInputStream s = new FileInputStream("/usr/gcf/greatidea"); |
There is a clever class called FilterInputStream which can be used to add value to a raw InputStream. You can define your own filters but important ones provided are:
|
These streams can be constructed from each other or InputStream to give added functionality. If "is" is an InputStream, then it can be converted to a buffered input stream with methods from datainputstream: |
DataInputStream data = new DataInputStream(new BufferedInputSream(is)); |
This area will evolve rapidly as existing I/O systems get linked to Java with special classes such as those needed to link MPI (HPCC Message Passing) or Nexus (Well known distributed memory thread package) |
One can establish Web Connection with URL class and access documents there |
One can set up a more general URLConnection for more general input/output operations through Web(HTTP) protocol |
One can set up a Socket link which is permanent rather than on again off again Web client-server interaction |
One can send messages and so transfer information between different Applets |
One aspect of Java security is language restrictions designed not to let a Java applet or application access memory on the machine outside of its own space. |
Applets have additional restrictions:
|
As of summer 1996, no known applets have seriously broken security to steal client information or trash the local disk. Exceptions:
|
This table shows what Java programs can do in the following four cases:
|
First you set the URL in various ways using something like |
String npacurl = "http://www.npac.syr.edu/index.html"; |
try {theinputurl=newURL(npacurl);} // URL class is in java.net |
catch ( MalformedURLException e) {
|
where you are meant to test to see if URL is legal! |
The simplest thing to do now is to see this page with |
getAppletContext().showDocument(theinputurl, Frame targetdisplayframe); |
More interesting is to access a URL and process the information there! |
This is done using streams: |
There are methods in class URL -- |
InputStream in = instanceofURL.openStream(); // opens an InputStream associated with given url |
More general is instanceofURL.openConnection() establishes a general connection and returns an instance of class URLConnection
|
Note that one can connect not just to HTML files but also to CGI scripts i.e. programs at server and so obtain flexible connectivity |
This applet creates a text area in the window, reads text from a file known by its URL, and displays the text in the text area. It uses the class URL from java.net, to set up a socket to the server, and the class InputStream from java.io. |
The openStream method opens the socket connection and returns an object of type InputStream. We convert this to a BufferedInputStream for performance and then to DataInputStream, where we have methods to read lines or characters of data. |