Programming in Java More about GUI tsaiwncsie nctu

Programming in Java More about GUI 蔡文能 交通大學資訊 程學系 tsaiwn@csie. nctu. edu. tw http: //www. csie. nctu. edu. tw/~tsaiwn/java/ 交通大學資訊 程學系

Java More-GUI Agenda GUI (Graphical User Interface) AWT Component (package java. awt ) Graphics and Events Event Model Listener interfaces and Adaptors Events and Listeners for standard AWT events Layout Manager? Swing Library 交通大學資訊 程學系 蔡文能 5 -第 2頁

Java More-GUI Java UI functionality Presenting a Graphical User Interface (GUI) Playing sounds - Applications can play sounds as well as Applets since JDK 1. 2. Getting configuration information - Users can specify configuration information to a program using commandline arguments (applications only) and parameters (applets only). Saving user preferences using properties - For information that applications need to save even when they're not running, you can use properties. (not for Applets due to security problem. ) Getting/displaying text using the standard input/output/error streams - Standard input, output, and error are the old-fashioned way of presenting a user interface. - They're still useful for testing and debugging programs. 交通大學資訊 程學系 蔡文能 5 -第 3頁

Java 交通大學資訊 程學系 蔡文能 http: //java. sun. com/j 2 se/1. 4. 1/docs/api/ More-GUI 5 -第 4頁

Java More-GUI The AWT Components 交通大學資訊 程學系 蔡文能 5 -第 5頁

Java More-GUI Example using AWT Component - 以下為 Java 的AWT 提供的Graphical UI (GUI) components ( 圖型元件). 交通大學資訊 程學系 蔡文能 5 -第 6頁

Java More-GUI JFC/Swing The Java Foundation Classes (JFC) API extends the original Abstract Window Toolkit (AWT) by adding a comprehensive set of graphical user interface class libraries. JFC/Swing components include: Pluggable Look and Feel Accessibility API Java 2 DTM API (Java 2 only) Drag and Drop (Java 2 only) AWT Internationalization 交通大學資訊 程學系 蔡文能 5 -第 7頁

Java More-GUI Swing Library 交通大學資訊 程學系 蔡文能 5 -第 8頁

Java More-GUI Class javax. swing. JComponent java. lang. Object | +--java. awt. Component | +--java. awt. Container | +-javax. swing. JComponent 交通大學資訊 程學系 蔡文能 5 -第 9頁

Java JDK 1. 0 8 packages 212 classes JDK 1. 1 JDK 1. 2 JDK 1. 3 JDK 1. 4 23 packages 504 classes 59 packages 1520 classes 77 packages 1595 classes 103 packages 2175 classes New Events JFC/Swing Inner class Drag and Drop Object Serialization Jar Files JNDI Java Sound Timer Java 2 D JDBC Regular Exp Logging Assertions NIO 131 packages 2656 classes javax. activity, javax. management java. nio, javax. imageio, javax. net, javax. print, javax. security, org. w 3 c CORBA International Reflection More-GUI JDK 1. 5 javax. naming, javax. sound, javax. transaction RMI javax. accessibility, javax. swing, org. omg java. math, java. rmi, java. security, java. sql, java. text, java. beans 交通大學資訊 程學系 蔡文能 java. applet, java. awt, java. io, java. lang, java. net, java. util 5 -第 10頁

Java More-GUI What is MFC? (Microsoft Foundation Classes) C++ API for Microsoft Windows programming. Object-oriented framework over Win 32. Provides a set of classes allowing an easy application creation process. It encapsulates most part of the Windows API. 交通大學資訊 程學系 蔡文能 5 -第 11頁

Java More-GUI MFC vs. JFC/Swing Java Foundation Classes (Swing) are a set of Java class libraries provided as part of the Java Platform to support building graphics user interface (GUI) and graphics functionality for client applications that will run on popular platforms such as Microsoft Windows, Linux, and Mac OSX. JFC is needed when multiplatform compatibility is wanted. Under Windows, MFC works better than JFC 交通大學資訊 程學系 蔡文能 5 -第 12頁

Java More-GUI Other Ways of Getting User Input Sliders, Scrollbars, and Text Areas - The Scrollbar class is used for both slider and scrollbar functionality. - The Text. Area class simply provides an area to display or allow editing of several lines of text. - Text areas automatically include scrollbars. 交通大學資訊 程學系 蔡文能 5 -第 13頁

Java More-GUI The Basic Controls and events 基本控制元件: Buttons, Checkboxes, Choices, Lists, Menus, and Text Fields When a user activates one of these controls, it posts an event. - An object that contains the control can react to the event by implementing the action() method. (AWT 1. 0舊的 event處理 方式) Clicking a button. Pressing Return in a text field. - 新的處理方式: (AWT 1. 1 event model) 該元件要先 add. Action. Listener( 有處理能力的物件 ) 或向其他 Listener 註冊 (參看後面 slides) 交通大學資訊 程學系 蔡文能 5 -第 14頁


Java More-GUI MVC design pattern Overview Model-View-Controller architecture decouples 3 aspects of a user-interface - Model: the data being displayed - View: how the data is displayed - Controller: how the user interacts with the displayed data JFC/Swing variant of MVC: separable model architecture. Provides benefits of complete MV separation. Easier to use because it bundles view and controller together. 交通大學資訊 程學系 蔡文能 5 -第 16頁

Java More-GUI More AWT Components Creating Custom Components: Canvases - The Canvas class lets you write custom Components. With your Canvas subclass, you can draw custom graphics to the screen. Labels - A Label simply displays an unselectable line of text. Containers: Windows, Panels, and Scroll Panes - The AWT provides three types of containers, all are subclasses of the Container class (which is a Component subclass). The Window subclasses -- Dialog, File. Dialog, and Frame -- provide windows to contain components. A Panel groups components within an area of an existing window. A Scroll. Pane display a potentially large component in a limited amount of space, using scrollbars to control which part of the component is displayed. 交通大學資訊 程學系 蔡文能 5 -第 17頁

Java More-GUI Windows (1/2) Includes Dialog, File. Dialog, and Frames (框窗) create normal, full-fledged windows. Dialogs(對話窗) create windows which depends on Frames and can be modal. Example: The File. Dialog(檔案對話盒) window for files: 交通大學資訊 程學系 蔡文能 5 -第 18頁

Java More-GUI Windows (2/2) Dialog is a Window 交通大學資訊 程學系 蔡文能 Frame is a Window javax. swing. JFrame 5 -第 19頁

Java More-GUI Applet is a Panel 交通大學資訊 程學系 蔡文能 5 -第 20頁

Java More-GUI Scroll. Pane is NOT a Panel 交通大學資訊 程學系 蔡文能 5 -第 21頁

Java More-GUI Scroll. Pane Example - The JDK 1. 1 AWT introduced the Scroll. Pane class, which makes it easy for you to provide a scrolling area. - The following picture shows an applet in which both the vertical and horizontal scrollbars are needed. 交通大學資訊 程學系 蔡文能 5 -第 22頁

Java How to Use Scroll. Pane More-GUI Creates a scroll pane and puts a child component in it: Scroll. Pane sp 1 = new Scroll. Pane(); sp 1. add(another. Component); You can also specify the scrollbar display policy in the Scroll. Pane: Scroll. Pane sp 2 = new Scroll. Pane(Scroll. Pane. SCROLLBARS_ALWAYS); SCROLLBARS_AS_NEEDED Other Constants - The default value. Show each scrollbar only when it's needed. SCROLLBARS_ALWAYS - Always show scrollbars. SCROLLBARS_NEVER - Never show scrollbars. You might use this option if you don't want the user to directly control what part of the child component is shown. 交通大學資訊 程學系 蔡文能 5 -第 23頁

