1 / 140

Programming in Java

Programming in Java. More about GUI 蔡文能 交通大學資訊工程學系 tsaiwn@csie.nctu.edu.tw. http://www.csie.nctu.edu.tw/~tsaiwn /java/. Agenda. GUI (Graphical User Interface) AWT Component (package java.awt ) Graphics and Events Event Model Listener interfaces and Adaptors

wylie
Download Presentation

Programming in Java

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

  2. 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

  3. Java UI functionality • Presenting a Graphical User Interface (GUI) • Playing sounds • Applications can play sounds as well as Applets since JDK1.2. • Getting configuration information • Users can specify configuration information to a program using command-line 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.

  4. http://java.sun.com/j2se/1.4.1/docs/api/

  5. The AWT Components

  6. Example using AWT Component • 以下為 Java 的AWT 提供的Graphical UI (GUI) components (圖型元件).

  7. 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 2DTM API (Java 2 only) • Drag and Drop (Java 2 only) • AWT • Internationalization

  8. Swing Library

  9. Class javax.swing.JComponent java.lang.Object | +--java.awt.Component | +--java.awt.Container | +--javax.swing.JComponent

  10. JDK 1.3 77 packages 1595 classes JDK 1.0 8 packages 212 classes JDK 1.2 59 packages 1520 classes JDK 1.4 103 packages 2175 classes JDK 1.5 131 packages 2656 classes javax.activity, javax.management New Events Inner class Object Serialization Jar Files International Reflection JDBC RMI JFC/Swing Drag and Drop Java2D CORBA Regular Exp Logging Assertions NIO JNDI Java Sound Timer java.nio, javax.imageio, javax.net, javax.print, javax.security, org.w3c javax.naming, javax.sound, javax.transaction 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 JDK 1.1 23 packages 504 classes

  11. What is MFC?(Microsoft Foundation Classes) • C++ API for Microsoft Windows programming. • Object-oriented framework over Win32. • Provides a set of classes allowing an easy application creation process. • It encapsulates most part of the Windows API.

  12. 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

  13. Other Ways of Getting User Input • Sliders, Scrollbars, and Text Areas • The Scrollbar class is used for both slider and scrollbar functionality. • The TextArea class simply provides an area to display or allow editing of several lines of text. • Text areas automatically include scrollbars.

  14. 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. (AWT1.0舊的 event處理方式) • Clicking a button. • Pressing Return in a text field. • 新的處理方式: (AWT1.1 event model) • 該元件要先 addActionListener( 有處理能力的物件 ) 或向其他Listener 註冊 (參看後面 slides)

  15. 動作 事件 監聽者物件 事件來源 Event driven (事件驅動) • Event (事件) • 使用者執行視窗程式時對視窗元件的動作,例如按一下按鈕或鍵盤。 • Event Handler (事件處理程式) • 程式執行中若發生事件,可以由指定的事件處理程式進行處理。 • Delegation Event Model (委託式的事件處理模型) • Java AWT1.1的事件處理模型, 包括: • 事件來源(Event Source) – 發出事件物件的來源, 如視窗元件的按鈕。 • 監聽者物件(Listener) – 被委託處理指定事件的物件。

  16. 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.

  17. 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, FileDialog, and Frame -- provide windows to contain components. • A Panel groups components within an area of an existing window. • A ScrollPane display a potentially large component in a limited amount of space, using scrollbars to control which part of the component is displayed.

  18. Windows (1/2) • Includes Dialog, FileDialog, and Frame. • Frames (框窗) create normal, full-fledged windows. • Dialogs(對話窗) create windows which depends on Frames and can be modal. • Example: The FileDialog(檔案對話盒) window for files:

  19. Windows (2/2) Dialog is a Window Frame is a Window javax.swing.JFrame

  20. Applet is a Panel

  21. ScrollPane is NOT a Panel

  22. ScrollPaneExample • The JDK 1.1 AWT introduced the ScrollPane 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.

  23. How to Use ScrollPane ScrollPane sp1 = new ScrollPane(); sp1.add(anotherComponent); • Creates a scroll pane and puts a child component in it: • You can also specify the scrollbar display policy in the ScrollPane: ScrollPane sp2 = new ScrollPane(ScrollPane.SCROLLBARS_ALWAYS); • SCROLLBARS_AS_NEEDED • 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. Other Constants

  24. Components to be put into a ScrollPane • When implement a component to be put in a ScrollPane: • Need to implement the child component's getPreferredSize 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.

  25. Scrolling-related code from the previous applet: //The component that will be scrolled. class ScrollableCanvas extends Canvas { ... Dimension preferredSize = new Dimension(600, 320); Dimension minimumSize = new Dimension(10, 10); public DimensiongetMinimumSize() { return minimumSize; } public DimensiongetPreferredSize() { return preferredSize; } public void paint(Graphics g) { g.drawImage(image, 0, 0, getBackground(), this); } }

  26. 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 getImage() methods. • …

  27. 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.

  28. Example: 英制公制轉換 (1/3) • http://java.sun.com/docs/books/tutorial/uiswing/components/example-1dot4/Converter.java • File lists: /* * A 1.4 application that requires the following files: * ConversionPanel.java * ConverterRangeModel.java * FollowerRangeModel.java * Unit.java */

  29. Example: 英制公制轉換 (2/3) 兩個主要 class: Converter ConversionPanel

  30. Example: 英制公制轉換 (3/3) The Component Hierarchy

  31. 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.drawRect(0,0, d.width - 1, d.height - 1); }

  32. AWT 1.0 Event Model 舊的方法

  33. Default Methods for Each Component 舊的方法 • action() (Event.ACTION_EVENT) • mouseEnter() (Event.MOUSE_ENTER) • mouseExit() (Event.MOUSE_EXIT) • mouseMove() (Event.MOUSE_MOVE) • mouseDown() (Event.MOUSE_DOWN) • mouseDrag() (Event.MOUSE_DRAG) • mouseUp() (Event.MOUSE_UP) • keyDown() (Event.KEY_PRESS or Event.KEY_ACTION) • keyUp() (Event.KEY_RELEASE or Event.KEY_ACTION_RELEASE) • gotFocus() (Event.GOT_FOCUS) • lostFocus() (Event.LOST_FOCUS) • handleEvent() (all event types)

  34. Example 舊的方法 public booleanaction(Event e, Object arg) { if (e.target instanceof TextField) { setSliderValue(getValue()); controller.convert(this); return true; } if (e.target instanceof Choice) { . . . } return false; } public booleanhandleEvent(Event e) { if (e.target instanceof Scrollbar) { textField.setText(String.valueOf(slider.getValue())); controller.convert(this); } return super.handleEvent(e); }

  35. Another example (1/ 7) 需要寫一個簡單的 HTML 把這 Applet 叫起來 //eventHandler.java import java.awt.*; class eventCanvas extends Canvas { boolean hasFocus; eventCanvas( int width, int height ) { setBackground( Color.yellow ); resize( width, height ); hasFocus = false; } public boolean mouseUp( Event e, int x, int y ) { eventHandler.reportEvent( "mouseUp" ); return true; }

  36. Another example (2/7 ) public boolean mouseDown( Event e, int x, int y ) { eventHandler.reportEvent( "mouseDown" ); return true; } public boolean mouseDrag( Event e, int x, int y ) { eventHandler.reportEvent( "mouseDrag" ); return true; } public boolean mouseEnter( Event e, int x, int y ) { eventHandler.reportEvent( "mouseEnter" ); return true; } public boolean mouseExit( Event e, int x, int y ) { eventHandler.reportEvent( "mouseExit" ); return true; }

  37. Another example (3/7 ) public boolean keyDown( Event e, int key ) { String eventString = "keyDown: "; String keyName, modifierName; modifierName = getModifierName( e ); if ( modifierName != null ) eventString += modifierName; keyName = getKeyName( key ); if ( keyName != null ) eventString += keyName; else if (( key >= 32 ) && ( key <= 127 )) eventString += new Character( (char)key ).toString(); else eventString += key; eventHandler.reportEvent( eventString ); return true; }

  38. Another example (4/7 ) public String getModifierName( Event e ) { if ( e.controlDown() ) return( "Control-" ); if ( e.metaDown() ) return( "Meta-" ); if ( e.shiftDown() ) return( "Shift-" ); return null; } public String getKeyName( int key ) { switch ( key ) { case Event.F1: return "F1"; case Event.F2: return "F2"; case Event.F3: return "F3"; case Event.F4: return "F4"; case Event.F5: return "F5"; case Event.F6: return "F6"; case Event.F7: return "F7"; case Event.F8: return "F8"; case Event.F9: return "F9"; case Event.F10: return "F10"; case Event.F11: return "F11"; case Event.F12: return "F12"; 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 "DownArrow"; case Event.PGUP: return "Page Up"; case Event.PGDN: return "Page Down"; } //switch return null; }

  39. Another example (5/7 ) public boolean keyUp( Event e, int key ) { eventHandler.reportEvent( "keyUp" ); return true; } public boolean gotFocus(Event e, Object what) { hasFocus = true; eventHandler.reportEvent( "gotFocus" ); repaint(); return true; } public boolean lostFocus(Event e, Object what) { hasFocus = false; eventHandler.reportEvent( "lostFocus" ); repaint(); return true; }

  40. Another example (6/7 ) public void paint( Graphics g ) { Rectangle r; r = bounds(); g = getGraphics(); if ( hasFocus ) g.setColor( Color.red ); else g.setColor( Color.yellow ); g.drawRect( 0, 0, r.width-1, r.height-1 ); g.drawRect( 1, 1, r.width-3, r.height-3 ); } } //class eventCanvas

  41. Another example (7/7) public class eventHandler extends java.applet.Applet { eventCanvas eCanvas; static TextArea tArea; public void init() { add( new Label( "Click and type in this Canvas:" ) ); eCanvas = new eventCanvas( 200, 100 ); add( eCanvas ); add( new Label( "Here’s a list of canvas events:" ) ); tArea = new TextArea( 15, 30 ); add( tArea ); setVisible(true); } public static void reportEvent( String eventString ) { tArea.appendText( eventString + "\r" ); } } 需要寫一個簡單的 HTML 把這 Applet 叫起來 <HTML><body> <applet code=eventHandler.class Width=555 Height=333> </applet>

  42. AWT 1.1. Event Model • In the 1.1 AWT event model, events are generated by event sources. • One or morelisteners 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. someComponent.addActionListener(instanceOfMyClass); • Declare the event handler implementing a listener interface. public class MyClass implements ActionListener { • The implementation of the methods in the listener interface. public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }

  43. Example public class MultiListener ... implements ActionListener { //... //where initialization occurs: button1.addActionListener(this); button2.addActionListener(this); button2.addActionListener(new Eavesdropper(bottomTextArea)); public void actionPerformed(ActionEvent e) { topTextArea.append(e.getActionCommand() + "\n"); } } class Eavesdropper implements ActionListener { ... public void actionPerformed(ActionEvent e) { myTextArea.append(e.getActionCommand() + "\n"); } }

  44. 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

  45. 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 MouseListener 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

  46. ActionListener

  47. 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 MyClass implements MouseListener { //... someObject.addMouseListener(this); //... /* Empty method definitions are required. */ public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mouseClicked(MouseEvent e) { //..Event handler implementation goes here... } }

  48. 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 MyClass extends MouseAdapter { //... someObject.addMouseListener(this); //... public void mouseClicked(MouseEvent e) { //...Event handler implementation goes here... } }

More Related