1 / 98

Object-Oriented Design and Programming (Java)

Object-Oriented Design and Programming (Java). Topics Covered Today. 3.2 Graphical User Interface 3.2.1 Swing Components and Containers 3.2.2 Swing Event Handling. GUI libraries in JAVA. Abstract Windows Toolkit (AWT) since Java 1.0

ttracy
Télécharger la présentation

Object-Oriented Design and Programming (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. Object-Oriented Design and Programming (Java)

  2. Topics Covered Today • 3.2 Graphical User Interface • 3.2.1 Swing Components and Containers • 3.2.2 Swing Event Handling

  3. GUI libraries in JAVA • Abstract Windows Toolkit (AWT) since Java 1.0 • Swing - Add-on since Java 1.1 and integral part of Java 1.2 • Third party GUI libraries like the Standard Windows Toolkit (SWT) e.g. used in Eclipse Here, we use Swing!

  4. Swing is Standard in Java 2 Platform(also known as JDK 1.2) • Includes Java2D • Adds support for MIDI, WAV, and other audio. • Swing package: javax.swing.* AWT package: java.awt.*

  5. Reference Book • Thinking in Java (2nd Edition), Bruce Eckel, Prentice Hall Chapter 13 Creating Windows & Applets • Getting Started with Swing http://java.sun.com/docs/books/tutorial/uiswing/

  6. New Features in Swing • Lightweight. Not built on native window-system windows. • Much bigger set of built-in controls. Trees, image buttons, tabbed panes, sliders, toolbars, color choosers, tables, etc. • Much more customizable(可定制). Can change border, text alignment, or add image to almost any control.

  7. New Features in Swing • Pluggable" look and feel. Can change look and feel at runtime, or design own look and feel. • Many miscellaneous new features. Double-buffering built in, tool tips, keyboard accelerators, custom cursors, etc.

  8. AWT Components primitive container

  9. Swing Components

  10. Frame • A Frame is a top-level window with a title and a border.

  11. Frame import java.awt.*; public class MyFrame extends Frame { public static void main(String args[ ]) { MyFrame fr = new MyFrame("Hello Out There"); fr.setSize(200,200); fr.setBackground(Color.red); fr.setVisible(true); } public MyFrame (String str) { super(str); } }

  12. Panel • Panel is the simplest container class. • A panel provides space in which an application can attach any other component, including other panels.

  13. Panel import java.awt.*; public class FrameWithPanel extends Frame{ public FrameWithPanel(String str){ super(str); } public static void main(String args[]){ FrameWithPanel fr = new FrameWithPanel("Frame with Panel"); Panel pan = new Panel(); fr.setSize(200,200); fr.setBackground(Color.red); fr.setLayout(null); pan.setSize(100,100); pan.setBackground(Color.yellow); fr.add(pan);// add pan to frame fr fr.setVisible(true); } }

  14. Layout Managers • Associated with containers • Automate the layout of elements • When elements are added to the container • When the window is resized • automatically adjust the positions and sizes of the elements.

  15. Hierarchy of Layout Managers Q: Can you identify the design pattern used here?

  16. BorderLayout • A border layout arranges and resizes container’s components to fit in five regions: north, south, east, west, and center. • Each region may contain no more than one component

  17. BorderLayout Example import java.awt.*; public class buttonDir{ public static void main(String args[]){ Frame f = new Frame("BorderLayout"); f.setLayout(new BorderLayout()); f.add("North", new Button("North")); f.add("South", new Button("South")); f.add("East", new Button("East")); f.add("West", new Button("West")); f.add("Center", new Button("Center")); f.setSize(200,200); f.setVisible(true); } }

  18. GridLayout • The GridLayout class is a layout manager that lays out a container's components in a rectangular grid.

  19. GridLayout import java.awt.*; public class ButtonGrid { public static void main(String args[]) { Frame f = new Frame("GridLayout"); f.setLayout(new GridLayout(3,2)); //3 rows & 2 columns f.add(new Button("1")); f.add(new Button("2")); f.add(new Button("3")); f.add(new Button("4")); f.add(new Button("5")); f.add(new Button("6")); f.setSize(200,200); f.setVisible(true); } }

  20. JLable • A JLabel can display both text and images • Example: JLabelDemo.java in Unit 3.2.1

  21. JButton • A JButton can not only display both text and image in the form of button, but also respond to an event triggered by users. • Example: JButtonDemo.java in Unit 3.2.1

  22. JRadioButton • Components of class JRadioButton can be selected or deselected by the user. If JRadioButton components are grouped, by means of the class ButtonGroup, only one button at a time can be selected. • Example: JRadioButtonDemo.java in Unit 3.2.1

  23. JTextField • Components of class JTextField let the user enter (or edit) a small quantity of text. • Example: JTextFieldDemo.java in Unit 3.2.1

  24. JTextArea • Components of class JTextArea let the user enter (or edit) multiple lines of text. If scroll bars are needed, the JTextArea is wrapped in a JScrollPane. • Example: JTextAreaDemo.java in Unit 3.2.1

  25. JList • Components of class JList let the user select one or more elements from a list. If scroll bars are needed, the JList is wrapped in a JScrollPane. • Example: JListDemo.java in Unit 3.2.1

  26. Back to the Buttons • You click buttons and they don’t do anything! • Well, what should they do? Java doesn’t know! • Capture the event that a button has been clicked, and write code to carry out the reaction. • Any Swing component (like JButton) can report any or all the things that happen to it.

  27. Some Events and the Associated Event Listeners

  28. ActionListener Model Every event handler requires three pieces of code: • A listener implements a listener interface or extends a class that implements a listener interface. For example: class ListenerOne implements ActionListener • Registers an instance of the event listener class on one or more components. For example: component.addActionListener( new ListenerOne()); • The event listener class implements the methods in the listener interface. For example: public void actionPerformed(ActionEvent e)

  29. ButtonEventsDemo • This demo contains 3 JRadioButtons and a JLabel. When a user clicks one of the radio buttons, the text in the label is updated. Only one radio button can be selected at a time because the radio buttons are grouped.

  30. FruitListDemo • This demo uses 3 components: a JList, a JTextArea, and a JButton. The JList contains a list of fruits and the JTextArea is initially empty. ListSelectionListener/valueChanged()

  31. GUI principles • GUI principles • Basic interacting objects supporting GUI • Components: GUI building blocks. • buttons, menus, labels, etc. • Events: reacting to user input. • button clicks, menu selections, etc. • Layout: arranging components to form a usable GUI. • layout managers.

  32. Views A = 30% B = 20% C = 50% Model Design Pattern - MVC • Model: the application object • View: its screen presentation • Controller: defines the way the user interface reacts to user input. Controller not shown

  33. View Controller User Actions Get Data State Change Notification Call Model Action Model Model-View-Controller • Model • Encapsulates Data presented by view • View • Renders Model Data • Controller • Model Controller • View Controller • Responds to user actions • Model is loosely coupled from view • State change communicated through notification. • Multiple views can be implemented for same model

  34. Display Product Detail Display Cart Add To Cart Continue Shopping Checkout Retrieve Profile Buy New Computer Confirm Address & Payment Submit Order Confirm Confirm Order Continue Shopping Purchase Task

  35. Controller Display Product Detail Display Cart Add To Cart Navigate “Continue Shopping” “Checkout” Retrieve Profile Views Confirm Address & Payment Submit Order State “Confirm” State Single User UI Process Reference Data Confirm Order “Continue Shopping” UI Navigation Graph Model Purchase Task Buy Computer

  36. Controller Display Product Detail Display Cart Add To Cart Navigate “Continue Shopping” “Checkout” Retrieve Profile Views Submit Order Confirm Address & Payment State “Confirm” State Single User UI Process Reference Data Confirm Order “Continue Shopping” UI Navigation Flow/Graph Model Purchase Task Buy Computer

  37. Event Delegation Model • The Delegation Event Model (事件委派模式) • Model used by Java to handle user interaction with GUI components • Describes how your program can respond to user interaction • Three important components: • Event Source • Event • Event Listener/Handler

  38. Event Source • GUI component that generates the event • Example: button, mouse, keyboard, etc

  39. Event Listener/Handler • Receives news of events and processes user's interaction • Example: displaying an information useful to the user, computing for a value

  40. Event Object • Created when an event occurs (i.e., user interacts with GUI component) • ActionEvent => clicking button in GUI • WindowEvent => closing a window • Contains all necessary information about the event that has occurred • Type of event that has occurred • Source of the event • May have one of several event classes as data type

  41. The Delegation Event Model • A listener should be registered with a source • Once registered, listener waits until an event occurs • When an event occurs • An event object created • Event object is fired by the source to the registered listeners • Once the listener receives an event object from the source • Deciphers the notification • Processes the event that occurred.

  42. The Delegation Event Model

  43. Registration of Listeners • Event source registering a listener: void add<Type>Listener(<Type>Listener listenerObj) where, • <Type> depends on the type of event source • Can be Key, Mouse, Focus, Component, Action and others • One event source can register several listeners • Registered listener being unregistered: void remove<Type>Listener(<Type>Listener listenerObj)

  44. Design Pattern Used in Java Event Handling • Observer Pattern • Aliases :Dependents, Publish-Subscribe • Category: behavioral • General Purpose • When one object changes state, all the dependent objects are notified and updated. • Allows for consistency between related objects without tightly coupling classes • e.g. “reduces coupling between objects” • “publish and subscription” services • eBay

  45. Observer Pattern - Key Players • Subject • Knows its observers – provides interface for attaching/detaching subjects • Observer • Defines an interface for notifying the subjects of changes to the object (ex. Data) • ConcreteSubject • Sends notification to observers when state changes by storing state to ConcreteObserver object • ConcreteObserver • Implements Observer interface to keep state consistent with subject

  46. Observer UML

  47. Real-World Example “General Broadcast” Observers “tuning in” to the notification

  48. Data Example Subject Interface Browser PDA Cell Phone Terminal XML xyz… Data is sent to the various observers Web Browser PDA Cell Phone Terminal Observers

  49. Weather Monitor Application

  50. Weather Monitor Application

More Related