Java More-GUI Components to be put into a Scroll. Pane When implement a component to be put in a Scroll. Pane: Need to implement the child component's get. Preferred. Size method so that it returns the dimensions needed to fully display the component. Implement the child component so that it works well when its drawing area is larger than its preferred size. - The component might draw itself in the center of its drawing area, filling the extra space with a solid color. When the component is being scrolled, you might notice flashing, or flickering, in the display area. 交通大學資訊 程學系 蔡文能 5 -第 24頁

Java More-GUI Scrolling-related code from the previous applet: //The component that will be scrolled. class Scrollable. Canvas extends Canvas {. . . Dimension preferred. Size = new Dimension(600, 320); Dimension minimum. Size = new Dimension(10, 10); public Dimension get. Minimum. Size() { return minimum. Size; } public Dimension get. Preferred. Size() { return preferred. Size; } public void paint(Graphics g) { g. draw. Image(image, 0, 0, get. Background(), this); } } 交通大學資訊 程學系 蔡文能 5 -第 25頁

Java More-GUI Other AWT Classes The java. awt package supplies several classes to represent sizes and shapes. - Dimension : specifies the size of a rectangular area. - Insets : specify how much padding should exist between the outside edges of a container and the container's display area. - Shape : include Point, Rectangle, and Polygon. The Color class is useful for representing and manipulating colors. The Image class provides a way to represent image data. - Applets can get Image objects for GIF and JPEG images using the Applet get. Image() methods. … 交通大學資訊 程學系 蔡文能 5 -第 26頁

Java More-GUI Graphics and Events The Graphics and Event classes are crucial to the AWT drawing and event handling system. - A Graphics object (圖形元件)represents a drawing context -without a Graphics object, no program can draw to the screen. - An Event (事件)object represents a user action, such as a mouse click. 交通大學資訊 程學系 蔡文能 5 -第 27頁

Java More-GUI Example: 英制公制轉換 (1/3) http: //java. sun. com/docs/books/tutorial/uiswing/components /example-1 dot 4/Converter. java File lists: /* * A 1. 4 application that requires the following files: * Conversion. Panel. java * Converter. Range. Model. java * Follower. Range. Model. java * Unit. java */ 交通大學資訊 程學系 蔡文能 5 -第 28頁

Java More-GUI Example: 英制公制轉換 (2/3) 兩個主要 class: Converter Conversion. Panel 交通大學資訊 程學系 蔡文能 5 -第 29頁

Java More-GUI Example: 英制公制轉換 (3/3) The Component Hierarchy 交通大學資訊 程學系 蔡文能 5 -第 30頁

Java More-GUI Drawing How Drawing Requests Occur - Use the repaint( ) method to request to be scheduled for drawing. - Invoke the Component's update( ) method. - Call the Component's paint( ) method. (default) The Graphics Object - The only argument to paint() and update() is a Graphics object. - The Graphics class provides methods for the following: Drawing and filling rectangles, arcs, lines, ovals, polygons, text, and images. Getting or setting the current color, font, or clipping area. How to Draw - The simplest way for a Component to draw itself is to put drawing code in its paint() method. public void paint(Graphics g) { Dimension d = size(); g. draw. Rect(0, 0, d. width - 1, d. height - 1); } 交通大學資訊 程學系 蔡文能 5 -第 31頁


Java More-GUI Default Methods for Each Component 舊的方法 action() (Event. ACTION_EVENT) mouse. Enter() (Event. MOUSE_ENTER) mouse. Exit() (Event. MOUSE_EXIT) mouse. Move() (Event. MOUSE_MOVE) mouse. Down() (Event. MOUSE_DOWN) mouse. Drag() (Event. MOUSE_DRAG) mouse. Up() (Event. MOUSE_UP) key. Down() (Event. KEY_PRESS or Event. KEY_ACTION) key. Up() (Event. KEY_RELEASE or Event. KEY_ACTION_RELEASE) got. Focus() (Event. GOT_FOCUS) lost. Focus() (Event. LOST_FOCUS) handle. Event() (all event types) 交通大學資訊 程學系 蔡文能 5 -第 33頁

Java More-GUI Example 舊的方法 public boolean action(Event e, Object arg) { if (e. target instanceof Text. Field) { set. Slider. Value(get. Value()); controller. convert(this); return true; } if (e. target instanceof Choice) {. . . } return false; } public boolean handle. Event(Event e) { if (e. target instanceof Scrollbar) { text. Field. set. Text(String. value. Of(slider. get. Value())); controller. convert(this); } return super. handle. Event(e); } 交通大學資訊 程學系 蔡文能 5 -第 34頁


Java Another example (1/ 7) //event. Handler. java import java. awt. *; class event. Canvas extends Canvas { boolean has. Focus; More-GUI 需要寫一個簡單的 HTML 把這 Applet 叫起來 event. Canvas( int width, int height ) { set. Background( Color. yellow ); resize( width, height ); has. Focus = false; } public boolean mouse. Up( Event e, int x, int y ) { event. Handler. report. Event( "mouse. Up" ); return true; } 交通大學資訊 程學系 蔡文能 5 -第 36頁

Java Another example (2/7 ) More-GUI public boolean mouse. Down( Event e, int x, int y ) { event. Handler. report. Event( "mouse. Down" ); return true; } public boolean mouse. Drag( Event e, int x, int y ) { event. Handler. report. Event( "mouse. Drag" ); return true; } public boolean mouse. Enter( Event e, int x, int y ) { event. Handler. report. Event( "mouse. Enter" ); return true; } public boolean mouse. Exit( Event e, int x, int y ) { event. Handler. report. Event( "mouse. Exit" ); return true; } 交通大學資訊 程學系 蔡文能 5 -第 37頁

Java Another example (3/7 ) More-GUI public boolean key. Down( Event e, int key ) { String event. String = "key. Down: "; String key. Name, modifier. Name; modifier. Name = get. Modifier. Name( e ); if ( modifier. Name != null ) event. String += modifier. Name; key. Name = get. Key. Name( key ); if ( key. Name != null ) event. String += key. Name; else if (( key >= 32 ) && ( key <= 127 )) event. String += new Character( (char)key ). to. String(); else event. String += key; event. Handler. report. Event( event. String ); return true; } 交通大學資訊 程學系 蔡文能 5 -第 38頁

Java Another example (4/7 ) public String get. Modifier. Name( Event e ) { if ( e. control. Down() ) return( "Control-" ); if ( e. meta. Down() ) return( "Meta-" ); if ( e. shift. Down() ) return( "Shift-" ); More-GUI case Event. F 10: return "F 10"; case Event. F 11: return "F 11"; case Event. F 12: return "F 12"; case Event. HOME: return "HOME"; case Event. END: return "END"; case Event. LEFT: return "Left Arrow"; case Event. RIGHT: return "Right Arrow"; case Event. UP: return "Up Arrow"; case Event. DOWN: return "Down. Arrow"; case Event. PGUP: return "Page Up"; case Event. PGDN: return "Page Down"; } //switch return null; } public String get. Key. Name( int key ) { switch ( key ) { case Event. F 1: return "F 1"; case Event. F 2: return "F 2"; case Event. F 3: return "F 3"; case Event. F 4: return "F 4"; case Event. F 5: return "F 5"; case Event. F 6: return "F 6"; case Event. F 7: return "F 7"; case Event. F 8: return "F 8"; case Event. F 9: return "F 9"; return null; } 交通大學資訊 程學系 蔡文能 5 -第 39頁

