980 likes | 1.13k Views
Continuation: GUI’s and eventhandlers in java +Some on design patterns. Lecturer: Martin Jagersand Department of Computing Science University of Alberta Notes based on previous courses by Ken Wong, Eleni Stroulia Zach Dodds, Martin Jagersand. Today. Example GUI application: Calculator
E N D
Continuation:GUI’s and eventhandlers in java+Some on design patterns. Lecturer: Martin Jagersand Department of Computing Science University of Alberta Notes based on previous courses by Ken Wong, Eleni Stroulia Zach Dodds, Martin Jagersand
Today • Example GUI application: Calculator • Some on design patterns and strategies
GUI practicalities • Divide task into subtasks/abstractions. • Decide how user interacts with each subtask • Design and implement drawing of GUI components, buttons etc. • Connecting buttons, sliders etc to code. • Eventhandlers
Containers: • Frame • top level container (window) • Has typical window components such as close buttons, possible scroll down menus etc • Panel • intermediate container • Organizes contained components • Atomic components • Buttons, labels etc. • Presents bits of info, allow interactio
Layouts • Layouts arrange items by specifying the relative locations in a pane. • Why layouts? – Make interfaces flexible to different windows, resizing etc. • Alternative: use absolute positioning of each item • Tedious for the programmer • Inflexible for the user (can’t stretch window to see more)
Event handling • How to connect graphics to action • Handled though interfaces “ActionListeners” • Programmers implement and specialize these for their application
Event handling • Source object: e.g. button • Target object: programmed to react appropriately
Case study:Calculator GUI • Was assignment 1 a couple of years ago…
Design idea 1 • Use several nested panes for structurally different components: Jframe Command history display Immediate results display Alfa keypad Numeric keypad
Small Big Flexible layout through the layout manager
Structure • Abstract into two classes: • Extend Jframe to set up the window and menu bars • Extend Jpanel to set up and arrange the calculator buttons and displays
JFrame Class JavaCalcFrame extends Jframe //constructor for menu etc : // misc events handling, e.g.: addWindowListener(new WindowAdapter(){ public void windowClosing(WindowEvent e){ System.exit(0); } }); : //Instantiate main panel Container contentpane = getContentPane(); CalculatorPanel panel = new CalculatorPanel(); contentPane.add(panel); Example of anonymous class implementing listener
JPanelCalculator panel class CalculatorPanel extends JPanel implements ActionListener, KeyListener • Implements reactive pattern.
Hierarchy of panels class CalculatorPanel extends Jpanel : setLayout(new BorderLayout()); //Component and panel setup JPanel eastPanel = new JPanel(); eastPanel.setLayout(new BorderLayout()); //display display = new JTextField(12); display.setHorizontalAlignment(JTextField.RIGHT); display.setEditable(false); Color col = new Color(255,255,255); display.setBackground(col); display.addKeyListener(this); Font f = new Font("MonoSpaced", Font.BOLD, 10); display.setText("0"); eastPanel.add(display, "North");
Hierarchy of panels 2 //scroll capability JScrollPane scrollPane = new JScrollPane(numList); scrollPane.setFont(f); add(scrollPane, "West"); scrollPane.addKeyListener(this); //button panels JPanel moreButs = new JPanel(); moreButs.setLayout(new GridLayout(4, 2)); : eastPanel.add(moreButs, "West"); : centerpanel = new JPanel(); centerpanel.setLayout(new GridLayout(4, 4)); eastPanel.add(centerpanel, "Center"); : add(eastPanel, ("Center")); Add history window, alfa and numeric buttons to intermediate pane Add intermediate pane
Adding atomic items private void addButton(Container c, String s) { JButton b = new JButton(s); c.add(b); b.addKeyListener(this); b.addActionListener(this); but = b; } Take care of event handling in same class (Reactive pattern)
Adding atomic items //button panels JPanel moreButs = new JPanel(); moreButs.setLayout(new GridLayout(4, 2)); String moreButtons[] = {"C ", "CE", "M+", "M-", "MR", "MC", SQRT, "%"}; for (i = 0; i < 8; i++) { addButton(moreButs, moreButtons[i]); } eastPanel.add(moreButs, "West"); centerpanel = new JPanel(); centerpanel.setLayout(new GridLayout(4, 4)); String buttons = "789/456x123-0.+="; for (i = 0; i < buttons.length(); i++) addButton(centerpanel, buttons.substring(i, i + 1)); centerpanel.setFont(f); eastPanel.add(centerpanel, "Center");
EventhandlersMouse events //mouse events public void actionPerformed(ActionEvent evt) { st = evt.getActionCommand(); doAction(st); } Required in interface Call calculation procedure with string of events
EventhandlersKey events //Event handlers public void keyAction(KeyEvent e) { char c = e.getKeyChar(); //handy substitutions if (c == '*') c = 'x'; else if (c == 'p') c = '+'; //enable the Enter keys else if (c == '\n' || c==141) c = '='; else if (c == 'c') c = '%'; st = c + ""; if (c == 'q') st = SQRT; else st = c + ""; doAction(st); }
Remains • Write the method “doAction” to perform the actual calculations based on the string of events. (exercise)
Lecture 8, Part 2Designing Classes • Heuristics and guidelines: • discovering a design • evaluating a design
Designing Classes • Issues: • process is iterative • introduce classes • consider alternative ideas • requires good judgement • comes with experience
Discovering Class Design • Inspirations for classes: • behavioral perspective • focus on actions on the system • structural perspective • focus on relationships among components • information perspective • focus on the role of information and its manipulation
Behavioral Perspective • Identify actions(what the system does). • Reveal objects to perform the actions. • Form collaborations of objects for more complex actions.
Behavioral Perspective • Questions to ask: • What object initiates the action? • What objects collaborate in performing the action? • What objects are altered in performing the action? • What objects are queried during the action?
Behavioral Perspective • Categories of objects often associated with action: • actor • reactor • transformer • agent
Behavioral Perspective • Actor: • has a specific goal or mission • drives the system to achieve the expected result • may enforce the sequencing of activities • may cope with exceptional conditions
Behavioral Perspective • Reactor: • responds to events:internal, external, and user interface • determines the appropriate reaction • initiates the response • may require state or be stateless • e.g., event handler, action listener
Behavioral Perspective • Transformer: • alters input data in some way and produces output • may be sequenced or pipelined • kinds:formatter, filters
Behavioral Perspective • Formatting transformer: • displayer • render data in human-readable form • e.g., stream I/O, text layout, etc. • marshaller • flatten or linearize structured data • e.g., converting data to file blocks • encoder • convert data into a standard format or encrypt the data for secure transfer
Behavioral Perspective • Filtering transformer: • screens the input data according to some criteria • e.g., pattern matching
Behavioral Perspective • Agent: • assists other objects in some way • relieves other objects of a responsibility • hides information • kinds:messenger, server, finder, communicator
Behavioral Perspective • Messenger agent: • relays information from one part of the system to another • relieves the sender from the responsibilities of locating the receiver, delivering the information, etc.
Behavioral Perspective • Server agent: • produces and/or consumes data • relieves clients from the responsibilities of managing the data • e.g., database, web, etc.
Behavioral Perspective • Finder agent: • locates other objects or data • contains knowledge of how and where to search • e.g., search engine, tool registry
Behavioral Perspective • Communicator agent: • interacts with the user • e.g., present a file dialog
II: Structural Perspective • Identify relationships implied by the specification(e.g., consists of, uses, maintains, etc.). • Form relationships among candidate entities (classes).
Structural Perspective • Questions to ask: • What objects are involved in the relationship? • What objects are necessary to sustain the relationship? • What objects not in the relationship are aware of and exploit the relationship? • What objects not in the relationship are used by the related objects?
Structural Perspective • Categories of structure: • acquaintance • containment • collection
Structural Perspective • Acquaintance structure: • association of objects • some objects know about one or more of the other objects • kinds:symmetric or asymmetric,persistent or transitory,direct or indirect
Structural Perspective • Containment structure: • aggregation of parts into a whole • “contains”, “consists of”, “has” • kinds:collaborator, controller
Structural Perspective • Collaborator containment: • whole is created by the interaction of its parts • e.g., StopWatch
Structural Perspective • Controller containment: • controller object may have total control over contained objects • e.g., boss/worker model • boss delegates tasks to workers • workers are independent of each other • workers are invisible to the client
Structural Perspective • Collection structure: • like containment, but collection does not totally conceal the grouped objects • objects might be shared across collections • kinds:peer, iteration, coordinator
Structural Perspective • Peer collection: • collection object imposes no control and simply gives a name to the grouping • grouped objects have equal status
Structural Perspective • Iterator collection: • collection object provides selection, ordering, or traversal over its objects • grouped objects may need to support a common interface(e.g., Comparable)
Structural Perspective • Coordinator collection: • collection object maintains some invariant condition among its objects • e.g., RadioButton collection
III: Information Perspective • Study the information content and manipulations of the system. • Distinguish betweendata (info to be processed) and state (info used to control processing).