Project JETT/Duke 1 javax.swing, events, and GUIs l GUI programming requires processing events  There’s no visible loop in the program  Wire up/connect.

Slides:



Advertisements
Similar presentations
1 Graphical User Interface (GUI) Applications Abstract Windowing Toolkit (AWT) Events Handling Applets.
Advertisements

Introduction to Java 2 Programming
Introduction to Java 2 Programming
CS18000: Problem Solving and Object-Oriented Programming.
Graphic User Interfaces Layout Managers Event Handling.
Fall 2007CS 225 Graphical User Interfaces Event Handling Appendix C.
Event Driven Programming and GUIs Part 3 CS221 – 4/15/09.
1 Chapter 7 Graphics and Event Handling. 2 Overview The java.awt and javax.swing packages and their subpackages support graphics and event handling. Many.
Event Handling Events and Listeners Timers and Animation.
Events ● Anything that happens in a GUI is an event. For example: – User clicks a button, presses return when typing text, or chooses a menu item ( ActionEvent.
Scott Grissom, copyright 2006Ch 11: GUI Slide 1 Graphical User Interfaces (Ch 11) Careful design of a graphical user interface is key to a viable software.
10.1 AWT The AWT classes Users today expect a Graphical User Interface (GUI) Improves application usability Difficult to implement cross-platform.
CSE 331 Software Design & Implementation Dan Grossman Spring 2015 GUI Event-Driven Programming (Based on slides by Mike Ernst, Dan Grossman, David Notkin,
Chapter 8: Graphical User Interfaces Objectives - by the end of this chapter, you should be able to do the following: –write a simple graphical user interface.
A.k.a. GUI’s.  If you want to discuss your Lab 2 grade come see me this week. ◦ Office: 436 ERB. One hour prior to class ◦ Open to Appointments MWF 
GUI Programming in Java
20-753: Fundamentals of Web Programming Copyright © 1999, Carnegie Mellon. All Rights Reserved. 1 Lecture 16: Java Applets & AWT Fundamentals of Web Programming.
ACM/JETT Workshop - August 4-5, ExceptionHandling and User Interfaces (Event Delegation, Inner classes) using Swing.
Welcome to CIS 083 ! Events CIS 068.
Java Swing, Events and MVC Optional Readings: Eckel’s Thinking in Java: Chap 14 (
MIT AITI 2003 Lecture 17. Swing - Part II. The Java Event Model Up until now, we have focused on GUI's to present information (with one exception) Up.
עקרונות תכנות מונחה עצמים תרגול 4 - GUI. Outline  Introduction to GUI  Swing  Basic components  Event handling.
Software Design 4.1 Tell, Don't Ask l Tell objects what you want them to do, do not ask questions about state, make a decision, then tell them what to.
Java Programming: Advanced Topics 1 Common Elements of Graphical User Interfaces Chapter 6.
Software Design 9.1 From Using to Programming GUIs l Extend model of "keep it simple" in code to GUI  Bells and whistles ok, should be easy to use and.
GUIs in Java Swing, Events CS2110, SW Development Methods Readings: MSD, Chapter 12 Lab Exercise.
Ch 3-4: GUI Basics Java Software Solutions Foundations of Program Design Sixth Edition by Lewis & Loftus Coming up: GUI Components.
Field Trip #19 Animations with Java By Keith Lynn.
 2002 Prentice Hall, Inc. All rights reserved Introduction Graphical User Interface (GUI) –Gives program distinctive “look” and “feel” –Provides.
1 CSC111H Graphical User Interfaces (GUIs) Introduction GUIs in Java Understanding Events A Simple Application The Containment Hierarchy Layout Managers.
– Advanced Programming P ROGRAMMING IN Lecture 21 Introduction to Swing.
1 Outline 1 Introduction 2 Overview of Swing Components 3 JLabel 4 Event Handling 5 TextFields 6 How Event Handling Works 7 JButton 8 JCheckBox and JRadioButton.
Graphic User Interface. Graphic User Interface (GUI) Most of us interact with computers using GUIs. GUIs are visual representations of the actions you.
Graphics and Event-Driven Programming in Java John C. Ramirez Department of Computer Science University of Pittsburgh.
Copyright © 2002, Systems and Computer Engineering, Carleton University c-Gui3.ppt * Object-Oriented Software Development Part 18-c Building.
MSc Workshop - © S. Kamin, U. ReddyLect 3 - GUI -1 Lecture 3 - Graphical User Interfaces r GUI toolkits in Java API r JFrame r GUI components.
COMP 321 Week 2. Outline Event-Driven Programming Events, Event Sources, Event Listeners Button and Timer Events Mouse Events, Adapters.
Layout Managers Arranges and lays out the GUI components on a container.
GUI Programming using NetBeans. RHS – SOC 2 GUI construction We have previously talked about elements in a (simple) GUI –Frames, Panes and Dialogs –Text.
1 / 67 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 14 Programming Fundamentals using Java 1.
CS324e - Elements of Graphics and Visualization Java GUIs - Event Handling.
CPS 108/ola.1 From XP to javax.swing.* l What parts of embracing change can we embrace in 108?  Evolutionary design, small releases, iterative enhancement.
Software Design 5.1 From Using to Programming GUIs l Extend model of "keep it simple" in code to GUI  Bells and whistles ok, but easy to use and hide.
UID – Event Handling and Listeners Boriana Koleva
Java GUI. Graphical User Interface (GUI) a list a button a text field a label combo box checkbox.
Anonymous Classes An anonymous class is a local class that does not have a name. An anonymous class allows an object to be created using an expression.
Week 6: Basic GUI Programming Concepts in Java Example: JFrameDemo.java container : a screen window/applet window/panel that groups and arranges components.
Object Oriented Programming.  Interface  Event Handling.
CSE 331 Software Design & Implementation Hal Perkins Autumn 2012 Event-Driven Programming 1.
Chapter 14: Introduction to Swing Components. Objectives Understand Swing components Use the JFrame class Use the JLabel class Use a layout manager Extend.
Graphical User Interfaces (GUI). PART ONE About GUI’s.
Java Swing, Events Readings: Just Java 2: Chap 19 & 21, or Eckel’s Thinking in Java: Chap 14 Slide credits to CMPUT 301, Department of Computing Science.
Chapter 10 - Writing Graphical User Interfaces1 Chapter 10 Writing Graphical User Interfaces.
Swing GUI Components So far, we have written GUI applications which can ‘ draw ’. These applications are simple, yet typical of all Java GUI applications.
Graphical User Interface (GUI)
1 Lecture 8: User Interface Components with Swing.
Sep 181 Example Program DemoTranslateEnglishGUI.java.
MIT AITI 2004 Swing Event Model Lecture 17. The Java Event Model In the last lecture, we learned how to construct a GUI to present information to the.
1 A Quick Java Swing Tutorial. 2 Introduction Swing – A set of GUI classes –Part of the Java's standard library –Much better than the previous library:
AWT Vs SWING. 2 AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses.
Introduction Many Java application use a graphical user interface or GUI (pronounced “gooey”). A GUI is a graphical window or windows that provide interaction.
Graphical User Interfaces
A First Look at GUI Applications
A Quick Java Swing Tutorial
Ellen Walker Hiram College
GUI Programming III: Events
Steps to Creating a GUI Interface
A Quick Java Swing Tutorial
MVC overview Model, View, Controller is MVC
Presentation transcript:

Project JETT/Duke 1 javax.swing, events, and GUIs l GUI programming requires processing events  There’s no visible loop in the program  Wire up/connect widgets, some generate events, some process events Pressing this button causes the following to happen  We want to practice “safe wiring”, meaning? l We need to put widgets together, what makes a good user- interface? What makes a bad user-interface?  How do we lay widgets out, by hand? Using a GUI- builder? Using a layout manager? l How do we cope with widget complexity?

Project JETT/Duke 2 Wiring Buttons and Events and GUIs l Button/Menu generates event  ActionEvent l Click mouse generates event  MouseEvent l When creating widget/button  Attach listeners for events  Can have multiple listeners l Activating widget/button  Causes listeners to “hear”  Listeners act accordingly l Press E, handle E-event  What happens? l Press A, handle A-event … EA

Project JETT/Duke 3 Action and other events l Widgets generate events, these events are processed by event listeners  Different types of events for different scenarios: press button, release button, drag mouse, press mouse button, release mouse button, edit text in field, check radio button, …  Some widgets “fire” events, some widgets “listen” for events l To process events, add a listener to the widget, when the widget changes, or fires, its listeners are automatically notified.  Firing widget is the “model”, listener is the “view” aka observable and observer, respectively

Project JETT/Duke 4 Code to wire widgets/events/listeners Old-fashioned way, make the GUI the listener – has doNext()  Listener is an object, with the right method (kind of event) myNextButton = new JButton("next"); myNextButton.addActionListener(this); public void actionPerformed(ActionEvent e) { if (e.getSource() == myNextButton) doNext(); } l New way, create anonymous event-listener object/on-the-fly  Inner class, has access to/can call GUI functions myNextButton.addActionListener( new ActionListener(){ public void actionPerformed(ActionEvent e) { doNext(); } });

Project JETT/Duke 5 Adding Listeners l In lots of code you’ll see that the Container widget is the listener, so pressing a button or selecting a menu is processed by the Container/Frame’s actionPerformed method  All ActionListeners have an actionPerformed method, is this interface/implements or inheritance/extends?  Here’s some “typical” code, why is this bad? void actionPerformed(ActionEvent e) { if (e.getSource() == thisButton) … else if (e.getSource() == thatMenu)… }

Project JETT/Duke 6 A GUI object can be its own client l Occasionally a GUI will be a listener of events it generates  Simple, but not extendable  Inner classes can be the listeners, arguably the GUI is still listening to itself, but … Encapsulating the listeners in separate classes is better l Client (nonGUI) objects cannot access GUI components  Properly encapsulated JTextField, for example, responds to aGui.displayText(),  Tension: simplicity vs. generality l Don’t wire widgets together directly, use methods/classes  Eventual trouble when GUI changes

Project JETT/Duke 7 Using inner/anonymous classes l For each action/event that must be processed, create an object to do the processing  Command pattern: parameterize object by an action to perform, queue up requests to be executed at different times, support undo  There is a javax.swing Event Queue for processing events, this is the hidden while loop in event processing GUI programs l The inner class can be named, or it can be created “anonymously”  For reuse in other contexts, sometimes naming helpful  Anonymous classes created close to use, easy to read (arguable to some)

Project JETT/Duke 8 Listeners l Events propagate in a Java GUI as part of the event thread  Don’t manipulate GUI components directly, use the event thread  Listeners/widgets register themselves as interested in particular events Events go only to registered listeners, can be forwarded/consumed ActionListener, KeyListener, ItemListener, MouseListener, MouseMotionListener, …, see java.awt.event.*  Isolate listeners as separate classes, mediators between GUI, Controller, Application  Anonymous classes can help here too

Project JETT/Duke 9 JComponent/Container/Component l The java.awt package was the original widget package, it persists as parent package/classes of javax.swing widgets  Most widgets are JComponents (subclasses), to be used they must be placed in a Container The former is a swing widget, the latter awt: Jconvention. l A Container is also a Component  JFrame is often the “big container” that holds all the GUI widgets, we’ll use this and JApplet (awt counterparts are Frame and Applet)  A JPanel is a JComponent that is also a Container Holds JComponents, for example and is holdable as well

Project JETT/Duke 10 Creating a GUI l Create Frame (applet)  Application/Applet l Create main panel  BorderLayout l Create button panels  Top/Bottom, wired l Create menus  Wired when created l Create main view/panel  Shows what’s happening l Create non-view logic and attach appropriately  Debug 5 days and serve Main Panel B1B2B3 FILE HELP

Project JETT/Duke 11 Creating a GUI (again) l Create Frame (applet)  Application/Applet l Create main panel  BorderLayout l Create button panels  Top/Bottom, wired l Create menus  Wired when created l Create main view/panel  Shows what’s happening l Create non-view logic and attach appropriately  Debug 5 days and serve Main Panel

Project JETT/Duke 12 Widget layout l A Layout Manager “decides” how widgets are arranged in a Container  In a JFrame, we use the ContentPane for holding widgets/components, not the JFrame itself  Strategy pattern: “related classes only differ in behavior, configure a class with different behaviors… you need variants of an algorithm reflecting different constraints…context forwards requests to strategy, clients create strategy for the context” Context == JFrame/container, Strategy == Layout l Layouts: Border, Flow, Grid, GridBag, Spring, …  I’ll use Border, Flow, Grid in my code

Project JETT/Duke 13 BorderLayout (see Browser.java) l Default for the JFrame content pane l Provides four areas, center is “main area” for resizing l Recursively nest for building complex (yet simple) GUIs BorderLayout.CENTER for adding components  Some code uses “center”, bad idea (bugs?) CENTER NORTH SOUTH WESTWEST EASTEAST

Project JETT/Duke 14 JFrame/JApplet things to remember l setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);  Sometimes see WindowListener, previous JDK  Not used in applets l setContentPane(panelWithEverything);  Create panel, add to top-level content pane l setVisible(true);  Must have this in application l JFrame  setSize(x,y); pack(); setTitle(..) l JApplet  init(); arguments via getParameter(..)

Project JETT/Duke 15 Model, View, Controller overview l Model, View, Controller is MVC  Model stores and updates state of application Example: calculator, what's the state of a GUI-calculator?  When model changes it notifies its views Example: pressing a button on calculator, what happens?  The controller interprets commands, e.g., button-click, forwards them appropriately to model ( not to view ) Example: code for calculator that reacts to button presses  Controller isn't always a separate class, often part of GUI- based view in M/VC l MVC is a fundamental design pattern : solution to a problem at a general level, not specific code per se

Project JETT/Duke 16 MVC in SameGame/Clickomania l Clicking on a piece connected to more than one causes pieces to be removed  See GameGui, GameCore, GameModel, GameApplet, GameMove l The model “knows” the location of the pieces  Determines if move is legal  Makes a move (records it) and updates views l View shows a board and information, e.g., undo possible  See IGameView interface, implemented by application and applet via GameCore

Project JETT/Duke 17 SameGame MVC: Controller l Here the GameCore communicates with model so acts as controller together with ButtonPanel  Sometimes a middleman class isn’t a good idea, extra layer of code that might not be needed  Often in MVC model communicates with multiple views, but communication to model via controller l GameCore implements IGameView, easy to incorporate new controllers/views  Model doesn’t know about implementation  Model doesn’t know about button panels

Project JETT/Duke 18 Controller and Commands l Use-case for making a move:  Move generated, e.g., by button-click  Move forwarded to model (by controller) (If move is made, then undo state set to true in views) If move is made, then views update board display l Use-case for undoing a move  Undo generated, e.g., by button or menu choice  Undo forwarded to model (by controller) If undo changes board, views will be updated If future undo not possible, undo state set to false