Java Another example (5/7 ) More-GUI public boolean key. Up( Event e, int key ) { event. Handler. report. Event( "key. Up" ); return true; } public boolean got. Focus(Event e, Object what) { has. Focus = true; event. Handler. report. Event( "got. Focus" ); repaint(); return true; } public boolean lost. Focus(Event e, Object what) { has. Focus = false; event. Handler. report. Event( "lost. Focus" ); repaint(); return true; } 交通大學資訊 程學系 蔡文能 5 -第 40頁

Java Another example (6/7 ) More-GUI public void paint( Graphics g ) { Rectangle r; r = bounds(); g = get. Graphics(); if ( has. Focus ) g. set. Color( Color. red ); else g. set. Color( Color. yellow ); g. draw. Rect( 0, 0, r. width-1, r. height-1 ); g. draw. Rect( 1, 1, r. width-3, r. height-3 ); } } //class event. Canvas 交通大學資訊 程學系 蔡文能 5 -第 41頁

Java Another example (7/7) More-GUI public class event. Handler extends java. applet. Applet { event. Canvas e. Canvas; static Text. Area; public void init() { add( new Label( "Click and type in this Canvas: " ) ); e. Canvas = new event. Canvas( 200, 100 ); add( e. Canvas ); add( new Label( "Here’s a list of canvas events: " ) ); t. Area = new Text. Area( 15, 30 ); add( t. Area ); set. Visible(true); } public static void report. Event( String event. String ) { t. Area. append. Text( event. String + "r" ); } 需要寫一個簡單的 HTML 把這 Applet 叫起來 <HTML><body> <applet code=event. Handler. class Width=555 Height=333> </applet> } 交通大學資訊 程學系 蔡文能 5 -第 42頁

Java More-GUI AWT 1. 1. Event Model In the 1. 1 AWT event model, events are generated by event sources. - One or more listeners can register to be notified about events of a particular kind from a particular source. In every program that has an event handler, you'll see three bits of code: - Code that registers an instance of a listener. some. Component. add. Action. Listener(instance. Of. My. Class); - Declare the event handler implementing a listener interface. public class My. Class implements Action. Listener { - The implementation of the methods in the listener interface. public void action. Performed(Action. Event e) {. . . //code that reacts to the action. . . } 交通大學資訊 程學系 蔡文能 5 -第 43頁

