Graphical User Interface Programming. Robert M. Dondero, Ph.D. Princeton University



Similar documents
GUI Components: Part 2

Mouse Event Handling (cont.)

Swing. A Quick Tutorial on Programming Swing Applications

GUIs with Swing. Principles of Software Construction: Objects, Design, and Concurrency. Jonathan Aldrich and Charlie Garrod Fall 2012

CS 335 Lecture 06 Java Programming GUI and Swing

LAYOUT MANAGERS. Layout Managers Page 1. java.lang.object. java.awt.component. java.awt.container. java.awt.window. java.awt.panel

5.17 GUI. Xiaoyi Jiang Informatik I Grundlagen der Programmierung

The Abstract Windowing Toolkit. Java Foundation Classes. Swing. In April 1997, JavaSoft announced the Java Foundation Classes (JFC).

Using A Frame for Output

Lecture VII JAVA SWING GUI TUTORIAL

GUI Event-Driven Programming

Extending Desktop Applications to the Web

@ - Internal # - Online TH PR OR TW TOTAL HOURS # @ 175

Programming with Java GUI components

How To Build A Swing Program In Java.Java.Netbeans.Netcode.Com (For Windows) (For Linux) (Java) (Javax) (Windows) (Powerpoint) (Netbeans) (Sun) (

Fondamenti di Java. Introduzione alla costruzione di GUI (graphic user interface)

Principles of Software Construction: Objects, Design and Concurrency. GUIs with Swing. toad Spring 2013


GUJARAT TECHNOLOGICAL UNIVERSITY, AHMEDABAD, GUJARAT COURSE CURRICULUM COURSE TITLE: ADVANCE JAVA PROGRAMMING (COURSE CODE: )

Appendix B Task 2: questionnaire and artefacts

Assignment # 2: Design Patterns and GUIs

Java Mouse and Keyboard Methods

Python Crash Course: GUIs with Tkinter

Java is commonly used for deploying applications across a network. Compiled Java code

Software Design: Figures

Graphical User Interfaces

Konzepte objektorientierter Programmierung

Event processing in Java: what happens when you click?

Skills and Topics for TeenCoder: Java Programming

java.applet Reference

Artificial Intelligence. Class: 3 rd

core 2 Handling Mouse and Keyboard Events

BHARATHIAR UNIVERSITY COIMBATORE SCHOOL OF DISTANCE EDUCATION

Developing GUI Applications: Architectural Patterns Revisited

Mapping to the Windows Presentation Framework

How Scala Improved Our Java

Advanced Network Programming Lab using Java. Angelos Stavrou

The class JOptionPane (javax.swing) allows you to display a dialog box containing info. showmessagedialog(), showinputdialog()

Karsten Lentzsch JGoodies SWING WITH STYLE

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Java GUI Programming. Building the GUI for the Microsoft Windows Calculator Lecture 2. Des Traynor 2005

Java Programming Guide - Quick Reference. Java Programming Guide - Quick Reference. Java Comments: Syntax for a standalone application in Java:

Fachbereich Informatik und Elektrotechnik Java Swing. Advanced Java. Java Swing Programming. Programming in Java, Helmut Dispert

core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt

CSS 543 Program 3: Online Tic-Tac-Toe Game Professor: Munehiro Fukuda Due date: see the syllabus

Mobile App Tutorial Animation with Custom View Class and Animated Object Bouncing and Frame Based Animation

Java GUI Programming

Essentials of the Java(TM) Programming Language, Part 1

GUI application set up using QT designer. Sana Siddique. Team 5

JIDE Common Layer Developer Guide (Open Source Project)

Syllabus for CS 134 Java Programming

Rapid Application Development with GNOME and Python

Tutorial: Time Of Day Part 2 GUI Design in NetBeans

Programação Orientada a Objetos. Programando Interfaces Gráficas Orientadas a Objeto Parte 2

1 Hour, Closed Notes, Browser open to Java API docs is OK

Tutorial Reference Manual. Java WireFusion 4.1

How to Convert an Application into an Applet.

JIDE Action Framework Developer Guide

CREATE AN ANIMATED AQUARIUM IN POWERPOINT

Essentials of the Java Programming Language

Writer Guide. Chapter 15 Using Forms in Writer

Lab 9. Spam, Spam, Spam. Handout 11 CSCI 134: Spring, To gain experience with Strings. Objective

Mobile Web Design with HTML5, CSS3, JavaScript and JQuery Mobile Training BSP-2256 Length: 5 days Price: $ 2,895.00

Chapter 15 Using Forms in Writer

CREATE A 3D MOVIE IN DIRECTOR

method is never called because it is automatically called by the window manager. An example of overriding the paint() method in an Applet follows:

Click on various options: Publications by Wizard Publications by Design Blank Publication

Creating a Poster in PowerPoint A. Set Up Your Poster

GUI and Web Programming

Demo: Embedding Windows Presentation Foundation elements inside a Java GUI application. Version 7.3

Done. Click Done to close the Capture Preview window.

Scientific Visualization with wxpython and Matplotlib. Scott Pearse CSCI 5448 Spring 2011

Specialized Programme on Web Application Development using Open Source Tools

JiST Graphical User Interface Event Viewer. Mark Fong

Microsoft Publisher 2010 What s New!

Implementação. Interfaces Pessoa Máquina 2010/ Salvador Abreu baseado em material Alan Dix. Thursday, June 2, 2011

Object Oriented Programming with Java. School of Computer Science University of KwaZulu-Natal

Guide to SAS/AF Applications Development

Cours de Java. Sciences-U Lyon. Java - Introduction Java - Fondamentaux Java Avancé.

If you know exactly how you want your business forms to look and don t mind

Design. in NetBeans 6.0

public class Craps extends JFrame implements ActionListener { final int WON = 0,LOST =1, CONTINUE = 2;

Dev Articles 05/25/07 11:07:33

Homework/Program #5 Solutions

Automated Data Collection for Usability Evaluation in Early Stages of Application Development

Summer Internship 2013

Mensch-Maschine-Interaktion 1. Chapter 8 (June 21st, 2012, 9am-12pm): Implementing Interactive Systems

Chaco: A Plotting Package for Scientists and Engineers. David C. Morrill Enthought, Inc.

Model-View-Controller (MVC) Design Pattern

Customization Manager in Microsoft Dynamics SL 7.0

VisIt Visualization Tool

Transcription:

Graphical User Interface Programming Robert M. Dondero, Ph.D. Princeton University 1

Objectives You will learn about: Graphical user interface (GUI) programming Specifically... For Java: The AWT/Swing GUI library For Python: The Tkinter GUI library 2

Objectives For each: Interface structure Program structure Components Dialog Boxes Layout managers Event handling First Java/AWT, then Python/Tkinter 3

Running GUI Apps Option 1: Run on your computer Requirement: Caveats: Install Java or Python on your computer Make sure you install proper version Must test Asgt 3 on penguins 4

Running GUI Apps Option 2: Run on penguins Requirement: Run X Window System Server on local computer That is, on your computer or lab computer Instructions available through "Topics" Web page 5

Part 1: Java AWT and Swing 6

AWT/Swing Brief History Abstract Window Toolkit (AWT) Java 1.0 Delegates creation/behavior of each GUI element to native GUI toolkit on each target platform Difficult to write highly-portable library Applications constrained to greatest common denominator approach 7

AWT/Swing Brief History Swing Java 1.2 Relies on underlying windowing system only to display and paint windows Paints components (buttons, menus, etc.) itself onto blank windows Easy to write portable library Application/user can choose look-and-feel Built on top of AWT architecture 8

AWT/Swing Window Structure JFrame JPanel JPanel 9

AWT/Swing Pgm Structure See FrameTest.java Create class to implement Runnable Create run() method within class Create JFrame object within run() method main() method: Creates new Runnable object Passes to EventQueue.invokeLater() EventQueue.invokeLater() method starts event loop 10

AWT/Swing Pgm Structure Generalizing Suggestion: accept as a pattern More details in "Threads" lecture 11

Swing Components See ComponentTest.java JFrame, JPanel JButton, JLabel, JTextField, JTextArea, JScrollPane, JScrollBar, JSlider, JCheckBox ButtonGroup, JRadioButton, Border JComboBox JMenuBar, JMenu, JMenuItem, JPopupMenu JToolBar Tool tips 12

Swing Dialog Components See OptionPaneMessageTest.java See OptionPaneConfirmTest.java See OptionPaneOptionTest.java See OptionPaneInputTest.java JOptionPane See FileChooserTest.java JFileChooser Generalizing... 13

Swing Components java.lang.object java.awt.component java.awt.container java.awt.window java.awt.frame javax.swing.jframe java.awt.dialog javax.swing.jdialog javax.swing.jcomponent javax.swing.jpanel javax.swing.jtextcomponent javax.swing.jtextfield javax.swing.jtextarea javax.swing.jlabel javax.swing.jscrollpane javax.swing.jscrollbar javax.swing.jslider javax.swing.jcombobox java.awt.abstractbutton javax.swing.jbutton javax.swing.jtogglebutton javax.swing.jradiobutton javax.swing.jmenuitem javax.swing.jmenu javax.swing.jmenubar javax.swing.joptionpane javax.swing.jfilechooser 14

AWT Layout Managers See FlowLayoutTest.java FlowLayout Flow is maintained as window resizes See GridLayoutTest.java GridLayout Components arranged in 2-D grid 15

AWT Layout Managers See BorderLayoutTest.java BorderLayout North and south border: sizes are fixed vertically, expand horizontally East and west border: sizes are fixed horizontally, expand vertically Center expands both horizontally and vertically 16

AWT Layout Managers And others; example... GridBagLayout "The mother of all layout managers" Horstmann and Cornell Beyond COS 333 scope (Unnecessary for assignments) Generalizing... 17

AWT Layout Managers java.lang.object java.awt.flowlayout java.awt.borderlayout java.awt.gridlayout java.awt.gridbaglayout java.awt.boxlayout java.awt.cardlayout java.awt.grouplayout java.awt.overlaylayout java.awt.scrollpanelayout java.awt.springlayout java.awt.viewportlayout 18

AWT Event Handling Show EventTest1.java JButton event handling Event handling for other components is similar Listener object must access panel Generalizing... 19

AWT Event Handling Problem: Listener object often must access Components other than the one generating the event Awkward to pass Components to Listener constructor Solution: Make the Runnable object the Listener... 20

AWT Event Handling See EventTest2.java EventTestRunnable2 implements ActionListener EventTestRunnable2 class is large; serves multiple purposes 21

AWT Event Handling Problem: Previous approach can yield large complex classes Solution: Inner classes... 22

AWT Event Handling See EventTest3.java ColorActionListener3 is inner class Editorial: Defined within EventTestRunnable3 ColorActionListener3 object can access fields of EventTestRunnable3 objects Are inner classes worth the added complexity? Generalizing... 23

AWT Event Handling Semantic events: Component Listener Interface Its Methods Parameter Its Methods AbstractButton JComboBox JTextField JScrollBar JSlider ActionListener actionperformed() AdjustmentListener adjustmentvaluechanged() ChangeListener statechanged() ActionEvent getsource(), getid(), getactioncommand(), getmodifiers() AdjustmentEvent getsource(), getid(), getadjustable(), getvalue(), getadjustmenttype() ChangeEvent getsource(), getid() AbstractButton JComboBox ItemListener itemstatechanged() ItemEvent getsource(), getid(), getitem(), getstatechange(), getitemselectable() 24

AWT Event Handling Low-level events: Component Listener Interface Its Methods Parameter Its Methods Component FocusListener focusgained() focuslost() FocusEvent getsource(), getid(), getcomponent(), istemporary() Component KeyListener keypressed() keyreleased() keytyped() KeyEvent getsource(), getid(), getcomponent(), getwhen(), getmodifiers(), isaltdown(), iscontroldown(), ismetadown(), isshiftdown(), getkeychar(), getkeycode(), getkeymodifierstext(), getkeytext(), isactionkey() Component MouseListener mousepressed() mousereleased() mouseentered() mouseexited() mouseclicked() MouseEvent getsource(), getid(), getwhen(), getmodifiers(), isaltdown(), iscontroldown(), ismetadown(), isshiftdown(), getclickcount(), getx(), gety(), getpoint(), translatepoint(), ispopuptrigger() Component MouseMotionListener mousedragged() mousemoved() MouseEvent getsource(), getid() 25

AWT Event Handling Low-level events: Component Listener Interface Its Methods Parameter Its Methods Component Window Window Window MouseWheelListener mousewheelmoved() WindowListener windowclosing() windowopening() windowopened() windowiconified() windowdeiconified() windowclosed() windowactivated() windowdeactivated() WindowFocusListener windowgainedfocus() windowlostfocus() WindowStateListener windowstatechanged() MouseWheelEvent getsource(), getid(), getwheelrotation(), getscrollamount() WindowEvent getsource(), getid(), getcomponent(), getwindow() WindowEvent getsource(), getid(), getcomponent(), getwindow() WindowEvent getsource(), getid(), getoldstate(), getnewstate() 26

AWT Event Handling See EventTestAll.java AWT informs JComponent and Window objects of many events 27

An AWT/Swing Example See ColorDisplayer.java Slightly larger and more realistic Multiple interacting components 28

Part 2: Python Tkinter 29

Tkinter Brief History Tcl Very successful scripting language John Ousterhout (Stanford U.) 30

Tkinter Brief History Tk Cross-platform GUI toolkit Developed for Tcl Ported to other scripting languages Ruby, Perl, Python

Tkinter Brief History Tkinter Python interface to TK ("Tk interface") Python wrapper around Tk The "standard" Python GUI library Distributed with Python Other Python GUI options are available http://wiki.python.org/moin/guiprogramming 32

Tkinter Window Structure Toplevel Frame Frame 33

Tkinter Program Structure See frametest.py TK constructor creates a Toplevel object tk.mainloop() method starts event handling loop Generalizing Suggestion: accept as a pattern 34

Tkinter Components See componenttest.py Label Button, Checkbutton, Radiobutton Entry Listbox Scale, Scrollbar Menu Text, ScrolledText Generalizing... 35

Tkinter Components object BaseWidget (and Pack, Grid, Place) Widget Label Button Checkbutton Radiobutton Entry Listbox Scale Scrollbar Text ScrolledText Menu Frame BaseWidget (and Wm) Toplevel No combo box 36

Tkinter Components Constructor arguments: First argument is parent Frame Subsequent arguments set options Each widget is a mapping After construction, use widget['option'] to get or set an option 37

Tkinter-Related Dialogs See messageboxtest.py tkmessagebox module See simpledialogtest.py tksimpledialog module See filedialogtest.py tkfiledialog module See colorchoosertest.py tkcolorchooser module 38

Tkinter-Related Dialogs Generalizing: tkmessagebox module askokcancel() askquestion() askretrycancel() askyesno() showerror() showinfo() showwarning() tksimpledialog askfloat() askinteger() askstring() tkfiledialog module askdirectory() askopenfilename() askopenfilenames() asksaveasfilename() tkcolorchooser module askcolor() 39

Tkinter Layout Managers See packertest.py Pack class, pack() method Widget inherits from Pack Can send pack() message to any Widget object to "pack" it within its parent Widget 40

Tkinter Layout Managers Same functionality as AWT BorderLayout... North and south border: sizes are fixed vertically, expand horizontally East and west border: sizes are fixed horizontally, expand vertically Center expands both horizontally and vertically 41

Tkinter Layout Managers See griddertest.py Grid class, grid() method Widget inherits from Grid Can send grid() message to any Widget object to "grid" it within its parent object Same functionality as AWT GridLayout... Components arranged in 2-D grid Generalizing... 42

Tkinter Layout Managers And one more... Place Low-level layout manager Places widgets within parent exactly as the widget requires Used to implement custom layout managers Beyond the scope of COS 333 43

Tkinter Layout Managers object Pack Grid Place 44

Tkinter Event Handling See eventtest.py Inner functions Similar to Java's inner classes 45

Tkinter Event Handling See eventtesteach.py Common patterns, per Widget Generalizing... Three non-disjoint mechanisms 46

Tkinter Event Handling "Command" Mechanism For Button, Radiobutton, Checkbutton, Menu Define zero-arg callback function Assign callback function to Widget "command" property Similar to Java Swing "semantic" event handling 47

Tkinter Event Handling "Variable Object" Mechanism For Checkbutton, Radiobutton, Entry, Scale Define Tkinter variable object IntVar, DoubleVar, StringVar Assign Tkinter variable object to Widget variable property User affects Widget => affects variable Program affects variable => affects Widget No Java Swing equivalent 48

Tkinter Event Handling "Bind" Mechanism For any Widget Define callback function with event as arg Send bind() message to Widget object with event pattern and callback function as args Similar to Java Swing "low-level" event handling 49

Tkinter Event Patterns First argument to bind() specifies an event pattern '<MODIFIER-MODIFIER-TYPE-DETAIL>' MODIFIER: Control, Alt, Double, Triple, Button1, B1, Button2, B2, Button3, B3, Button4, B4, Button5, B5 M, Mod1, M1, Mod2, M2, Mod3, M3, Mod4, M4, Mod5, M5, Shift, Lock, Meta, TYPE: KeyPress, Key, KeyRelease, ButtonPress, Button, ButtonRelease, Motion, Enter, Leave, FocusIn, FocusOut, Destroy, MouseWheel, Activate, Map, Expose, Circulate, Property, Colormap, Gravity, Reparent, Configure, Unmap, Deactivate, Visibility DETAIL: For KeyPress, Key, KeyRelease: the Keysym For ButtonPress, Button, ButtonRelease: the button number 50

Tkinter Event Patterns Keysym a, b, 0, 1, F1, F2, Left, Right, Up, Down, End, Home, Insert, Print, Tab, Escape, Return, Caps_Lock, Num_Lock, Scroll_Lock space, less Button Number 1 (the left mouse button) 2 (the middle mouse button, or both mouse buttons) 3 (the right mouse button) 51

Tkinter Event Patterns widget.bind('<button>', f) Call f() when user clicks a mouse button widget.bind('<key>', f) Call f() when user types a key widget.bind('<double-button-1>', f) Call f() when user double clicks the left mouse button widget.bind('<control-key-a>', f) Call f() when user types Ctrl-a 52

Tkinter Event Handling See eventtestall.py Tkinter informs component objects of many events 53

A Tkinter Example See colordisplayer.py Slightly larger and more realistic Multiple interacting components 54

Getting More Information tux:~$ python >>> from Tkinter import * >>> from ScrolledText import * >>> help(toplevel) >>> help(widget) >>> help(button) >>> help(scrolledtext) >>> help(event)... 55

GUI Editorial Java's AWT/Swing library is welldocumented Python's Tkinter library is less so Avoid Tkinter for GUI applications? Avoid Python for GUI applications? 56

Summary We have covered: Graphical user interface (GUI) programming Specifically... For Java: The AWT/Swing GUI library For Python: The Tkinter GUI library 57

Summary For each: Interface structure Program structure Components Dialog Boxes Layout managers Event handling 58

Summary Not covered... Low-level drawing For Java: the Graphics2D class and the 2D library For Python: the Canvas class 59

Appendix 1: Graphical User Interfaces in C 60

GUIs in C For C/Unix/Linux... The X-Window GUI library X-Window server runs on local computer X-Window client runs on server computer See http://www.paulgriffiths.net/program/c/srcs/helloxsrc.html Use -lx11 option to build Explicit coding of event loop 61

GUIs in C Higher level GUI modules exist Especially... GTK+ See http://www.gtk.org/ 62

Appendix 2: Bad GUIs 63

Bad GUIs A few collected by Dr. Kernighan... 64

Bad GUIs 65

Bad GUIs 66

Bad GUIs 67

Bad GUIs 68

Bad GUIs 69

Bad GUIs 70

Bad GUIs 71

Bad GUIs See also... The "Interface Hall of Shame" http://homepage.mac.com/bradster/iarchitect/shame.htm 72