1.09k likes | 1.3k Views
GSAMS’ Un distinguished Lecture Series presents . . . Graphical User Interfaces: Applets, Graphical Applications, Events & Interfaces. Lecture Contents. GUIs and the Java AWT “Graphical User Interfaces” / “Abstract Windowing Toolkit” Components as elements of presentation and interaction
E N D
GSAMS’Undistinguished Lecture Seriespresents . . . Graphical User Interfaces:Applets, Graphical Applications,Events & Interfaces
Lecture Contents • GUIs and the Java AWT • “Graphical User Interfaces” / “Abstract Windowing Toolkit” • Components as elements of presentation and interaction • Composition of UIs with containers of components • Layout of components within containers • Interaction with GUIs through event-driven programming
Graphical User Interface (GUI) • The name for one variety of “user interface” (UI). • An interface in which the user interacts with objects on the screen (icons, buttons, scroll-bars, etc.) via mouse clicks or keyboard actions. (Expressed in the Seeheim model.) • Popularized in 1980s by the Macintosh. • Now state of the practice, and not final word in UI • Replaced text-based “command line” • and “function key” interfaces. • Despite similarities, GUIs are typically • platform-specific (Windows 95/98/NT, • MacOS, Xt, NeWS)
The AWT(Abstract Windowing Toolkit) • How Java implements a platform-independent GUI (Graphical User Interface) on different platforms. • API to the JVM’s “virtual” user interface • Java 1.0 & 1.1 GUIs were quite bland because of the need to be platform-independent. • Related: Java 1.2’s “Swing” classes • create fully-functional GUIs for Java
Steps to GUI Construction • In Java, to create a GUI, you (1): • Specify a Container, using . . . • a Layout Manager to . . . • place Components and/or Containers of Components . . . • on the screen as desired. I.e. UI form and appearance I.e. UI interaction and behavior • In Java, to make a GUI act as the interface for a program, you (2) • Design human/computer dialog, using Listeners and component-generated events
Lecture Contents • GUIs and the Java AWT • “Graphical User Interfaces” / “Abstract Windowing Toolkit” • Components as elements of presentation and interaction • Classes of components & the AWT class hierarchy • Example declaration & presentation Java code • Composition of UIs with containers of components • Layout of components within containers
GUI Components • Most interactionsin a Java GUI are with Components. • Another generic term for Component in other GUIs (e.g. X Windows) is "widget". • Different types of components for different types of • interaction (e.g. buttons, etc.) • User interactions with components create events (thus, event-driven programming) • As a rule, components cannot have • other components added to them • Exception to rule: pop up menus may • have menu items added to them.
The AWT Component Class Hierarchy Component - generic widget that you can interact with Button - a widget that you can press Canvas - a widget that you can draw on Checkbox - a widget that is checked or not checked Choice - an option menu that drops down Container - a generic class that contains Components Panel - a container to be used inside another container; used to split an existing window Label - a single line of read-only text List - a list of Strings Scrollbar - a horizontal or vertical scrollbar TextComponent TextArea - multi-line editable text TextField - single-line editable text
Components--Examples • Canvas: • typically a drawing surface on which shapes, graphs, pictures, etc can be drawn. • utilize mouse events and mouse motion events to interact with the user to accomplish the drawing tasks. • TextField: • a one-line data entry area • theoretically infinite in length • can generate Key events to indicate that • the user has typed a key • more typically, it generates an Action event • when the user finishes the data entry and • hits Return in the TextField.
Components--Examples • Button: • simply a clickable label-like component • appears as a standard button on whatever graphical environment the user happens to be running at the time • generates an Action event when clicked • Label: • a one-line field of text. • user cannot change this text directly; program changes text with setText( ) method. • usually not used to capture events (but could) • usually used as a one-way information source • to provide a message to the user.
GUI Containers • Containers are special components that may contain other components with which the user interacts. • Examples of Containers: • Panels • Frames • Applets • Note: Containment is not the same as extension. • A Frame may contain buttons, • but buttons are not subclasses of • Frame.
Containers • Containers are components which can have: • Layouts set on them • Other components or containers added to them. • The types of containers include: • 1. Applet: • Generally (but not always) embedded in HTML; • Is automatically created for you as the area of the web browser or appletviewer in which the applet loads. • A class that extends Applet: • Is automatically an Applet container, • Can have a layout set on it and components/containers added to it.
Containers • 2. Frame: • Represents a window on the screen. • Can have Menu bars on them for pull-down menus • Can be positioned on the screen via such methods: • public void setBounds(int x, int y, int width, int height) • public void setLocation(int x, int y); • 3. Panel: • Is intended as a container/component that can be added to another container's layout to produce an embedded or multi-level layout. • Clever use of panels and layouts within • the panels can produce professional • and complex interface designs.
Selecting a Container Common Top-Level Containers: Frame -- familiar window object with scrollbars, etc. Window -- more basic window object, no scrollbars, etc. Applet -- embedded byte code inside HTML document. Instantiation: Note: Frames and Windows not self-disposing. (GUI components use more than just memory: Only memory is garbage-collected by the JVM. Other resources have to be reclaimed manually by dispose() ) Frame myFrame = new Frame(); myFrame.setLayout(new FlowLayout()); myFrame.add(myButtonInstance); . . . /* when done */ myFrame.dispose(); /* (event handling to come shortly . . .) */
Containers -- Applets • Special types of containers • -- embedded inside HTML document, between tags: • <HTML> • <APPLET code = “MyApplet.class” • WIDTH = 400 HEIGHT = 300> • </APPLET> • </HTML> • Applets have no main(String arg[]) method • -- supplied by browser instead • -- Applet lifecycle: • public void init () • /* a main() ‘substitute’ */ • public void start () • public void paint (Graphics g) • public void stop () • public void destroy () Minimum params; others possible
Containers -- Subclassing import java.applet.Applet; import java.awt.*; class myApplet extends Applet { public void init () { //define what happens here } public void start () { //define what happens here } public void paint (Graphics g) { //define what happens here } public void stop () { //define what happens here } //...etc... } Generally: Applets use inheritance while Frames use composition and/or inheritance
The Applet ‘Sandbox’ Model Applet code runs in 'sandbox’ within the VM, with significant restrictions on what it can do. This is enforced by the SecurityManager class Work-arounds for applet security restrictions include digitally signing code, servlettes, etc. Applications can similarly invoke SecurityManager objects
The Applet ‘Sandbox’ Model Untrusted code cannot: • Read files (except from host URL) • List Directories • Obtain file information (existence, size, date, etc.) • Write, Delete, Rename files or directories • Read or write from FileDescriptor objects • Listen/Accept on any privileged port <= 1024 • Call System.exit() or Runtime.ext() • Create new processes with Runtime.exec() • Start a print job, access clipboard or event queue Remaining weak-spot: Denial of Service Attacks • Get full access to System.getProperty(), but it can • use getProperty() to find: • java.version, java.class.version, java.vendor, • java.vendor.url, os.name, os.version • os.arch, file.separator, path.separator, • line.separator
Applet Example /** * * ReadsFromURL.java -- a trivial applet demonstrating * how to read server-side data via a URL stream * * The applet also uses heavyweights, causing * slow redraws * */ import java.awt.*; import java.applet.*; import java.net.*; import java.io.*; public class ReadsFromURL extends Applet { protected URL fileURL; protected String result; protected TextArea ta; protected int off = 15;
/** * Default constructor * */ public ReadsFromURL() { // default constructor for some fussy VMs } /** * initialize the applet * * @see#readInURL() -- called to initialize data */ public void init(){ setBackground(Color.lightGray); ta = new TextArea(); ta.setFont(new Font("Courier", Font.BOLD, 12));
/* * Set server to read applet source code */ try { fileURL = new URL (getCodeBase() + "/ReadsFromURL.java"); } catch(MalformedURLException e){ showStatus("Error!"); } /* * Layout the container */ this.setLayout(null); // necessitates setBounds() add(ta); ta.setBounds(getSize().width/8, getSize().height/8, getSize().width*3/4, getSize().height*3/4); readInURL(); }// init
/** * paint the applet, including borders, bevels, and * screws * */ public void paint(Graphics g) { // bevels for (int w=0; w<getSize().width; w+=12) { for (int h=0; h<getSize().height; h+=12) { g.setColor(Color.white); g.drawLine(w,h,w+1,h); g.drawLine(w+1,h,w+5,h+4); g.drawLine(w+8,h+10,w+12,h+6); g.drawLine(w+12,h+6,w+13,h+6); g.setColor(Color.darkGray); g.drawLine(w,h+2,w+5,h+7); g.drawLine(w+5,h+7,w+6,h+7); g.drawLine(w+9,h+12,w+13,h+8); } }
/* borders */ g.setColor(Color.gray); g.fillRect(0, 0, getSize().width, off); g.fillRect(0, 0, off, getSize().height); g.fillRect(getSize().width-off,0, off,getSize().height); g.fillRect(0,getSize().height-off, getSize().width, off); g.fillRect(0,0,2*off, 2*off); g.fillRect(getSize().width-2*off,0, 2*off, 2*off); g.fillRect(0, getSize().height-2*off, 2*off, 2*off); g.fillRect(getSize().width-2*off, getSize().height-2*off, 2*off, 2*off); int dX, dY; int x1=off; int x2=2*off; int x3=getSize().width-(1+2*off); int x4=getSize().width-(1+off); int y1=off; int y2=2*off; int y3=getSize().height-(1+2*off); int y4=getSize().height-(1+off);
g.setColor(Color.black); g.drawLine(x4,y2,x3,y2); g.drawLine(x3,y1,x2,y1); g.drawLine(x2,y1,x2,y2); g.drawLine(x2,y2,x1,y2); g.drawLine(x1,y2,x1,y3); g.drawLine(x2,y3,x2,y4); g.setColor(Color.white); g.drawLine(x3,y1,x3,y2); g.drawLine(x4,y2,x4,y3); g.drawLine(x4,y3,x3,y3); g.drawLine(x3,y3,x3,y4); g.drawLine(x3,y4,x2,y4); g.drawLine(x2,y3,x1,y3); //raised outer edge g.setColor(Color.black); g.drawRect(0,0, getSize().width-1, getSize().height-1); g.setColor(Color.white); g.drawLine(0,0, getSize().width-1,0); g.drawLine(0,0,0, getSize().height-1);
//screws for (int x=2;x-->0;){ for (int y=2;y-->0;){ dX=(x==1)?0:x3; dY=(y==1)?0:y3; g.setColor(Color.white); g.drawArc(dX+off/2+1,dY+off/2+1, (int)1.5*off,(int)1.5*off,90,100); g.drawLine(dX+(int) (1.25*off)+2, dY+(int) (.75*off), dX+(int) (.75*off)-1, dY+(int) (1.5*off)-1); g.setColor(Color.black); g.drawOval(dX+off/2,dY+off/2, (int)1.5*off,(int)1.5*off); g.drawLine(dX+(int) (1.25*off)+1, dY+(int) (.75*off)-1, dX+(int) (.75*off)-2, dY+(int) (1.5*off)-2); } } }// paint
public void readInURL() { try { String strTemp; java.io.InputStream input = fileURL.openStream(); BufferedReader buff = new BufferedReader (new InputStreamReader(input)); while((strTemp = buff.readLine()) != null) ta.append(strTemp+"\n"); /* Be a good net neighbor and close the stream! */ buff.close(); } catch(IOException darn){ showStatus("Exception: " + darn); } }// readInURL }// class ReadsFromURL
GUI Layout • The problem • How should components be laid out within a container? • (Why is this a problem? Because platforms may differ in screen size / resolution) • AWT Solution • Layout Managers are AWT classes that encapsulate policies for laying out components in a container • Can ensure that the arrangement of objects within a window will remain proportional regardless of changes in window dimensions. • Example of general OOD strategy of putting • rules/policies in a coordinator/referee class. • A layout manager is always associated • with a container
Layout Managers -- Motivation • One could specify the location of a Component by specific x and y coordinates. The Component class contains the method setLocation(int width, int height): • Button myButton = new Button (“Click”); • add(myButton); // adds to whatever ‘this’ container is • myButton.setLocation(25, 75); NOTE: Origin 0,0 at top left 75 pixels down Click Note: Button’s x and y coordinate starts from top left 25 pixels over
Layout Managers -- Motivation • Problems with specifying x, y coordinates for Component: • Tedious for even mildly complex GUIs. • Addition of more components requires recalculation of every component’s x, y coordinate • If container resizes (e.g., user expands window), calculations have to be redone! • Solution: • Position components based on a percentage • of available container size. Or create an • algorithm to place components . . . • But Java already does this for you . . .
Layout Managers -- AWT Based • Java provides several layout managers. • We will concentrate here on two of them: • BorderLayout • GridLayout • To tell a container which layout manager to use, invoke the method: • setLayout( ); • and specify a type of layout. • For example: • To specify a BorderLayout: • setLayout (new BorderLayout());
LayoutManagers: Two General Flavors • One can conceptually divide layout managers into two types: • Those that attach constraints to their components. • Those that do not. • What does this mean?If a manager attaches constraints to a component, then information about a component’s location (e.g., compass points) is generated with the object.
NORTH WEST EAST CENTER SOUTH LayoutManagers: Constraints • BorderLayout specifies constraints corresponding to compass regions of a container:
LayoutManagers: Constraints • BorderLayout then appends constraint information on all components, e.g.: this.setLayout (new BorderLayout()); Button e = new Button (“East”); Button w = new Button (“West”); Button n = new Button (“North”); add(e, “East”); // deprecated add(“West”, w); // works; deprecated //add(n, BorderLayout.NORTH); // better
LayoutManagers: Another Example import java.awt.*; import java.applet.*; public class test extends Applet { String Compass[] = {"North", "South", "East", "West", "Center"}; public void init() { /* ALWAYS call super init! */ super.init(); /* set layout */ setLayout(new BorderLayout()); for (int i = (Compass.length) - 1; i >= 0; i- -){ Button temp = new Button (Compass[i]); add (temp, Compass[i]); } // for loop } // test
LayoutManager: Example Giving:
LayoutManager: No Constraints • The second type of LayoutManager does not specify constraints for the objects it holds. • Examples: • GridLayout() • FlowLayout() • Without constraints, you cannot accurately predict layout behavior across platforms
LayoutManager: No Constraints import java.awt.*; import java.applet.*; public class test extends Applet { public void init() { super.init(); String Labels[] = {"Short", "Short", "Long Label", "Really Long Label", "Really, really long"}; setLayout(new FlowLayout()); for (int i = (Labels.length - 1); i >= 0; i- -){ Button temp = new Button (Labels[i]); add (temp); } // for } //init } //class test
LayoutManager: No Constraints Giving:
LayoutManager: No Constraints And also:
LayoutManager: No Constraints • Note: • Since pixels, fonts and insets vary with each platform, layout without constraints will vary greatly. • Lesson: • Use layout managers without constraints only when you have one or few components
LayoutManager: No Constraints • Don’t think that layout managers without constraints are not useful! • One of the most useful constraint-free layout manager is “GridLayout”. public GridLayout(); public GridLayout(int rows, int cols); public GridLayout(int rows, int cols, int hgap, int vgap);
GridLayout GridLayout specifies a grid pattern via: setLayout (new GridLayout (rows, columns)); For example: setLayout (new GridLayout(2,3)); generates:
GridLayout • To add components (or containers) to a GridLayout, particular locations are not specified (unlike BorderLayout). • Instead, the components (or containers) are positioned by the sequence in which they are added, as indicated by numerals below. 1 2 3 4 5 6
GridLayout Optionally, two additional parameters may be used with GridLayout to specify the horizontal and vertical spacing (in pixels) between grid elements: • setLayout (new GridLayout (rows, columns, hspace, vspace)); • where hspace specifies horizontal size, • and vspace specifies vertical size, e.g., • setLayout (new GridLayout (2, 2, 7, 5));
GridLayout: Example import java.awt.*; import java.applet.*; public class test extends Applet { public void init() { super.init(); setLayout(new GridLayout(4,3,5,5)); int off[]={-2,2,0}; for (int i=9; i >= 1; i--) // this is “clever” but hard to grok // thus, is ill-advised: add (new Button (""+(i+off[i%3]))); add (new Button (".")); add (new Button ("0")); add (new Button ("+/-")); add (new MyPanel(null)); }// init }//test
GridLayout: Example Giving:
A Layout Example Imagine that we wish to create an Applet with the following interface layout . . . Label One TextArea1 is here {no label displayed} Label Two Label 3 Button One Label Four Button Two Button Three (dotted lines do not really appear; shown for reference)
A Layout Example • Because this is an Applet, the entire layout is defined in the init( ) method of the Applet. • Doing this implies three activities: • Sketching the layout on paper. • Declaring instance variables of the visible components. • Arranging the components as appropriate using a combination of nested containers.
A Layout Example Step One:Sketching the layout on paper As shown on earlier slide. Step Two:Declaring instance variables of the visible components: TextArea TextArea1 = new TextArea( ); Label Label1 = new Label ("Label One"); Label Label2 = new Label ("Label Two"); Label Label3 = new Label ("Label 3"); Label Label4 = new Label ("Label Four"); Button Button1 = new Button ("Button One"); Button Button2 = new Button ("Button Two"); Button Button3 = new Button ("Button 3");