Java More-GUI Example public class Multi. Listener. . . implements Action. Listener { //. . . //where initialization occurs: button 1. add. Action. Listener(this); button 2. add. Action. Listener(new Eavesdropper(bottom. Text. Area)); public void action. Performed(Action. Event e) { top. Text. Area. append(e. get. Action. Command() + "n"); } } class Eavesdropper implements Action. Listener {. . . public void action. Performed(Action. Event e) { my. Text. Area. append(e. get. Action. Command() + "n"); } } 交通大學資訊 程學系 蔡文能 5 -第 44頁

Java More-GUI Events The Java standard class library contains several classes that represent typical events Certain objects, such as an applet or a graphical button, generate (fire) an event when it occurs Other objects, called listeners, respond to events We can write listener objects to do whatever we want when an event occurs 交通大學資訊 程學系 蔡文能 5 -第 45頁

Java More-GUI Listener Interfaces We can create a listener object by writing a class that implements a particular Listener interface The Java standard class library contains several interfaces that correspond to particular event categories For example, the Mouse. Listener interface contains methods that correspond to mouse events After creating the listener, we add the listener to the component that might generate the event to set up a formal relationship between the generator and listener 交通大學資訊 程學系 蔡文能 5 -第 46頁

Java More-GUI Action. Listener 交通大學資訊 程學系 蔡文能 5 -第 47頁

Java More-GUI Problem of Using Listeners AWT Listeners usually have several methods. - If a class implements the listener, need to write all the methods. //An example with cluttered but valid code. public class My. Class implements Mouse. Listener { //. . . some. Object. add. Mouse. Listener(this); //. . . /* Empty method definitions are required. */ public void mouse. Pressed(Mouse. Event e) { } public void mouse. Released(Mouse. Event e) { } public void mouse. Entered(Mouse. Event e) { } public void mouse. Exited(Mouse. Event e) { } public void mouse. Clicked(Mouse. Event e) { //. . Event handler implementation goes here. . . } } 交通大學資訊 程學系 蔡文能 5 -第 48頁

Java More-GUI Solution: Using Adaptors Use Adaptor instead of Listener to simplify design. /* * An example of extending an adapter class instead of * directly implementing a listener interface. */ public class My. Class extends Mouse. Adapter { //. . . some. Object. add. Mouse. Listener(this); //. . . public void mouse. Clicked(Mouse. Event e) { //. . . Event handler implementation goes here. . . } } 交通大學資訊 程學系 蔡文能 5 -第 49頁


Java More-GUI Using Inner Classes Use inner classes with adaptors to simplify design. //An example of using an anonymous inner class. public class My. Class extends Applet { //. . . some. Object. add. Mouse. Listener( new Mouse. Adapter() { public void mouse. Clicked(Mouse. Event e) { //. . Event handler implementation //. . goes here. . . } // with Adapter, only methos we want } ); //. . . } } 交通大學資訊 程學系 蔡文能 5 -第 51頁

Java More-GUI Listener interfaces Action. Listener - action. Performed(Action. Event e) Adjustment. Listener - adjustment. Value. Changed(Adjustment. Event e) Ancestor. Listener - ancestor. Added(Ancestor. Event event) - ancestor. Moved(Ancestor. Event event) - ancestor. Removed(Ancestor. Event event) AWTEvent. Listener - event. Dispatched(AWTEvent event) Bean. Context. Membership. Listener - children. Added(Bean. Context. Membership. Event bcme) - children. Removed(Bean. Context. Membership. Event bcme) . . . 交通大學資訊 程學系 蔡文能 5 -第 52頁

Java More-GUI Standard AWT Events (1/2) Handling standard AWT events 交通大學資訊 程學系 蔡文能 5 -第 53頁

Java More-GUI Standard AWT Events (2/2) 交通大學資訊 程學系 蔡文能 5 -第 54頁

Java More-GUI Events Generated by AWT Components The AWT events can be divided into two groups: component -level (low-level) events and semantic events. Component-Level Events - Represent user or window-system actions such as a mouse click or a key press, … - Component. Event, Focus. Event, Input. Event, Key. Event, Mouse. Event, Container. Event, Window. Event Semantic Events - Represent higher-level functions or meanings of events such as double-clicking a text-line, … - Action. Event, Adjustment. Event, Item. Event, Text. Event Please see our text book: chap 7 , . . 交通大學資訊 程學系 蔡文能 5 -第 55頁

Java More-GUI Action Listener Writing an action listener - The Action. Listener interface contains a single method. void action. Performed(Action. Event) No corresponding adapter class since there is only one method. - An action event occurs, When the user clicks a button, When doubleclicks a list item, When chooses a menu item, When presses return in a text field, - An action event handling code example : public class Beeper. . . implements Action. Listener { //. . . //where initialization occurs: button. add. Action. Listener(this); //. . . public void action. Performed(Action. Event e) { //…Make a beep sound. . . } } 交通大學資訊 程學系 蔡文能 5 -第 56頁

Java More-GUI Action Events The Action. Event class - String get. Action. Command() Returns the string associated with this action. Default string is the text displayed in the component. - int get. Modifiers() Returns an integer representing the modifier keys the user was pressing when the action event occurred. For example, if the user shift-selects a menu item, then the following expression is nonzero: action. Event. get. Modifiers() & Action. Event. SHIFT_MASK 交通大學資訊 程學系 蔡文能 5 -第 57頁

Java More-GUI Action. Event methods 交通大學資訊 程學系 蔡文能 5 -第 58頁

Java More-GUI Adjustment Listener Adjustment events notify you of changes in the value of components that implement the adjustable interface. The only AWT class that implements adjustable is scrollbar. There are five kinds of adjustment events: - Track - Unit increment, unit decrement - Block increment, block decrement The Adjustment. Listener interface contains a single method. - No corresponding adapter class. void adjustment. Value. Changed(Adjustment. Event) 交通大學資訊 程學系 蔡文能 5 -第 59頁

Java More-GUI Adjustment Events The Adjustment. Event class defines the following handy methods: - Adjustable get. Adjustable() Returns the component that generated the event. - int get. Adjustment. Type() Returns the type of adjustment that occurred. The returned value is one of the following UNIT_INCREMENT, UNIT_DECREMENT, BLOCK_INCREMENT, BLOCK_DECREMENT, TRACK. - int get. Value() Returns the value of the component just after the adjustment occurred. 交通大學資訊 程學系 蔡文能 5 -第 60頁

Java More-GUI Component Listener One or more component events are generated by a component object. - After the component is hidden, made visible, moved, or resized. The component hidden and component visible events occur only as the result of calls to a component's set. Visible method. - For example, a window might be miniaturized into an icon (iconified), without a component hidden event being generated. Component Listener Methods - void component. Hidden(Component. Event) component. Moved(Component. Event) component. Resized(Component. Event) component. Shown(Component. Event) 交通大學資訊 程學系 蔡文能 5 -第 61頁

Java More-GUI Container Listener Methods - Void component. Added(Container. Event) - Void component. Removed(Container. Event) The Container. Event class defines two useful methods: - Component get. Child() - Container get. Container() 交通大學資訊 程學系 蔡文能 5 -第 62頁

Java More-GUI Focus Listener Writing a focus listener - Focus events are generated whenever a component gains or loses the keyboard focus -- the ability to receive keyboard events. - At most one component in the window system can have the keyboard focus. - You can request that a component get the focus by invoking the Component`s request. Focus method. - The Focus. Listener interface and its corresponding adapter class, Focus. Adapter, contain two methods: void focus. Gained(Focus. Event) void focus. Lost(Focus. Event) 交通大學資訊 程學系 蔡文能 5 -第 63頁

Java More-GUI Item Listener Writing an Item Listener - Item events are generated by components that implement the Item. Selectable interface. - The 1. 1 AWT components that generate item events are checkboxes, checkbox menu items, choices, and lists. - The Item. Listener interface has just one method, so it has no corresponding adapter class. void item. State. Changed(Item. Event) Called by the AWT just after a state change in the listenedto component. 交通大學資訊 程學系 蔡文能 5 -第 64頁

Java More-GUI Item Events The Item. Event class defines the following handy methods: - Object get. Item() Returns the component-specific object associated with the item whose state changed. Often this is a String containing the text on the selected item. For an item event generated by a List, this is an Integer that specifies the index of the selected item. - Item. Selectable get. Item. Selectable() Returns the component that generated the item event. - int get. State. Change() Returns the new state of the item. The Item. Event class defines two states: SELECTED and DESELECTED. 交通大學資訊 程學系 蔡文能 5 -第 65頁

Java More-GUI Key Listener Writing a key listener - Key events tell you when the user types at the keyboard. - Two basic kinds of key events: Typing of a Unicode character -- key typed event. Pressing or releasing of a key on the keyboard -- key pressed and key released event. - Three methods: void key. Typed(Key. Event) void key. Pressed(Key. Event) void key. Released(Key. Event) 交通大學資訊 程學系 蔡文能 5 -第 66頁

Java More-GUI Key Events The Key. Event class defines the following useful methods: - int get. Key. Char() void set. Key. Char(char) Get or set the Unicode character associated with this event. - int get. Key. Code() void set. Key. Code(int) Get or set the key code associated with this event. For example, VK_A specifies the key labeled A, and VK_ESCAPE specifies the ESCAPE key. - void set. Modifiers(int) Sets the state of the modifier keys for this event. 交通大學資訊 程學系 蔡文能 5 -第 67頁

Java More-GUI Mouse Listener Writing a mouse listener - Mouse events tell you when the user uses the mouse (or similar input device) to interact with a component. - Methods: Void void mouse. Clicked(Mouse. Event) mouse. Entered(Mouse. Event) mouse. Exited(Mouse. Event) mouse. Pressed(Mouse. Event) mouse. Released(Mouse. Event) Mouse Events: int get. Click. Count() int get. X() int get. Y() Point get. Point() boolean is. Popup. Trigger() 交通大學資訊 程學系 蔡文能 5 -第 68頁

Java More-GUI import java. applet. Applet; import java. awt. *; public class Dots extends Applet { private final int APPLET_WIDTH = 200; private final int APPLET_HEIGHT = 100; private final int RADIUS = 6; private Point click. Point = null; public void init() { Dots. Mouse. Listener listener = new Dots. Mouse. Listener(this); add. Mouse. Listener(listener); set. Background (Color. black); set. Size (APPLET_WIDTH, APPLET_HEIGHT); } 交通大學資訊 程學系 蔡文能 5 -第 69頁

Java More-GUI public void paint (Graphics page){ page. set. Color (Color. green); if (click. Point != null) page. fill. Oval (click. Point. x - RADIUS, click. Point. y - RADIUS, RADIUS * 2); } public void set. Point (Point point) { click. Point = point; } } 交通大學資訊 程學系 蔡文能 5 -第 70頁

Java Class implementing listener interface More-GUI import java. applet. Applet; import java. awt. *; import java. awt. event. *; class Dots. Mouse. Listener implements Mouse. Listener { private Dots applet; public Dots. Mouse. Listener (Dots applet) { this. applet = applet; } public void mouse. Clicked (Mouse. Event event) { Point click. Point = event. get. Point(); applet. set. Point (click. Point); applet. repaint(); } 交通大學資訊 程學系 蔡文能 5 -第 71頁

Java More-GUI //---------------------------// Provide empty definitions for unused event methods. //---------------------------public void mouse. Pressed (Mouse. Event event) {} public void mouse. Released (Mouse. Event event) {} public void mouse. Entered (Mouse. Event event) {} public void mouse. Exited (Mouse. Event event) {} }// end of Dots. Mouse. Listener 交通大學資訊 程學系 蔡文能 5 -第 72頁

Java More-GUI Input Events - The Mouse. Event class extends Input. Event, which extends Component. Event. - Input. Event provides the following useful methods: int get. When() boolean is. Alt. Down() boolean is. Control. Down() boolean is. Meta. Down() boolean is. Shift. Down() int get. Modifiers() 交通大學資訊 程學系 蔡文能 5 -第 73頁

Java More-GUI Mouse Motion Listener Writing a mouse motion listener - Mouse motion events tell you when the user uses the mouse (or a similar input device) to move the onscreen cursor. - Methods: void mouse. Dragged(Mouse. Event) void mouse. Moved(Mouse. Event) 交通大學資訊 程學系 蔡文能 5 -第 74頁

Java More-GUI Text Listener Writing a text listener - Text events are generated after the text in a text component has changed somehow. - The Text. Listener interface has just one method, so it has no corresponding adapter class. Void text. Value. Changed(Text. Event) - Called by the AWT just after the text in the listened-to component changes. 交通大學資訊 程學系 蔡文能 5 -第 75頁

Java More-GUI Window Listener Writing a window listener - Window events are generated by a window just after the window is opened, closed, iconified, deiconified, activated, or deactivated. - Methods: void void window. Opened(Window. Event) window. Closing(Window. Event) window. Closed(Window. Event) window. Iconified(Window. Event) window. Deiconified(Window. Event) window. Activated(Window. Event) window. Deactivated(Window. Event) 交通大學資訊 程學系 蔡文能 5 -第 76頁

Java More-GUI Take a Break Take a Break 交通大學資訊 程學系 蔡文能 5 -第 77頁

Java More-GUI What Is Layout Managers? An object that controls the size and position of components in a container. Panel : default -- Flow. Layout Window : default -- Grid. Layout 交通大學資訊 程學系 蔡文能 5 -第 78頁

Java More-GUI How to Use Border. Layout Example: set. Layout(new Border. Layout()); add("North", new Button("North")); add("South", new Button("South")); add("East", new Button("East")); add("West", new Button("West")); add("Center", new Button("Center")); 交通大學資訊 程學系 蔡文能 5 -第 79頁

Java More-GUI • If you use the one-argument version of add(), or if you specify an invalid first argument, your component might not be visible. • Border. Layout puts no gap between the components by default. • Specify gaps (in pixels) using the following constructor: – public Border. Layout(int horizontal. Gap, int vertical. Gap) 交通大學資訊 程學系 蔡文能 5 -第 80頁

Java More-GUI How to Use Flow. Layout set. Layout(new Flow. Layout()); add(new add(new Button("Button 1")); Button("2")); Button("Button 3")); Button("Long-Named Button 4")); Button("Button 5")); Three constructors: - public Flow. Layout() - public Flow. Layout(int alignment) alignment value : Flow. Layout. LEFT, Flow. Layout. CENTER, or Flow. Layout. RIGHT - public Flow. Layout(int alignment, int horizontal. Gap, int vertical. Gap) Default gap is 5 pixels. 交通大學資訊 程學系 蔡文能 5 -第 81頁

Java More-GUI How to Use Card. Layout public class Card. Window extends Frame implements Item. Listener { Panel cards; final static String BUTTONPANEL = "Panel with Buttons"; final static String TEXTPANEL = "Panel with Text. Field"; public Card. Window() { set. Layout(new Border. Layout()); //Put the Choice in a Panel to get a nicer look. Panel cp = new Panel(); Choice c = new Choice(); c. add. Item(BUTTONPANEL); c. add. Item(TEXTPANEL); c. add. Item. Listener(this); cp. add(c); add("North", cp); 交通大學資訊 程學系 蔡文能 5 -第 82頁

Java cards = new Panel(); cards. set. Layout(new Card. Layout()); Panel p 1 = p 1. add(new More-GUI new Panel(); Button("Button 1")); Button("Button 2")); Button("Button 3")); Panel p 2 = new Panel(); p 2. add(new Text. Field("Text. Field", 20)); cards. add(BUTTONPANEL, p 1); cards. add(TEXTPANEL, p 2); add("Center", cards); . . . } public void item. State. Changed(Item. Event evt) { Card. Layout cl = (Card. Layout)(cards. get. Layout()); cl. show(cards, (String)evt. get. Item()); } 交通大學資訊 程學系 蔡文能 5 -第 83頁

Java More-GUI How to Use Grid. Layout //Construct a Grid. Layout with 2 columns and // an unspecified number of rows. set. Layout(new Grid. Layout(0, 2)); add(new add(new Button("Button 1")); Button("2")); Button("Button 3")); Button("Long-Named Button 4")); Button("Button 5")); Two constructors: - public Grid. Layout(int rows, int columns) At least one of the rows and columns arguments must be non-zero. - public Grid. Layout(int rows, int columns, int horizontal. Gap, int vertical. Gap) 交通大學資訊 程學系 蔡文能 5 -第 84頁

Java More-GUI Grid. Bag Layout controls using a rectangular grid - controls can span multiple rows or columns - use constraints (0, 0) (1, 0) (2, 0) Spans 3 columns Spans 2 columns 交通大學資訊 程學系 蔡文能 5 -第 85頁

Java More-GUI Grid. Bag Layout Constraints gridx, gridy = upper left corner of control (0, 0) (1, 0) (2, 0) Spans 3 columns Spans 2 columns gridwidth = columns to span gridheight = rows to span weightx = how much of extra space goes to this column weighty = how much of extra space goes to this row fill = (none, H, V) anchor = {NW, N, NE, E…} 交通大學資訊 程學系 蔡文能 5 -第 86頁

Java More-GUI How to Use Grid. Bag. Layout Using Grid. Bag. Layout gridbag = new Grid. Bag. Layout(); Grid. Bag. Constraints c = new Grid. Bag. Constraints(); set. Layout(gridbag); //For each component to be added to this container: //. . . Create the component. . . //. . . Set instance variables in the Grid. Bag. Constraints // instance. . . gridbag. set. Constraints(the. Component, c); add(the. Component); 交通大學資訊 程學系 蔡文能 5 -第 87頁

Java More-GUI Grid. Bag. Contraints again (1/2) - gridx, gridy • Specify the row and column at the upper left of the component. • Grid. Bag. Constraints. RELATIVE (default value) - gridwidth, gridheight Specify the number of columns (for gridwidth) or rows (for gridheight) of the component. The default value is 1. Grid. Bag. Constraints. REMAINDER Grid. Bag. Constraints. RELATIVE - fill Grid. Bag. Constraints. NONE (the default) Grid. Bag. Constraints. HORIZONTAL Grid. Bag. Constraints. VERTICAL Grid. Bag. Constraints. BOTH - ipadx, ipady Specifies the internal padding. The default value is zero. 交通大學資訊 程學系 蔡文能 5 -第 88頁

Java More-GUI Grid. Bag. Contraints again (2/2) - insets Specifies the external padding of the component. Default is no external padding. - anchor Valid values are Grid. Bag. Constraints. CENTER (the default), Grid. Bag. Constraints. NORTHEAST, Grid. Bag. Constraints. SOUTHEAST, Grid. Bag. Constraints. SOUTHWEST, Grid. Bag. Constraints. WEST, and Grid. Bag. Constraints. NORTHWEST. - weightx, weighty Used to determine how to distribute space among columns (weightx) and among rows (weighty). 交通大學資訊 程學系 蔡文能 5 -第 89頁

Java More-GUI Grid. Bag. Layout Example (1/2) protected void makebutton(String name, Grid. Bag. Layout gridbag, Grid. Bag. Constraints c) { Button button = new Button(name); gridbag. set. Constraints(button, c); add(button); } public Grid. Bag. Window() { Grid. Bag. Layout gridbag = new Grid. Bag. Layout(); Grid. Bag. Constraints c = new Grid. Bag. Constraints(); set. Layout(gridbag); c. fill = Grid. Bag. Constraints. BOTH; c. weightx = 1. 0; makebutton("Button 1", gridbag, c); makebutton("Button 2", gridbag, c); makebutton("Button 3", gridbag, c); c. gridwidth = Grid. Bag. Constraints. REMAINDER; //end of row makebutton("Button 4", gridbag, c); 交通大學資訊 程學系 蔡文能 5 -第 90頁

Java More-GUI Grid. Bag. Layout Example (2/2) c. weightx = 0. 0; //reset to the default makebutton("Button 5", gridbag, c); //another row c. gridwidth = Grid. Bag. Constraints. RELATIVE; //next to last in row makebutton("Button 6", gridbag, c); c. gridwidth = Grid. Bag. Constraints. REMAINDER; //end of row makebutton("Button 7", gridbag, c); c. gridwidth = 1; //reset to the default c. gridheight = 2; c. weighty = 1. 0; makebutton("Button 8", gridbag, c); c. weighty = 0. 0; //reset to the default c. gridwidth = Grid. Bag. Constraints. REMAINDER; //end of row c. gridheight = 1; //reset to the default makebutton("Button 9", gridbag, c); makebutton("Button 10", gridbag, c); } 交通大學資訊 程學系 蔡文能 5 -第 91頁

Java More-GUI fill = Grid. Bag. Constraints. NONE weight = 0 交通大學資訊 程學系 蔡文能 5 -第 92頁

Java More-GUI General Rules for Using Layout Managers How to Choose a Layout Manager - Display a component in as much space as it can get Border. Layout - Put the space-hungry component in the center. Grid. Bag. Layout - Set the constraints for the component so that fill=Grid. Bag. Constraints. BOTH. Grid. Layout - All components will be the same size. - Display a few components in a compact row at their natural size Using a Panel and using the Panel's default Flow. Layout manager. - Display a few same-sized components in rows and/or columns Grid. Layout How to Create a Layout Manager and Associate It with a Container a. Container. set. Layout(new Card. Layout()); 交通大學資訊 程學系 蔡文能 5 -第 93頁

Java Doing Without a Layout Manager More-GUI public class None. Window extends Frame { private boolean laid. Out = false; private Button b 1, b 2, b 3; public None. Window() { super(); set. Layout(null); b 1 = new Button("one"); add(b 1); b 2 = new Button("two"); add(b 2); b 3 = new Button("three"); add(b 3); } public void paint(Graphics g) { if (!laid. Out) { Insets insets = insets(); b 1. reshape(50 + insets. left, 5 + insets. top, 50, 20); b 2. reshape(70 + insets. left, 35 + insets. top, 50, 20); b 3. reshape(130 + insets. left, 15 + insets. top, 50, 30); laid. Out = true; } }. . . } 交通大學資訊 程學系 蔡文能 5 -第 94頁

Java More-GUI Overview of AWT Graphics Support The Graphics Object - paint(Graphics g), update(Graphics g) - Two basic kinds of drawing Primitive graphics (such as lines, rectangles, and text) Images - Provides a drawing context The current drawing area The current drawing color The Coordinate System The Four Forms of the repaint() Method - public void repaint() public void repaint(long time) public void repaint(int x, int y, int width, int height) public void repaint(long time, int x, int y, int width, int height) 交通大學資訊 程學系 蔡文能 5 -第 95頁

Java More-GUI Drawing Shapes The Graphics class drawing the following kinds of shapes: - Lines (draw. Line()) Rectangles, (draw. Rect(), fill. Rect(), and clear. Rect()) Raised or lowered rectangles (draw 3 DRect() and fill 3 DRect()) Round-edged rectangles (draw. Round. Rect() and fill. Round. Rect()) Ovals (draw. Oval() and fill. Oval()) Arcs (draw. Arc() and fill. Arc()) Polygons (draw. Polygon() and fill. Polygon()) 交通大學資訊 程學系 蔡文能 5 -第 96頁

Java More-GUI Example: Simple Rectangle Drawing //In Framed. Area (a Panel subclass): public Insets get. Insets() { return new Insets(4, 4, 5, 5); } public void paint(Graphics g) { Dimension d = get. Size(); Color bg = get. Background(); g. set. Color(bg); g. draw 3 DRect(0, 0, d. width - 1, d. height - 1, true); g. draw 3 DRect(3, 3, d. width - 7, d. height - 7, false); } 交通大學資訊 程學系 蔡文能 5 -第 97頁

Java More-GUI Example (cont. ) class Coordinate. Area extends Canvas { Point point = null; Coordinates. Demo controller; public Coordinate. Area(Coordinates. Demo controller) { super(); this. controller = controller; add. Mouse. Listener(new Mouse. Adapter() { public void mouse. Pressed(Mouse. Event e) { int x=e. get. X(); int y=e. get. Y(); if(point==null) { point=new Point(x, y); } else { point. x=x; point. y=y; } repaint(); } } public void paint(Graphics g) { if(point != null) { controller. update. Label(point); g. fill. Rect(point. x - 1, point. y - 1, 2, 2); } } 交通大學資訊 程學系 蔡文能 5 -第 98頁

Java More-GUI Example: Selected Area Using a Rectangle to Indicate a Selected Area class Selection. Area extends Canvas { Rectangle current. Rect = null; Rectangle. Demo controller; public Selection. Area(Rectangle. Demo controller) { super(); this. controller = controller; My. Listener my. Listener = new My. Listener(); add. Mouse. Listener(my. Listener); add. Mouse. Motion. Listener(my. Listener); } 交通大學資訊 程學系 蔡文能 5 -第 99頁

Java More-GUI public void paint(Graphics g) { //update has already cleared the previous rectangle, //so we don't need to here. //If current. Rect exists, paint a rectangle on top. if (current. Rect != null) { Dimension d = get. Size(); Rectangle box = get. Drawable. Rect(current. Rect, d); controller. update. Label(box); //Draw the box outline. g. draw. Rect(box. x, box. y, box. width - 1, box. height - 1); } } Rectangle get. Drawable. Rect(Rectangle original. Rect, Dimension drawing. Area) {. . . //Make sure rectangle width and height are positive. . //The rectangle shouldn't extend past the drawing area. . } 交通大學資訊 程學系 蔡文能 5 -第 100頁

Java More-GUI class My. Listener extends Mouse. Adapter implements Mouse. Motion. Listener { public void mouse. Pressed(Mouse. Event e) { int x = e. get. X(); int y = e. get. Y(); current. Rect = new Rectangle(x, y, 0, 0); repaint(); } public void mouse. Released(Mouse. Event e) {update. Size(e); } public void mouse. Dragged(Mouse. Event e) {update. Size(e); } public void mouse. Moved(Mouse. Event e) {} void update. Size(Mouse. Event e) { int x = e. get. X(); int y = e. get. Y(); current. Rect. set. Size(x-current. Rect. x, y-current. Rect. y); repaint(); } } 交通大學資訊 程學系 蔡文能 5 -第 101頁

Java Working With Text More-GUI Drawing Text - Using text-oriented Component Label, Text. Field, or Text. Area Example: label. set. Text("Hello World!"); - If a Component isn't appropriate - Using the Graphics draw. Bytes(), draw. Chars(), or draw. String() methods. Example: g. draw. String("Hello World!", x, y); x and y specify the position of the lower left corner of the text. The y coordinate specifies the baseline of the text. d 交通大學資訊 程學系 蔡文能 5 -第 102頁

Java More-GUI Font and Font. Metrics Getting Information about a Font: Font. Metrics pick. Font(Graphics g, String long. String, int x. Space) { boolean font. Fits = false; Font font = g. get. Font(); Font. Metrics font. Metrics = g. get. Font. Metrics(); int size = font. get. Size(); String name = font. get. Name(); int style = font. get. Style(); while (!font. Fits) { if ( font. Metrics. get. Height()<=max. Char. Height && font. Metrics. string. Width(long. String)<=x. Space ) { font. Fits = true; } else { if (size <= min. Font. Size) { font. Fits = true; } else { g. set. Font(font = new Font(name, style, --size)); font. Metrics = g. get. Font. Metrics(); } } } return font. Metrics; } 交通大學資訊 程學系 蔡文能 5 -第 103頁

Java More-GUI Font. Metrics – – – get. Ascent(), get. Max. Ascent() get. Descent(), get. Max. Descent() get. Height() get. Width() get. Max. Advance() char. Width(int), char. Width(char) chars. Width(char[], int) string. Width(String) get. Widths() 交通大學資訊 程學系 蔡文能 5 -第 104頁

Java More-GUI Using Images Loading Images - Using the get. Image() Methods It is easy to get an Image object for it if - Image data is in GIF or JPEG format. my. Image = get. Image(URL); // in an Applet subclass only my. Image = Toolkit. get. Default. Toolkit(). get. Image(filename. Or. URL); Applets - The Applet class supplies : public Image get. Image(URL url) public Image get. Image(URL url, String name) - Example: Image image 1 = get. Image(get. Code. Base(), "image. File. gif"); Image image 2 = get. Image(get. Document. Base(), "an. Image. File. jpeg "); Image image 3 = get. Image(new URL("http: //java. sun. com/graphics/people. gif ")); Toolkit: Toolkit toolkit = Toolkit. get. Default. Toolkit (); Image image 1 = toolkit. get. Image("image. File. gif "); Image image 2 = toolkit. get. Image(new URL("http: //java. sun. com/graphics/people. gif ")); 交通大學資訊 程學系 蔡文能 5 -第 105頁

Java More-GUI Memory. Image. Source Creating Images with Memory. Image. Source The following code example calculates a 100 x 100 image representing a fade from black to blue along the X axis and a fade from black to red along the Y axis. int w = 100; int h = 100; int[] pix = new int[w * h]; int index = 0; for (int y = 0; y < h; y++) { int red = (y * 255) / (h - 1); for (int x = 0; x < w; x++) { int blue = (x * 255) / (w - 1); pix[index++] = (255 << 24) | (red << 16) | blue; } } Image img = create. Image( new Memory. Image. Source(w, h, pix, 0, w)); 交通大學資訊 程學系 蔡文能 5 -第 106頁

Java More-GUI Image Loading Requesting and Tracking Image Loading: Media. Tracker and Image. Observer - The Media. Tracker class is sufficient for many programs. See the example improving. Image. Anim The Image. Observer interface lets you keep even closer track of image loading than Media. Tracker allows. To use the Image. Observer interface, you implement the Image. Observer image. Update() method. 交通大學資訊 程學系 蔡文能 5 -第 107頁

Java More-GUI image. Update in Image. Observer Here is an example of image. Update() method: public boolean image. Update(Image theimg, int infoflags, int x, int y, int w, int h) { if ((infoflags & (ERROR)) != 0) { errored = true; } if ((infoflags & (WIDTH | HEIGHT)) != 0) { position. Images(); } boolean done = ( (infoflags & (ERROR | FRAMEBITS | ALLBITS)) != 0 ); // Repaint immediately if we are done, // otherwise batch up repaint requests // every 100 milliseconds repaint(done ? 0 : 100); //If done, no further updates required. return !done; } 交通大學資訊 程學系 蔡文能 5 -第 108頁

Java More-GUI Displaying Images - Below is an applet that loads a single image and displays it twice, using both code examples below : g. draw. Image(image, 0, 0, this); g. draw. Image(my. Image, 90, 0, 300, 62, this); 交通大學資訊 程學系 蔡文能 5 -第 109頁

Java More-GUI Manipulating Images The figure shows how image data is created: An image filter is an Image. Filterobject - Sitting between a producer and a consumer. - Modifying the image data before the consumer gets it. Image source. Image; . . . //Initialize source. Image, using the Toolkit or Applet get. Image() method. Image. Filter filter = new Some. Image. Filter(); Image. Producer producer = new Filtered. Image. Source(source. Image. get. Source(), filter); Image result. Image = create. Image(producer); 交通大學資訊 程學系 蔡文能 5 -第 110頁

Java More-GUI Example: Rotate an Image (1/2) public class Image. Rotator extends Applet {. . . Rotator. Canvas rotator; double radians. Per. Degree = Math. PI / 180; } public void init() { //Load the image. Image image = get. Image(get. Code. Base(), ". . /images/rocketship. gif"); . . . //Create the component that uses the image filter: rotator = new Rotator. Canvas(image); . . . add(rotator); . . . } public boolean action(Event evt, Object arg) { int degrees; . . . //Get the number of degrees to rotate the image //Convert to radians. rotator. rotate. Image((double)degrees * radians. Per. Degree); return true; } 交通大學資訊 程學系 蔡文能 5 -第 111頁

Java More-GUI Example: Rotate an Image (2/2) class Rotator. Canvas extends Canvas { Image source. Image; Image result. Image; public Rotator. Canvas(Image image) { source. Image = image; result. Image = source. Image; } public void rotate. Image(double angle) { Image. Filter filter = new Rotate. Filter(angle); Image. Producer producer = new Filtered. Image. Source( source. Image. get. Source(), filter); result. Image = create. Image(producer); repaint(); } public void paint(Graphics g) { Dimension d = size(); int x = (d. width-result. Image. get. Width(this))/2; int y = (d. height-result. Image. get. Height(this))/2; g. draw. Image(result. Image, x, y, this); } } 交通大學資訊 程學系 蔡文能 5 -第 112頁
![Java More-GUI Another Suggestion int [] thispixels = new thispixels[width*height]; Pixel. Grabber pg = Java More-GUI Another Suggestion int [] thispixels = new thispixels[width*height]; Pixel. Grabber pg =](http://slidetodoc.com/presentation_image_h2/0cb642e0437f77dc2676e847ca583563/image-113.jpg)
Java More-GUI Another Suggestion int [] thispixels = new thispixels[width*height]; Pixel. Grabber pg = new Pixel. Grabber(an. Image, 0, 0, width, height, thispixels, 0, width); try { pg. grab. Pixels(); } catch (Interrupted. Exception e) { System. err. println("waiting for pixels!"); return null; } Image destination = Elife. create. Image(new Memory. Image. Source(width, height, thispixels, 0, width)); 交通大學資訊 程學系 蔡文能 5 -第 113頁

Java More-GUI Performing Animation Creating the Animation Loop - Every program that performs animation by drawing at regular intervals needs an animation loop. - This loop should be in its own thread and never be in the paint() or update() method. - Initializing Instance Variables frame. Number represents the current frame. It's initialized to -1, even though the first frame number is 0. delay is the number of milliseconds between frames. animator. Thread is a Thread object, representing the thread in which the animation loop runs. frozen is a boolean value that's initialized to false. Set it to true to indicate that the user has requested that the animation stop. 交通大學資訊 程學系 蔡文能 5 -第 114頁

Java More-GUI Example (1/2) public class Animator. Class extends AComponent. Class implements Runnable { //In initialization code: //From user-specified frames-per-second value, //determine how long to delay between frames. //In a method that does nothing but start the animation: //Create and start the animating thread. //In a method that does nothing but stop the animation: //Stop the animating thread. public boolean mouse. Down(Event e, int x, int y) { if ( /* animation is currently frozen */ ) { //Call the method that starts the animation. } else { } } //Call the method that stops the animation. 交通大學資訊 程學系 蔡文能 5 -第 115頁

Java More-GUI Example (2/2) public void run() { // Lower this thread's priority so it can't // interfere with other processing going on. // Remember the starting time. // Here's the animation loop: while ( /* animation thread is still running */ ) { // Advance the animation frame. // Display it. // Delay depending on how far we are behind. } } } public void paint(Graphics g) { // Draw the current frame of animation. } 交通大學資訊 程學系 蔡文能 5 -第 116頁

Java More-GUI Animation Loop - Advances the frame number. - Calls the repaint() method to request that the current frame of animation be drawn. - Sleeps for up to delay milliseconds. while (/* animation thread is still running */) { //Advance the animation frame. Number++; //Display it. repaint(); } . . . //Delay depending on how far we are behind. - Ensuring a Constant Frame Rate long start. Time = System. current. Time. Millis (); while (/* animation thread is still running */) {. . . //Advance the animation frame and display it. try { start. Time += delay; Thread. sleep(Math. max(0, start. Time-System. current. Time. Millis ())); } catch (Interrupted. Exception e) { break; } } 交通大學資訊 程學系 蔡文能 5 -第 117頁

Java More-GUI - Behaving Politely Allowing the user to stop (and restart) the animation, while the applet or application is still visible. - Implemented by overriding the mouse. Down() method. Suspending the animation whenever the applet or application is known not to be visible. - This is achieved by implementing the Applet stop() and start() methods 交通大學資訊 程學系 蔡文能 5 -第 118頁

Java More-GUI Animating Graphics An example applet that creates a moving a checkerboard effect by painting alternate squares which are drawn by the Graphics fill. Rect() method. // Draw the rectangle if necessary. if (fill. Square) { g. fill. Rect(x, y, w, h); fill. Square = false; } else { fill. Square = true; } 交通大學資訊 程學系 蔡文能 5 -第 119頁

Java More-GUI Eliminating Flashing Problem The flashing effect is the result of two facts: - By default, the background of the animation is cleared before the paint() method is called. - The computation in the paint() method is complex enough that it takes longer to compute and draw each frame than the video screen's refresh rate. Solution I 請參考 http: //scv. bu. edu/Doc/Java/tutorial/ui/drawing/example/Update. java 交通大學資訊 程學系 蔡文能 5 -第 120頁

Java More-GUI Solution I Eliminating Flashing: Overriding the update() Method public void paint(Graphics g) { update(g); } public void update(Graphics g) { Color bg = get. Background(); Color fg = get. Foreground(); . . . //same as old paint() method if (fill. Square) { g. fill. Rect(x, y, w, h); fill. Square = false; } else { g. set. Color(bg); g. fill. Rect(x, y, w, h); g. set. Color(fg); fill. Square = true; }. . . //same as old paint() method } 交通大學資訊 程學系 蔡文能 5 -第 121頁

Java More-GUI Solution II Eliminating Flashing: Double Buffering - Forcing the entire frame to be drawn at once. First creating an undisplayed buffer -- backbuffer or offscreen buffer. Drawing to the buffer Displaying the resulting image onscreen. - To create an offscreen buffer with the AWT: Creating an image of the proper size. Getting a graphics context to manipulate the image. 請參考: http: //scv. bu. edu/Doc/Java/tutorial/ui/drawing/double. Buffer. html 交通大學資訊 程學系 蔡文能 5 -第 122頁

Java More-GUI Example //Where instance variables are declared: Dimension off. Dimension; Image off. Image; Graphics off. Graphics; . . . public void update(Graphics g) {. . . //In the update() method, where d holds the size of //the onscreen drawing area: if( (off. Graphics == null) || (d. width != off. Dimension. width) || (d. height != off. Dimension. height) ) { off. Dimension = d; off. Image = create. Image(d. width, d. height); off. Graphics = off. Image. get. Graphics(); } //Erase the previous image. off. Graphics. set. Color(get. Background()); off. Graphics. fill. Rect(0, 0, d. width, d. height); off. Graphics. set. Color(Color. black); 交通大學資訊 程學系 蔡文能 5 -第 123頁

Java More-GUI Animation: Displaying a Sequence of Images Below are the ten images this applet uses. 交通大學資訊 程學系 蔡文能 5 -第 124頁
![Java More-GUI Sample Code. . . //Where instance variables are declared: Image duke[10]; . Java More-GUI Sample Code. . . //Where instance variables are declared: Image duke[10]; .](http://slidetodoc.com/presentation_image_h2/0cb642e0437f77dc2676e847ca583563/image-125.jpg)
Java More-GUI Sample Code. . . //Where instance variables are declared: Image duke[10]; . . . //In the init() method: for (int i = 1; i <= 10; i++) { images[i-1] = get. Image(get. Code. Base(), ". . /images/duke/T"+i+". gif"); }. . . //In the update() method, //instead of calling draw. Frame(): off. Graphics. draw. Image(images[frame. Number % 10], 0, 0, this); Problem: delay for each loading in draw. Image(). Solution: Use Media. Tracker to improve the performance 交通大學資訊 程學系 蔡文能 5 -第 125頁

Java More-GUI Media. Tracker Using Media. Tracker to Download Images and Delay Image Display - To request a group of images be preloaded asynchronously, you can use check. ID(true) and check. All(true). - To load data synchronously (waiting for the data to arrive), use the wait. For. ID() and wait. For. All() methods. 請參考 Java tutorial 裡的範例 improving. Image. Anim 交通大學資訊 程學系 蔡文能 5 -第 126頁

Java More-GUI Speeding Up Image Loading images using URLs (as applets usually do) usually takes a long time. - Most of the time is taken up by initiating HTTP connections. The key to avoiding this performance hit is to combine the images in a single file. - One simple way to combine images in a single file is to create an image strip. 交通大學資訊 程學系 蔡文能 5 -第 127頁

Java More-GUI Image Clipping To draw an image from the strip - First set the clipping area to the size of one image. - Then you draw the image strip, shifted to the left (if necessary) so that only the image you want appears within the clipping area. //image. Strip is the Image object representing the image strip. //image. Width is the size of an individual image in the strip. //image. Number is the number (from 0 to num. Images) // of the image to draw. int strip. Width = image. Strip. get. Width(this); int strip. Height = image. Strip. get. Height(this); int image. Width = strip. Width / num. Images; g. clip. Rect(0, 0, image. Width, strip. Height); g. draw. Image(image. Strip, -image. Number*image. Width, 0, this); 交通大學資訊 程學系 蔡文能 5 -第 128頁

Java Swing Library again More-GUI http: //java. sun. com/docs/books/tutorial/uiswing/TOC. html#start 交通大學資訊 程學系 蔡文能 5 -第 129頁

Java http: //java. sun. com/docs/books/tutorial/ 交通大學資訊 程學系 蔡文能 More-GUI 5 -第 130頁

Java Swing Library More-GUI http: //java. sun. com/docs/books/tutorial/uiswing/TOC. html#start 交通大學資訊 程學系 蔡文能 5 -第 131頁


Java More-GUI JFC/Swing GUI Components (1/6) Top-Level Containers Applet 交通大學資訊 程學系 蔡文能 Dialog Frame 5 -第 133頁

Java More-GUI JFC/Swing GUI Components (2/6) General-Purpose Containers Tabbed Pane Split Pane Scroll Pane Toolbar 交通大學資訊 程學系 蔡文能 Panel 5 -第 134頁

Java More-GUI JFC/Swing GUI Components (3/6) Special-Purpose Containers Internal Frame Layered Pane Root Pane 交通大學資訊 程學系 蔡文能 5 -第 135頁

Java More-GUI JFC/Swing GUI Components (4/6) Basic Controls Buttons Menu 交通大學資訊 程學系 蔡文能 Combobox Slider List Text Fields 5 -第 136頁

Java More-GUI JFC/Swing GUI Components (5/6) Uneditable Information Displays Progress Bar Label Tooltip 交通大學資訊 程學系 蔡文能 5 -第 137頁

Java More-GUI JFC/Swing GUI Components (6/6) Editable Displays of Formatted Information Table Color Chooser 交通大學資訊 程學系 蔡文能 Text Tree File Chooser 5 -第 138頁

Java More-GUI Introduction to Java Programming 謝謝捧場 http: //www. csie. nctu. edu. tw/~tsaiwn/java/ 蔡文能 交通大學資訊 程學系 蔡文能 5 -第 139頁

- Slides: 140