gui programming cs3283 - nus computingcs3283/2003-semesterii/... · 2004. 3. 22. · gui...
TRANSCRIPT
GUI ProgrammingCS3283
Hugh Anderson
CS3283 - Hugh Anderson’s notes.
Contact information
Room S15 #06-12Telephone 6874-6903E-mail [email protected]
CS3283 - Hugh Anderson’s notes. Page number: 1
BAD and GOOD
CS3283 - Hugh Anderson’s notes. Page number: 2
GUI definition
The use of pictures rather than just words to representthe input and output of a program.
A program with a GUI runs under some windowingsystem.
Original idea from research at SRI by Doug Engelbart.
CS3283 - Hugh Anderson’s notes. Page number: 3
GUI
Icons, buttons, dialogue/dialog boxes, windows on thescreen.
User controls by moving a pointer on the screen andselecting objects.
Though Apple Computer would like to claim theyinvented the GUI with their Macintosh operatingsystem, the concept originated in the early 1970s atXerox’s PARC laboratory.
CS3283 - Hugh Anderson’s notes. Page number: 4
Official description of CS3283
This module aims to teach the nuts and bolts of GUIprogramming. At the end of the course, students willacquire practical knowledge in Windows programmingand techniques of programming interactive systems.Topics include Windows programming, Motif, Tcl/Tkprogramming.
CS3283 - Hugh Anderson’s notes. Page number: 5
And...
✔ Graphical visualization
CS3283 - Hugh Anderson’s notes. Page number: 6
My expectation
✔ Read supporting papers, and
✔ maintain an active interest in GUI design andimplementation.
CS3283 - Hugh Anderson’s notes. Page number: 7
Assessment
Assessment Weighting Grade
Assignments 35%
Ass1 Group 10
Ass2 Individual 20
Ass3 Individual 40
Ass4 Group 30
Tutorials 5%
Mid-term Closed book 10%
Final Exam Open Book 50%
Total marks 100%
CS3283 - Hugh Anderson’s notes. Page number: 8
Readings...
1. My textbook, and
The User Interface Concepts & Design, Lon Barfield,Addison-Wesley (1993)
The JFC Swing Tutorial - A Guide to Constructing GUIs,Kathy Walrath & Mary Campione, Addison-Wesley (1999)
Tcl and the Tk Toolkit, John K. Ousterhout, Addison-Wesley(1994)
CS3283 - Hugh Anderson’s notes. Page number: 9
Coverage
Fundamental GUI concepts (1 lecture)
Design and programming techniques (3 lectures)
Cross platform GUI development (6 lectures)
Visualization techniques (2 lectures)
Enjoy the course!
CS3283 - Hugh Anderson’s notes. Page number: 10
Chapter 1
Module 1 - GUI concepts
CS3283 - Hugh Anderson’s notes. Page number: 11
GUI concepts
✔ Early user interfaces text based - fixed event ordering.
✔ GUI provides for complex interaction, and
✔ GUI relies on shared concepts or metaphors.
GUI programming is about the conceptualization, designand implementation of that part of a software applicationwhich is concerned with user interaction.
CS3283 - Hugh Anderson’s notes. Page number: 12
How not to do GUI
CS3283 - Hugh Anderson’s notes. Page number: 13
Two points
Try out your applications before delivering them.
Ensure that error messages are precise, and indicate thenext step.
CS3283 - Hugh Anderson’s notes. Page number: 14
How not to do GUI
CS3283 - Hugh Anderson’s notes. Page number: 15
General rules of GUI
Effective GUIs owe more to effective psychology than toeffective programming.
✔ Not just icons - includes an abstract view
✔ No clash between views
CS3283 - Hugh Anderson’s notes. Page number: 16
EZ-link
Clash between
• User view: pay afterwards
• Bus co view: pay first
CS3283 - Hugh Anderson’s notes. Page number: 17
Key points
Another key point is that humans are not equipped to handlemultiple things at one time, and this leads us to try to keepinterfaces simple and uncluttered.
Humans are particularly good at navigating systems whichhave some analogy to things they know - for example theuse of the desktop metaphor is well established and workswell in most cultures. Icons are also useful, but shouldn’t beabused.
CS3283 - Hugh Anderson’s notes. Page number: 18
Summary
Ensure correlation between What-u-c and What-u-think
KISS
Analogy, metaphor and icons
Always remember to include the U in GUI.
CS3283 - Hugh Anderson’s notes. Page number: 19
Do’s and don’ts
Do follow standards
Do be predictable and responsive
Do be flexible
Don’t forget the user
Don’t forget the machine/environment
Dont assume things
CS3283 - Hugh Anderson’s notes. Page number: 20
Types of applications
Not all applications benefit from a GUI - consider embeddedsystems
However, there are areas that do benefit from a GUI:
• Immersive applications
• Office and business applications
• Interactive control systems
CS3283 - Hugh Anderson’s notes. Page number: 21
And visualization ...
In addition, a newer application area involves the use ofvisualization to examine large data sets:
• Data mining: - delving into some set of data.
CS3283 - Hugh Anderson’s notes. Page number: 22
And WAP, PDA ...
Finally, there is the use of GUI in WAP enabled devices andon PDAs.
This is a specialist topic, which will not be covered in thiscourse.
CS3283 - Hugh Anderson’s notes. Page number: 23
MAC platform
CS3283 - Hugh Anderson’s notes. Page number: 24
MAC platform
CS3283 - Hugh Anderson’s notes. Page number: 25
MAC platform
CS3283 - Hugh Anderson’s notes. Page number: 26
X
The X window system1 is a sophisticated and welldeveloped system which allows for multimedia software andhardware components to be distributed around a network.
✔ At its simplest level, it allows a program and its display tobe on different computers.
1The system is called X, or the X window system. UNIX weenies insist that it is notcalled X-windows!
CS3283 - Hugh Anderson’s notes. Page number: 27
X architecture
The architectural view of X is a little peculiar. The designersview the display as central to the system, and the softwarerunning on the display is called the X-server:
Clients
X display (server)
CS3283 - Hugh Anderson’s notes. Page number: 28
Components of X
The X server
The X protocol
X clients
The Window manager(s)
The Display manager(s)
CS3283 - Hugh Anderson’s notes. Page number: 29
Display manager
CS3283 - Hugh Anderson’s notes. Page number: 30
Display manager
or
CS3283 - Hugh Anderson’s notes. Page number: 31
Window managers
or
CS3283 - Hugh Anderson’s notes. Page number: 32
Win32
✔ Win32 is the 32 bit successor of the Win16 API
✔ Win32 is a generic name for 4 (slightly) different APIs
✔ The Win32 API on Win95 is a subset of those on WinNT,so applications written for Win95 should be portable toWinNT.
CS3283 - Hugh Anderson’s notes. Page number: 33
Using Win32
✔ The normal way for you to access Win32 functions is byusing a precompiled library from a C program.
✔ C programmers include a set of header files, andapplications link at run time to the Win32 DLLs.
CS3283 - Hugh Anderson’s notes. Page number: 34
API for Win9X
Has three sections:
KERNEL: - the low level kernel services in kernel32.dll.
GDI: - Graphics Device Interface - drawing and printing ingdi32.dll.
USER: - User Interface controls, windows and messagingservices in user32.dll.
CS3283 - Hugh Anderson’s notes. Page number: 35
Non-native platforms
The following systems can be used to provide a consistentenvironment that is independant of the host operatingsystems:
Java/Swing
Web browser interfaces
Thin client systems
CS3283 - Hugh Anderson’s notes. Page number: 36
Java
Sun Microsystem’s development of Java has always beendone with portability issues in mind.
It is relatively easy to write a portable application - fordelivery either as an applet in a web page, or as astandalone application.
The swing windowing toolkit is the Java API for GUIdevelopment.
CS3283 - Hugh Anderson’s notes. Page number: 37
Java app
CS3283 - Hugh Anderson’s notes. Page number: 38
Web browser interfaces
✔ The first web servers provided static pages of hypertextand images.
✔ Demand led to the specification of a standard for activepage generation - CGI
CS3283 - Hugh Anderson’s notes. Page number: 39
CGI
✔ CGI specifies how to pass arguments to a program on aserver as part of the HTTP request.
✔ The program might then look up a database beforegenerating some HTML to pass back to the browser.
✔ A CGI program can be any program which can acceptcommand line arguments
✔ Perl is a common choice for writing these programs.
CS3283 - Hugh Anderson’s notes. Page number: 40
Warning
✘ You should be aware that poorly constructed CGI scriptscan result in security problems for the server, and
✘ there is normally a process overhead for each scriptstarted.
CS3283 - Hugh Anderson’s notes. Page number: 41
Other web interfaces
Java applets, to allow processing at the browser,
PHP (a server-side, cross-platform, HTML-embeddedscripting language), or
ASP (a scripting environment for Microsoft InternetInformation Server in which you can combine HTML, scriptsand reusable ActiveX server components).
CS3283 - Hugh Anderson’s notes. Page number: 42
Thin client systems
CS3283 - Hugh Anderson’s notes. Page number: 43
Widget sets
[possibly evoking “window gadget”] In graphical userinterfaces, a combination of a graphic symbol andsome program code to perform a specific function.E.g. a scroll-bar or button. Windowing systemsusually provide widget libraries (sets) containingcommonly used widgets drawn in a certain style andwith consistent behaviour.
When we use different widget sets, our applications have aslightly different look-and-feel.
CS3283 - Hugh Anderson’s notes. Page number: 44
Motif application
CS3283 - Hugh Anderson’s notes. Page number: 45
Athena application
CS3283 - Hugh Anderson’s notes. Page number: 46
Widgets as components
The ICS widget databook has a series of useful widgets toextend the basic Motif set, including ones for bar graphs andso on.
CS3283 - Hugh Anderson’s notes. Page number: 47
Summary of topics
In this module, we introduced the following topics:
Rules of GUI
Types of applications
Windowing/GUI environments
Widgets
CS3283 - Hugh Anderson’s notes. Page number: 48
Chapter 2
Module 2 - Design
CS3283 - Hugh Anderson’s notes. Page number: 49
Some fun
CS3283 - Hugh Anderson’s notes. Page number: 50
General issues of design
✔ Must design large things
✔ Design approaches an art form
✔ Principal concern with user
CS3283 - Hugh Anderson’s notes. Page number: 51
How not to design
CS3283 - Hugh Anderson’s notes. Page number: 52
Rules
Avoid doing things just because you know how to do them.
Make your designs be driven by requirements.
CS3283 - Hugh Anderson’s notes. Page number: 53
The design process
The design process involves both
specification of the behaviour of a product, and
specification of the detailed techniques used to implementthe product.
In each area, there exist a range of tools and techniquesthat can benefit any software product.
CS3283 - Hugh Anderson’s notes. Page number: 54
Role of designer
✔ Designer interacts with people
✔ Must relate designs back to requirements and constraints.
✔ Design must be readable, understandable, implementable.
✔ Designer uses abstraction.
CS3283 - Hugh Anderson’s notes. Page number: 55
Iconic abstraction
Text file using an icon:
CS3283 - Hugh Anderson’s notes. Page number: 56
Higher level abstractions
✔ Desktop
✔ Wastebasket
CS3283 - Hugh Anderson’s notes. Page number: 57
Building blocks
Button Testbox Label
CS3283 - Hugh Anderson’s notes. Page number: 58
Building blocks
Menu Checkbox Radiobutton
CS3283 - Hugh Anderson’s notes. Page number: 59
Building blocks
Scrollbar Graph Directory Tree
CS3283 - Hugh Anderson’s notes. Page number: 60
Containers
CS3283 - Hugh Anderson’s notes. Page number: 61
Sundries
✔ Cursors
✔ Fonts
✔ Colours
✔ Drag-n-drop
✔ Cut-n-paste.
CS3283 - Hugh Anderson’s notes. Page number: 62
Use cases
Designer imagines and proposes common scenarios2, and
checks to see if the scenarios are consistent, and complete,
tries out the scenarios on people to see if they work,
tests the scenarios and attempts to quantify their behaviour.
2Scenarios=Use cases. Use cases=scenarios.
CS3283 - Hugh Anderson’s notes. Page number: 63
F&R state diagram
SpecifyPattern Change
Specify
Doit!
Enter
Escape
Cancel
Escape
Enter
Enter
CS3283 - Hugh Anderson’s notes. Page number: 64
GUI-style find-and-replace :
CS3283 - Hugh Anderson’s notes. Page number: 65
State diagram
Idle
ChangeSpecified
PatternspecifiedSpecified
Do change
Patternspecified
Change
unspecunspec
unspec
unspec
spec
spec
unspec
spec
unspec
spec
Doit
Cancel
Cancel
Doit
CS3283 - Hugh Anderson’s notes. Page number: 66
Therac25
The focus on detail related to the state of a dialog is nottrivial.
✔ There is a well known example of a poorly constructeddialog, that contributed to the death of cancer patients inthe US
http://sunnyday.mit.edu/therac-25.html
CS3283 - Hugh Anderson’s notes. Page number: 67
Modelling
Modelling: - Used to demonstrate the UI, without actuallyimplementing the core software.
Dan Bricklen’s demo program (a demo copy is available athttp://www.brickin.com/) is worth looking at for modelling a userinterface. There is an amusing demo called chiapaint .
CS3283 - Hugh Anderson’s notes. Page number: 68
Chiapaint
CS3283 - Hugh Anderson’s notes. Page number: 69
Modelling
It is also relatively easy to model a new UI using Tcl/Tk.
CS3283 - Hugh Anderson’s notes. Page number: 70
OO technology
The principle features of OO technology are as follows:
Abstraction,
Information hiding,
Inheritance,
Polymorphism, and
Genericity
CS3283 - Hugh Anderson’s notes. Page number: 71
OO technology and design
Some of these OO features provide a mechanism whichsupports the construction of better software...
✔ Create library
✔ Generalize it
✔ Design becomes the detailing of new classes derivedfrom the generalized ones...
CS3283 - Hugh Anderson’s notes. Page number: 72
GUI design
GUI design has to meld four possibly conflicting elements:
Software model - structure of data and software
User profile - the types of users
Product perception - the mental image developed by user
Product image - the GUI - screenshots, descriptions orspecifications
In general, a GUI is successful when the product perceptionmatches the product image.
CS3283 - Hugh Anderson’s notes. Page number: 73
GUI specification/design
Our concern is to:
Develop a functional and behavioural responsespecification in terms of its cognitive aspects.
The functional and behavioural response specification isturned inside-out from a normal software specification. Witha software behavioural model, we start with an analysis ofstates, events and actions, and specify the expected viewsas a result. With GUI specification, our orientation is to startwith the views, and specify the states, events and actionsassociated with those views.
CS3283 - Hugh Anderson’s notes. Page number: 74
Basis for GUI design
One of the most characteristic elements of manyGUI programs is the use of the event-driven softwarearchitecture.
When the designer adopts this paradigm, the GUI programis viewed as a series of response routines for particularevents.
CS3283 - Hugh Anderson’s notes. Page number: 75
Design document
User requirement
Environment
Software constraints
Other constraints
Interface design
Overview
Interface description
Prototype screens
Functional specifications
Behavioural specifications
Testing methodology
CS3283 - Hugh Anderson’s notes. Page number: 76
Formal GUI design
✔ Z can formally specify complex GUI interactions.
✔ Z tools test the specification
More details may be found in the handout, found at
http://www.cs.virginia.edu/˜jck/publications/zum.97.pdf
It describes the interface to a nuclear reactor.
CS3283 - Hugh Anderson’s notes. Page number: 77
GUI designs
✔ With Therac-25, we saw how a poorly constructedinterface led to deaths of patients...
✔ By contrast, a good interface may result in the reverse...
CS3283 - Hugh Anderson’s notes. Page number: 78
Examples of GUI designs
Here are some examples of different designs for similarthings
CS3283 - Hugh Anderson’s notes. Page number: 79
Lyx Find-and-replace:
CS3283 - Hugh Anderson’s notes. Page number: 80
Nedit find-and-replace
CS3283 - Hugh Anderson’s notes. Page number: 81
Word find-and-replace
CS3283 - Hugh Anderson’s notes. Page number: 82
Win98 file manager
CS3283 - Hugh Anderson’s notes. Page number: 83
KDE file manager
CS3283 - Hugh Anderson’s notes. Page number: 84
FSN
CS3283 - Hugh Anderson’s notes. Page number: 85
Vizualization design
Visualization design has a similar structure to GUI design -a difference being the focus on the use of analogy.
CS3283 - Hugh Anderson’s notes. Page number: 86
Basis for visualization design
Eick proposes the following guidelines:
1. Focus the visualization on task-specific user needs.
2. Use a whole-database overview display.
3. Encode the data using colour, shape, size, position.
4. Use drill-down, filters and multiple linked views
5. Use smooth animation for time
CS3283 - Hugh Anderson’s notes. Page number: 87
Visualization document
User requirement
Environment
Software constraints
Other constraints
Interface design
Overview
Interface description
Drill-down and other displays
Encoding
Testing methodologies
CS3283 - Hugh Anderson’s notes. Page number: 88
Examples of visualization
There are many examples of data visualizations, and I havejust taken some from the world of network management- starting from simple graphical displays through to 3Dimages.
CS3283 - Hugh Anderson’s notes. Page number: 89
Graphs and diagramming
CS3283 - Hugh Anderson’s notes. Page number: 90
Compact visualization
CS3283 - Hugh Anderson’s notes. Page number: 91
3D graph
CS3283 - Hugh Anderson’s notes. Page number: 92
Abstract 3D view - SeeNet
eickrab eick
> <
Half Lines
Both Active
Show Nodes
Outside OK
Help
All On
All Off
Zoom
Unzoom
Variables--> <--weights 35
-21
2956
84111
20.00 111.00weights
Short
Long
Thin
Wide
THYST-L
TheDailyQuote
XspcDlv
ballman
bdewbank
bld
blewett
ches
cope
dep
dla
dorene
ees
eick
em1
express
exptools
gen
hartmanhastings
info-hol-request
jcr
johnson
kss
kwc
laddlas
lda
maa
mckinzie
mferber
ni-fwd
north
otto
pkohorn
postmaster
rab
ralph
root
sml-redistribution-request
steffen
techlibtelevi
tmd
tuckey
uucp
votta
wth
ycw
CS3283 - Hugh Anderson’s notes. Page number: 93
Abstract 3D view - Flodar
CS3283 - Hugh Anderson’s notes. Page number: 94
3D world-view
CS3283 - Hugh Anderson’s notes. Page number: 95
Summary of topics
In this module, we introduced the following topics:
The designer’s mindset
Specification and design, tools and methods
Examples of successful designs
CS3283 - Hugh Anderson’s notes. Page number: 96
Chapter 3
Architecture
CS3283 - Hugh Anderson’s notes. Page number: 97
Assignment
• Up to 3/group
• 3% of assignment mark/about 12% of final
• Development of a design/analysis document , withmodelling
CS3283 - Hugh Anderson’s notes. Page number: 98
Your task...
✔ System with a GUI interface
✔ Help track disease
✔ View patient histories✔ Select by region✔ + other functions
✔ Design, not implement.
CS3283 - Hugh Anderson’s notes. Page number: 99
Submission
✔ Description of system architecture
✔ GUI design/analysis document concerned with theGUI interface.
CS3283 - Hugh Anderson’s notes. Page number: 100
Deliverables
A title page
Table of contents...
Introduction - non-technical
System architecture with justifications
GUI design/analysis document
CS3283 - Hugh Anderson’s notes. Page number: 101
Design/analysis document
Follow suggested structure?
User requirement, user profile, environment
Overview of the GUI interface
Description of the interface
Prototype screens
Functional spec
Behavioural spec
Justifications - relating back to user requirement.
A testing methodology
CS3283 - Hugh Anderson’s notes. Page number: 102
Design/analysis document
Note that this assignment does not require you to implementthe application, just to design one, and to model the designwith prototype screens
You could use Java/Visual Basic/ a graphics editor...anything as long as you show screenshots.
CS3283 - Hugh Anderson’s notes. Page number: 103
Assessment
The assessment will be graded with the followingweightings:
Introduction 10%System architecture 25%GUI design 50%Extra 15%
CS3283 - Hugh Anderson’s notes. Page number: 104
Assessment
• The “Extra” component of the assessment is forsubmissions which show clear evidence of extrathought or care.
• In evaluating the “GUI design” component, I will alsobe looking for “justifications you can make for designdecisions”.
Try to achieve clarity in your writing and take care in thestructuring of the document.
CS3283 - Hugh Anderson’s notes. Page number: 105
Architecture
✔ GUI applications can be BIG
✔ Hence concern with architecture
CS3283 - Hugh Anderson’s notes. Page number: 106
Architecture
Standalone
Shared file
Shared database
Web based
Simple
Scripting
Java
CS3283 - Hugh Anderson’s notes. Page number: 107
Web architecture
✔ Common to deliver applications via web browsers.
✔ MSIE/Navigator/iCab/Opera.. different in implementation.
CS3283 - Hugh Anderson’s notes. Page number: 108
Standalone
High
Disk
SpeedHigh
Disk
Speed
CS3283 - Hugh Anderson’s notes. Page number: 109
Shared file
FileServer High
Disk
Speed
CS3283 - Hugh Anderson’s notes. Page number: 110
Shared database
DatabaseServer High
Disk
Speed
CS3283 - Hugh Anderson’s notes. Page number: 111
Web server
Web Browser Web Browser
WebServer
CS3283 - Hugh Anderson’s notes. Page number: 112
Active scripting
Web Browser Web Browser
WebServer PHP
CGIHigh
Disk
Speed
CS3283 - Hugh Anderson’s notes. Page number: 113
Java applet
An even more complex GUI application might beconstructed using a series of interlinked web pagescontaining Java applets. The advantage of this, is two fold.
The processing load on the web server may be reduced .
The Java applet can directly3 communicate with a databaseserver.
3Note that there are some security concerns here.
CS3283 - Hugh Anderson’s notes. Page number: 114
Java applet
Web Browser+ Java applet
WebServer
DatabaseServer High
Disk
Speed
CS3283 - Hugh Anderson’s notes. Page number: 115
Chapter 4
First steps
CS3283 - Hugh Anderson’s notes. Page number: 116
GUI programming
In elementary programming styles, there is a single thread-of-control
✔ GUI programs respond to events
✔ Restructuring programs as a group of callbacks .
CS3283 - Hugh Anderson’s notes. Page number: 117
GUI mainline
#include <any GUI header files needed> int main () { RegisterAllCallbacks (); LoopForever (); }
CODE LISTING GUICode.c
CS3283 - Hugh Anderson’s notes. Page number: 118
How not to ...
Don’t do it the hard way!
CS3283 - Hugh Anderson’s notes. Page number: 119
X API
CS3283 - Hugh Anderson’s notes. Page number: 120
X source
#include <stdio.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/Paned.h> #include <X11/Xaw/Label.h> void quit_callback (widget, client_data, call_data) Widget widget; caddr_t client_data; caddr_t call_data; { exit (0); } main (argc, argv) int argc; char *argv[]; { /* main */ Widget parent; Arg args[20]; int n; Widget pane_widget, quit_widget; Widget label_widget; /* Set up top−level shell widget */ parent = XtInitialize (argv[0], "Xaw1", NULL, 0, &argc, argv); /* Set up pane to control whole application */ n = 0; pane_widget = XtCreateManagedWidget ("pane", panedWidgetClass, parent, args, n); /* Set up command widget to act as a push button */ n = 0; quit_widget = XtCreateManagedWidget ("quit", commandWidgetClass, pane_widget, args, n); /* Set up a callback function */ XtAddCallback (quit_widget, XtNcallback, quit_callback, (caddr_t) NULL); /* Set up label widget */ n = 0; XtSetArg (args[n], XtNlabel, "This is a label."); n++; label_widget = XtCreateManagedWidget ("label", labelWidgetClass, pane_widget, args, n); /* Map widgets and handle events */ XtRealizeWidget (parent); XtMainLoop (); }
CODE LISTING xaw1.c
CS3283 - Hugh Anderson’s notes. Page number: 121
X compilation
gcc -o xaw1 xaw1.c -lXt -lXaw
CS3283 - Hugh Anderson’s notes. Page number: 122
Win32 API
#include <windows.h> int STDCALL WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow) { MessageBox (NULL, "Hello, Windows!", "Hello", MB_OK); return 0; }
CODE LISTING SimpleWin32.c
CS3283 - Hugh Anderson’s notes. Page number: 123
Win32 compilation
gcc -oSimpleWin32 SimpleWin32.c -mwindows
CS3283 - Hugh Anderson’s notes. Page number: 124
Win32 application
CS3283 - Hugh Anderson’s notes. Page number: 125
Win32 application
#include <windows.h> #include <string.h> int STDCALL WinMain (HINSTANCE hInst, HINSTANCE hPrev, LPSTR lpCmd, int nShow) { HWND hwndMain; /* Handle for the main window. */ MSG msg; /* A Win32 message structure. */ WNDCLASSEX wndclass; /* A window class structure. */ char *szMainWndClass = "WinTestWin"; memset (&wndclass, 0, sizeof (WNDCLASSEX)); wndclass.lpszClassName = szMainWndClass; wndclass.cbSize = sizeof (WNDCLASSEX); wndclass.style = CS_HREDRAW | CS_VREDRAW; wndclass.lpfnWndProc = MainWndProc; wndclass.hInstance = hInst; wndclass.hIcon = LoadIcon (NULL, IDI_APPLICATION); wndclass.hIconSm = LoadIcon (NULL, IDI_APPLICATION); wndclass.hCursor = LoadCursor (NULL, IDC_ARROW); wndclass.hbrBackground = (HBRUSH) GetStockObject (WHITE_BRUSH); RegisterClassEx (&wndclass); hwndMain = CreateWindow (szMainWndClass, "Hello", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, NULL, NULL, hInst, NULL); ShowWindow (hwndMain, nShow); UpdateWindow (hwndMain); while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); } return msg.wParam; }
CODE LISTING BiggerWin.c
CS3283 - Hugh Anderson’s notes. Page number: 126
Win32 application
The full source code and a makefile is available athttp://www.comp.nus.edu.sg/˜cs3283/ftp/generic.tgz.
CS3283 - Hugh Anderson’s notes. Page number: 127
Win32 application
CS3283 - Hugh Anderson’s notes. Page number: 128
Win32 programming
Interesting tutorial at http://www.winprog.org/tutorial.
CS3283 - Hugh Anderson’s notes. Page number: 129
OO GUI toolkits
No one object-oriented standard for GUI applications
CS3283 - Hugh Anderson’s notes. Page number: 130
Event handling
Quit
Frame Button
CS3283 - Hugh Anderson’s notes. Page number: 131
GTK+
✔ GTK+ is a multi-platform toolkit
✔ By using CygWin GTK+ works on Win32.
✔ GTK+ is free software and part of the GNU Project.
CS3283 - Hugh Anderson’s notes. Page number: 132
GTK+
GTK+ has an object-oriented architecture with componentlibraries:
GDK - A wrapper for low-level windowing functions.
GTK - An advanced widget set.
CS3283 - Hugh Anderson’s notes. Page number: 133
Glade
CS3283 - Hugh Anderson’s notes. Page number: 134
Glade application
CS3283 - Hugh Anderson’s notes. Page number: 135
MFC
✔ OO toolkit to access Win32
✔ DLL contains code for MFC
✔ Linked at runtime.
✔ Base class CObject
CS3283 - Hugh Anderson’s notes. Page number: 136
Notation
One characteristic of MFC programs is the use of Hungarian(prefix) notation for variable names. It is common to seeMFC program variables prefixed with type identifiers. Forexample:
dLocalMax is a double variable
iLocalMin is an integer variable.
CS3283 - Hugh Anderson’s notes. Page number: 137
Java/Swing
✔ Originally the graphical toolkit for Java was AWT, theAbstract Windowing Toolkit.
✔ It is fairly primitive, and the new Swing toolkit providesmuch more functionality.
✔ AWT is native code, with a Java API, but Swing isimplemented on-top-of AWT.
CS3283 - Hugh Anderson’s notes. Page number: 138
Swing
✔ Swing components inherit from java.awt.component , andthe Swing classes that are similar to AWT classes areprefixed with the letter “J”.
✔ For example, the AWT Button class is renamed JButton .
✔ You can mix-and-match AWT and Swing components.
CS3283 - Hugh Anderson’s notes. Page number: 139
Swing
Java/Swing may be used in two distinct ways:
Producing a standalone application.
Producing an applet to run within a web browser.
One of the features of Swing is that it implements apluggable look-and-feel.
The look-and-feel can even be changed dynamically.
CS3283 - Hugh Anderson’s notes. Page number: 140
Web interfaces
Categories:
Server-side dynamic pages
Server-side scripting
Client-side scripting
Client-side applets
We will look at some of these methods later in the course.
CS3283 - Hugh Anderson’s notes. Page number: 141
Scripting languages
✔ Scripting languages which can produce GUI interfacesare relatively easy to use.
✔ An effective strategy for building GUI applications is towrite the GUI part in a scripting language, and to writethe core ’difficult’ part in C.
CS3283 - Hugh Anderson’s notes. Page number: 142
Summary of topics
In this module, we introduced the following topics:
Programming styles to avoid
Event driven architectures
OO toolkits
Web-based systems
Scripting languages
CS3283 - Hugh Anderson’s notes. Page number: 143
Further study
http://www.public.asu.edu/~tobiazz/papers/thesis/local/gui toolkit list.html
CS3283 - Hugh Anderson’s notes. Page number: 144
Chapter 5
Tcl/Tk - 1
CS3283 - Hugh Anderson’s notes. Page number: 145
Environment
✔ X - from UNIX/sunfire
✔ Cygwin - download ~cs3283/ftp/full.exe (OLD)
✔ Native - download www.scriptics.com
CS3283 - Hugh Anderson’s notes. Page number: 146
Installing Tcl/Tk
✔ If you are using cygwin-b20 , the wish interpreter is calledcygwish80.exe .
✔ Find cygwish80.exe .
✔ Copy and call it wish8.0.exe for UNIX compatibility.
CS3283 - Hugh Anderson’s notes. Page number: 147
Installing Tcl/Tk
✔ In the first line of your tcl files, you should put#!/bin/wish8.0
CS3283 - Hugh Anderson’s notes. Page number: 148
Tcl/Tk demos
✔ If you download the file ~cs3283/ftp/demos.tar and extractit, you will have a series of Tcl/Tk widget examples in~/Demos .
✔ Change into the directory ~/Demos , and type ./widget .
CS3283 - Hugh Anderson’s notes. Page number: 149
Tcl/Tk tutor
✔ There is a Tcl/Tk tutor, and many learn-to-program-Tcl/Tk documents available at many sites on the Internet- if you continue to have trouble, you may wish to trythem.
CS3283 - Hugh Anderson’s notes. Page number: 150
Tcl/Tk
✔ Tcl (Tool Command Language) is an interpreted scriptinglanguage
✔ Pronounced ’tickle’.
✔ Tk - X-window toolkit
✔ Wish - the windowing shell
CS3283 - Hugh Anderson’s notes. Page number: 151
Scripting language
✔ Difficult to define.
✔ Job control languages ...
✔ More powerful basic operations
✔ Regular-expression pattern matching
CS3283 - Hugh Anderson’s notes. Page number: 152
Scripting
✔ Normally interpreted
✔ One line equivalent to 100 lines of C.
✔ Overhead
Perl in web page developments, Tcl/Tk for GUI development
CS3283 - Hugh Anderson’s notes. Page number: 153
How not to!
Don’t use to the exclusion of other languages!
✔ Good and bad
✔ Array lookup ..
✔ Common to mix scripting and other languages.
CS3283 - Hugh Anderson’s notes. Page number: 154
Xspin
CS3283 - Hugh Anderson’s notes. Page number: 155
Hello world
manu> wishwish> button .quit -text "Hello World!" -command {exit}.quitwish> pack .quitwish>
CS3283 - Hugh Anderson’s notes. Page number: 156
In a script
#!/usr/local/bin/wish8.1 −f
button .quit −text " Hello World!" −command { exit} pack .quit
CODE LISTING HelloWorld.tcl
CS3283 - Hugh Anderson’s notes. Page number: 157
Run it
CS3283 - Hugh Anderson’s notes. Page number: 158
Tcl first...then Tk
CS3283 - Hugh Anderson’s notes. Page number: 159
Tcl structure
✔ Tiny syntax
✔ Single command structure
✔ Set of rules
✔ All PROGRAM structures are implemented as commands.
✔ Level’ of the GUI interface is quite high.
CS3283 - Hugh Anderson’s notes. Page number: 160
Comments
If the first character of a command is #, it is a comment.
CS3283 - Hugh Anderson’s notes. Page number: 161
Commands
Tcl commands are just words separated by spaces.Commands return strings, and arguments are just furtherwords.
command argument argumentcommand argument
Tcl commands are separated by a new line, or a semicolon,and arrays are indexed by text:
set a(a\ text\ index) 4
CS3283 - Hugh Anderson’s notes. Page number: 162
Command examples
Procedures File Access Miscellaneous
proc name {params} {body} open <name> source <NameOfFile>
read <fileID> global <varname>
close <fileID> catch <command>
cd <directoryname> format <fmtstrng> <val>
exec <process>
return <value>
CS3283 - Hugh Anderson’s notes. Page number: 163
Spaces
Spaces are important:
expr 5*3 has a single argumentexpr 5 * 3 has three arguments
CS3283 - Hugh Anderson’s notes. Page number: 164
Tcl/Tk quoting rules
When the " or { character are first in the word.
".." disables a few of the special characters - for examplespace, tab, newline and semicolon, and
{..} disables everything except \{, \} and \nl.
CS3283 - Hugh Anderson’s notes. Page number: 165
Control structures
End up looking very like ’C’:
while {a==10} {set b [tst a]
}
CS3283 - Hugh Anderson’s notes. Page number: 166
Command
The []’s are replaced by the value returned by executing theTcl command ’doit’.
set a [doit param1 param2]
CS3283 - Hugh Anderson’s notes. Page number: 167
Variable substitution
The dollar sign performs the variable value substitution. Tclvariables are strings.
set a 12b a will be "12b"set b 12$a b will be "1212b"
CS3283 - Hugh Anderson’s notes. Page number: 168
Backslash
set a a\ string\ with\ spaces\ \and\ a\ new\ line
CS3283 - Hugh Anderson’s notes. Page number: 169
tclsh or wish?
✔ tclsh - a shell-like application that reads Tcl commandsfrom its standard input or from a file and evaluates them.
✔ wish - the Tcl command language, the Tk toolkit, and amain program that reads commands from standard inputor from a file.
CS3283 - Hugh Anderson’s notes. Page number: 170
Assignment
% set a 11% set a1% set a 22% set a2
CS3283 - Hugh Anderson’s notes. Page number: 171
Assignment
% set a alhabetapruningalhabetapruning% set aalhabetapruning% set a alpha\ beta\ pruningalpha beta pruning% set aalpha beta pruning
CS3283 - Hugh Anderson’s notes. Page number: 172
Assignment
% set a alhabetapruningalhabetapruning% set aalhabetapruning% set a alpha\ beta\ pruningalpha beta pruning% set aalpha beta pruning
(Backslash substitution)
CS3283 - Hugh Anderson’s notes. Page number: 173
Assignment
% set a {alhabetapruning}....% set aalphabetapruning
CS3283 - Hugh Anderson’s notes. Page number: 174
Assignment
% set a 22/322/3% set a22/3
CS3283 - Hugh Anderson’s notes. Page number: 175
Assignment
% set a expr 22/3wrong # args: should be "set varName ?newValue?"
% set a {expr 12/4.2}expr 12/4.2% set a [expr 12.2/33]0.369696969697% set a0.369696969697
(Command substitution)
CS3283 - Hugh Anderson’s notes. Page number: 176
Assignment
% set a0.369696969697% set a [expr $a*33]12.2
(Variable and Command substitution)
CS3283 - Hugh Anderson’s notes. Page number: 177
Assignment
% expr 1+2+36% expr 1 + 2+36
CS3283 - Hugh Anderson’s notes. Page number: 178
Assignment - increment
% set a 1010% incr a11% set a11
CS3283 - Hugh Anderson’s notes. Page number: 179
Assignment
% set g gallongallon% set gallons $gscan’t read "gs": no such variable% set gallons ${g}sgallons
(Variable substitution)
CS3283 - Hugh Anderson’s notes. Page number: 180
Assignment - append
% set a ${a}22211222% append a 33311222333
CS3283 - Hugh Anderson’s notes. Page number: 181
Tcl/Tk list
Just a sequence of words:
% set dow {Mon Tue Wed Thu Fri Party Sun}Mon Tue Wed Thu Fri Party Sun% lindex $dow 3Thu%lindex $dow 1Tue
CS3283 - Hugh Anderson’s notes. Page number: 182
Lists within lists
% set a {0 1 {2 x} {3 x y} 4}0 1 {2 x} {3 x y} 4% lindex $a 33 x y
CS3283 - Hugh Anderson’s notes. Page number: 183
Iteration over list
% foreach day $dow {puts Day\ of\ week\ is\ $day
}Day of week is MonDay of week is TueDay of week is WedDay of week is ThuDay of week is FriDay of week is PartyDay of week is Sun
CS3283 - Hugh Anderson’s notes. Page number: 184
Arrays
% set work(Mon) 88% set work(Tue) 1010% foreach day $dow {
puts $day\ I\ worked\ $work($day)hrs}
Mon I worked 8hrsTue I worked 10hrscan’t read "work(Wed)": no such element in array
CS3283 - Hugh Anderson’s notes. Page number: 185
Arrays
% array size work2% array names workTue Mon
CS3283 - Hugh Anderson’s notes. Page number: 186
Summary
✔ Tcl
✔ commands✔ quoting and substitutions✔ assignment (set)✔ Lists and arrays
CS3283 - Hugh Anderson’s notes. Page number: 187
Chapter 6
Tcl/Tk - 2
CS3283 - Hugh Anderson’s notes. Page number: 188
Summary
✔ Tcl
✔ commands✔ quoting and substitutions✔ assignment (set)✔ Lists and arrays
CS3283 - Hugh Anderson’s notes. Page number: 189
Tcl/Tk list - recap
Just a sequence of words:
% set dow {Mon Tue Wed Thu Fri Party Sun}Mon Tue Wed Thu Fri Party Sun% lindex $dow 3Thu%lindex $dow 1Tue
CS3283 - Hugh Anderson’s notes. Page number: 190
Lists within lists - recap
% set a {0 1 {2 x} {3 x y} 4}0 1 {2 x} {3 x y} 4% lindex $a 33 x y
CS3283 - Hugh Anderson’s notes. Page number: 191
Iteration over list - recap
% foreach day $dow {puts Day\ of\ week\ is\ $day
}Day of week is MonDay of week is TueDay of week is WedDay of week is ThuDay of week is FriDay of week is PartyDay of week is Sun
CS3283 - Hugh Anderson’s notes. Page number: 192
List operators
sort ?options? <list>split <string> ?splitcharacters?concat <list> <list>lindex <list> <index>... + lots more
CS3283 - Hugh Anderson’s notes. Page number: 193
Sorting a list
% lsort $dowFri Mon Party Sun Thu Tue Wed
CS3283 - Hugh Anderson’s notes. Page number: 194
Split (string to list)
% split "/usr/local/bin/tclsh" /{} usr local bin tclsh
% join {{} usr local bin} //usr/local/bin
CS3283 - Hugh Anderson’s notes. Page number: 195
Arrays - recap
% set work(Mon) 88% set work(Tue) 1010% foreach day $dow {
puts $day\ I\ worked\ $work($day)hrs}
Mon I worked 8hrsTue I worked 10hrscan’t read "work(Wed)": no such element in array
CS3283 - Hugh Anderson’s notes. Page number: 196
Arrays - recap
% array size work2% array names workTue Mon
CS3283 - Hugh Anderson’s notes. Page number: 197
Multidimensional arrays
% set lect(Mon,8-10) cs2106cs2106% set lect(Mon, 8-10) cs2106wrong # args: should be "set varName ?newValue?"
CS3283 - Hugh Anderson’s notes. Page number: 198
if then else
% if {3==3} {puts hi}hi% if {3==4} {puts hi}% if {3 == 3} {puts hi}hi% if {"help" == "help"} {puts hi}hi
CS3283 - Hugh Anderson’s notes. Page number: 199
while
% set c 33% while {$c>=0} {
puts "c is $c"set c [expr $c-1]
}c is 3c is 2c is 1c is 0
CS3283 - Hugh Anderson’s notes. Page number: 200
foreach
% foreach day $dow {puts $day\ I\ worked\ $work($day)hrs
}Mon I worked 8hrsTue I worked 10hrs...
CS3283 - Hugh Anderson’s notes. Page number: 201
Control - summary
if {test} {thenpart} {elsepart}while {test} {body}for {init} {test} {incr} {body}continueswitch $x {a {a-part} b {b-part}... }
CS3283 - Hugh Anderson’s notes. Page number: 202
Procedures
% proc fac x {if {$x<=1} {return 1}expr $x * [fac [expr $x-1]]
}% fac 424
CS3283 - Hugh Anderson’s notes. Page number: 203
Globals
% proc printerrorno {global errnoputs “The error is $errno”
}
CS3283 - Hugh Anderson’s notes. Page number: 204
Parameter passing
✔ By value
✔ i.e. not arrays
CS3283 - Hugh Anderson’s notes. Page number: 205
Parameter passing
% set arr(1) 10% set arr(2) 20% proc prnt ar {
puts $ar(1)puts $ar(2)
}% prnt arrcan’t read "ar(1)": no such variable
CS3283 - Hugh Anderson’s notes. Page number: 206
Parameter passing
% proc prnt ar {upvar $ar arraputs $arra(1)puts $arra(2)
}% prnt arr10100
CS3283 - Hugh Anderson’s notes. Page number: 207
Parameter passing
% proc prnt ar {upvar $ar arraset i 1while {$i<=[array size arra]} {
puts $arra($i)incr i
}}
% prnt arr1020
CS3283 - Hugh Anderson’s notes. Page number: 208
End of Tcl, Start of Tk
CS3283 - Hugh Anderson’s notes. Page number: 209
Widget creation commands
First parameter is a ’dotted’ name.
% label <name> -optional parameter pairs ...% canvas <name> -optional parameter pairs ...% button <name> -optional parameter pairs ...% frame <name> -optional parameter pairs ...% ... and so on
The dot heirarchy indicates the relationships between thewidgets.
CS3283 - Hugh Anderson’s notes. Page number: 210
New widget commands
When you create a widget ".b", a new command ".b" iscreated, which you can use to further communicate with it.
The geometry managers in Tk assemble the widgets:
% pack <name> .... where ....
CS3283 - Hugh Anderson’s notes. Page number: 211
Widget becomes command
canvas .cpack .cbutton .q -text Quit -command {exit}pack .q.q configure -foreground blue.q configure -background red
CS3283 - Hugh Anderson’s notes. Page number: 212
Example 2
foreach r {raised sunken flat groove ridge} {frame .$r -width 15m -height 10m -relief $r -
borderwidth 8pack .$r -side left -padx 2m -pady 2m
}.flat configure -background blue. configure -background gray
CS3283 - Hugh Anderson’s notes. Page number: 213
Example 2
CS3283 - Hugh Anderson’s notes. Page number: 214
Example 3
radiobutton .cs2105 -text CS2105 -variable course -value CS2105 -anchor wradiobutton .cs2106 -text CS2106 -variable course -value CS2106 -anchor wpack .cs2105 .cs2106
CS3283 - Hugh Anderson’s notes. Page number: 215
Example 3
CS3283 - Hugh Anderson’s notes. Page number: 216
Example 3
set course CS2106
CS3283 - Hugh Anderson’s notes. Page number: 217
Tcl/Tk example software
CS3283 - Hugh Anderson’s notes. Page number: 218
Code is
#!/usr/local/bin/wish8.1 −f
text .log −width 60 −height 5 −bd 2 −relief raised pack .log button .buttonquit −text " Quit" −command exit pack .buttonquit button .buttondate −text " date" −command getdate pack .buttondate proc getdate {} { set result [ exec date] .log insert end $result .log insert end \n }
CODE LISTING SimpleProg.tcl
CS3283 - Hugh Anderson’s notes. Page number: 219
Listbox
Tutorial...
CS3283 - Hugh Anderson’s notes. Page number: 220
Scrollbars
Tutorial...
CS3283 - Hugh Anderson’s notes. Page number: 221
Scales
Tutorial...
CS3283 - Hugh Anderson’s notes. Page number: 222
Tcl/Tk menus
✔ Make up a frame for the menu
✔ Add in the top level menu items
✔ For each top level item, add in the drop-menu items
✔ For each nested item, add in any cascaded menus.
✔ Remember to pack it...
CS3283 - Hugh Anderson’s notes. Page number: 223
Tcl/Tk menus
#!/usr/bin/wish
frame .mbar −relief raised −bd 2pack .mbar −side top −fill x
frame .dummy −width 10c −height 100pack .dummy
menubutton .mbar.file −text File −underline 0 −menu .mbar.file.menumenu .mbar.file.menu −tearoff 0.mbar.file.menu add command −label " New..." −command " newcommand".mbar.file.menu add command −label " Open..." −command " opencommand".mbar.file.menu add separator.mbar.file.menu add command −label Quit −command exitpack .mbar.file −side left
menubutton .mbar.edit −text Edit −underline 0 −menu .mbar.edit.menumenu .mbar.edit.menu −tearoff 1.mbar.edit.menu add command −label " Undo..." −command " undocommand".mbar.edit.menu add separator.mbar.edit.menu add cascade −label Preferences −menu .mbar.edit.menu.prefsmenu .mbar.edit.menu.prefs −tearoff 0.mbar.edit.menu.prefs add command −label " Load default" −command " defaultprefs".mbar.edit.menu.prefs add command −label " Revert" −command " revertprefs"pack .mbar.edit −side left
menubutton .mbar.help −text Help −underline 0 −menu .mbar.help.menumenu .mbar.help.menu −tearoff 0.mbar.help.menu add command −label " About ThisApp..." −command " aboutcommand"pack .mbar.help −side right
proc aboutcommand {} { tk_dialog .win {About this program} " Hugh wrote it!" {} 0 OK}
CODE LISTING Menus.tcl
CS3283 - Hugh Anderson’s notes. Page number: 224
Tcl/Tk menus
CS3283 - Hugh Anderson’s notes. Page number: 225
Tk canvas
✔ Draw items
✔ Items may be tagged
✔ Described in Robert Biddle’s “Using the Tk CanvasFacility”, a copy of which is found at ~cs3283/ftp/CS-TR-94-5.pdf .
✔ Dynamically created variable names (node$nodes ).
CS3283 - Hugh Anderson’s notes. Page number: 226
Chapter 7
Tcl/Tk - 3, Java
CS3283 - Hugh Anderson’s notes. Page number: 227
Bindings
Bind a Tcl/Tk script to an X event
CS3283 - Hugh Anderson’s notes. Page number: 228
Example 4
canvas .c -bd 3 -relief raised; pack .cbutton .b -text BUTTON1; pack .bbind .b <Enter> {.c config -cursor {clock}}
CS3283 - Hugh Anderson’s notes. Page number: 229
File I/O
open /etc/passwd rset f file4while {[gets $f line] >=0} {
puts $line}close $f
CS3283 - Hugh Anderson’s notes. Page number: 230
File I/O
✔ flush fileId
✔ seek fileID offset [start/current/end]
✔ tell fileID
✔ read fileID numbytes
CS3283 - Hugh Anderson’s notes. Page number: 231
File I/O
✔ file dirname name
✔ file tail name
CS3283 - Hugh Anderson’s notes. Page number: 232
Demo tkpaint
CS3283 - Hugh Anderson’s notes. Page number: 233
Mainline
#! /usr/local/bin/wish −f set thistool rectangle set thisop grow set thiscolour black button .exitbtn −bitmap @exit.xbm −command exit button .squarebtn −bitmap @square.xbm −command setsquaretool button .circlebtn −bitmap @circle.xbm −command setcircletool button .shrnkbtn −bitmap @shrink.xbm −command " set thisop shrnk" button .growbtn −bitmap @grow.xbm −command " set thisop grow" button .printbtn −bitmap @print.xbm −command printit button .colorbtn −bitmap @newcolour.xbm −command setanewcolour canvas .net −width 400 −height 400 −background white −relief sunken canvas .status −width 40 −height 40 −background white −relief sunken pack .net −side bottom pack .status −side right pack .squarebtn .circlebtn −side left −ipadx 1m −ipady 1m −expand 1 pack .exitbtn .printbtn −side right −ipadx 1m −ipady 1m −expand 1 pack .colorbtn .shrnkbtn .growbtn −side right −ipadx 1m −ipady 1m −expand 1 bind .net <ButtonPress−1> {makenode %x %y} .status create rectangle 10 10 37 37 −tag statusthingy −fill $thiscolour set nodes 0; set oldx 0; set oldy 0;
CODE LISTING Page 1/1tkpaint1.tcl
CS3283 - Hugh Anderson’s notes. Page number: 234
Routines
proc beginmove {x y} {global oldx oldyset oldx $x; set oldy $y
}
proc domove {item x y} {global oldx oldy.net move $item [ expr " $x − $oldx"] [ expr " $y − $oldy"]set oldx $x; set oldy $y
}
proc altersize {item x y z} {.net scale $item $x $y $z $z
}
proc printit {} {.net postscript −file " pic.ps"
}
CODE LISTING tkpaint4.tcl
CS3283 - Hugh Anderson’s notes. Page number: 235
Routines
proc makenode {x y} { global nodes oldx oldy thistool thiscolor set nodes [ expr " $nodes+1"]
set x1 [ expr " $x−20"]; set y1 [ expr " $y−20"] set x2 [ expr " $x+20"]; set y2 [ expr " $y+20"] if {[ string compare $thistool " oval"] == 0} {
.net create oval $x1 $y1 $x2 $y2 −tag node$nodes −fill $thiscolor } if {[ string compare $thistool " rectangle"] == 0} {
.net create rectangle $x1 $y1 $x2 $y2 −tag node$nodes −fill $thiscolor } .net bind node$nodes <Enter> " .net itemconfigure node$nodes −width 5" .net bind node$nodes <Leave> " .net itemconfigure node$nodes −width 1" .net bind node$nodes <ButtonPress−3> " beginmove %x %y" .net bind node$nodes <B3−Motion> " domove node$nodes %x %y" .net bind node$nodes <ButtonPress−2> " dothisop node$nodes %x %y" }
proc dothisop {item x y} { global thisop if {[ string compare $thisop " shrink"] == 0} {
altersize $item $x $y 0.5 } if {[ string compare $thisop " grow"] == 0} {
altersize $item $x $y 2.0 } }
CODE LISTING tkpaint2.tcl
CS3283 - Hugh Anderson’s notes. Page number: 236
Routines
proc setcircletool {} {global thistool thiscolorset thistool oval.status delete statusthingy.status create oval 10 10 37 37 −tag statusthingy −fill $thiscolor
}
proc setsquaretool {} {global thistool thiscolorset thistool rectangle.status delete statusthingy.status create rectangle 10 10 37 37 −tag statusthingy −fill $thiscolor
}
proc setanewcolor {} {global thiscolor
if {[ string compare $thiscolor " black"] == 0} {set thiscolor green
} { if {[ string compare $thiscolor " green"] == 0} { set thiscolor blue
} { if {[ string compare $thiscolor " blue"] == 0} { set thiscolor red
} { if {[ string compare $thiscolor " red"] == 0} { set thiscolor orange
} { set thiscolor black } }
} }.status itemconfigure statusthingy −fill $thiscolor
}
CODE LISTING tkpaint3.tcl
CS3283 - Hugh Anderson’s notes. Page number: 237
End of Tk intro
Next assignment will be a Tk programming one...
and now...
CS3283 - Hugh Anderson’s notes. Page number: 238
Java and JFC
✔ Java - applications across a network
✔ Native-code interpreter for Java code.
✔ Core functions called JFC (Java Foundation Classes).
✔ JFC for GUIs, accessability, 2D drawing...
CS3283 - Hugh Anderson’s notes. Page number: 239
AWT
✔ AWT - the Abstract Windowing Toolkit.
✔ AWT provides buttons, frames, dialogs...
✔ Implemented in native code in the Java interpreter.
CS3283 - Hugh Anderson’s notes. Page number: 240
Swing
✔ Not implemented in native code
✔ Implemented in AWT.
✔ Swing and AWT coexist
CS3283 - Hugh Anderson’s notes. Page number: 241
Swing advantages
Consistent look-and-feel
Pluggable look-and-feel
High-level widgets
CS3283 - Hugh Anderson’s notes. Page number: 242
How not to...
✘ Watch interpreter overhead
✘ Internal thread scheduling
CS3283 - Hugh Anderson’s notes. Page number: 243
Getting started
http://java.sun.com/j2se/1.4.2/download.html
j2sdk1.4.2http://www.comp.nus.edu.sg/˜cs3283/ftp/Java/
Netbeans+j2sdkhttp://www.comp.nus.edu.sg/˜cs3283/ftp/Java/
CS3283 - Hugh Anderson’s notes. Page number: 244
Documentation
Sun’s Java web site, and http://www.netbeans.org.http://www.comp.nus.edu.sg/˜cs3283/ftp/Java/jfcapi/
http://www.comp.nus.edu.sg/˜cs3283/ftp/Java/OpenAPIs/
http://www.comp.nus.edu.sg/˜cs3283/ftp/Java/JavaTutorial/
http://www.comp.nus.edu.sg/˜cs3283/ftp/Java/swingConnect/
CS3283 - Hugh Anderson’s notes. Page number: 245
Demo
Find the file called SwingSet2.jar. Then try:
java -jar SwingSet2.jar
CS3283 - Hugh Anderson’s notes. Page number: 246
Swing programming
✔ Use same strategy as used in Tcl/Tk.
✔ A good book that covers this material in detail is
The JFC Swing Tutorial
by Kathy Walrath and Mary Campione.
CS3283 - Hugh Anderson’s notes. Page number: 247
Toplevel components
The toplevel components provided by Swing are:
JApplet - for applets within web pages
JDialog - for dialog boxes
JFrame - for building applications
All other Swing components derive from the JComponentclass.
CS3283 - Hugh Anderson’s notes. Page number: 248
JComponent
Tool tips - little windows with explanations
Pluggable look and feel - as described
Layour management - items within the component
Keyboard action management - Hot keys and so on.
And other facilities
Swing implements an MVC architecture.
CS3283 - Hugh Anderson’s notes. Page number: 249
Pluggable look and feel
CS3283 - Hugh Anderson’s notes. Page number: 250
Pluggable look and feel
CS3283 - Hugh Anderson’s notes. Page number: 251
Pluggable look and feel
CS3283 - Hugh Anderson’s notes. Page number: 252
Pluggable look and feel
If you wished to use the WinXX look-and-feel, in the main ofyour application, you can make the following call:
UIManager.setLookAndFeel( "com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
CS3283 - Hugh Anderson’s notes. Page number: 253
Example application
public class t2 extends javax.swing.JFrame { public t2() { initComponents(); } private void initComponents() { jLabel2 = new javax.swing.JLabel(); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); jLabel2.setText("Hello Singapore!"); jLabel2.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabel2, java.awt.BorderLayout.CENTER); pack(); } private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0); } public static void main(String args[]) { new t2().show(); } private javax.swing.JLabel jLabel2;}
CODE LISTING t2.java
CS3283 - Hugh Anderson’s notes. Page number: 254
Example application
✔ Instantiates a JLabel , and sets the text field.
✔ Call to getContentPane returns the contentPane objectfor the frame - this is a generic AWT container forcomponents associated with each JFrame .
✔ The addWindowListener call is from java.awt.Window.
CS3283 - Hugh Anderson’s notes. Page number: 255
Example application
CS3283 - Hugh Anderson’s notes. Page number: 256
Example applet
public class HelloWorldApp extends javax.swing.JApplet { public HelloWorldApp() { initComponents(); } private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel1.setText("Hello Singapore!"); jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER); getContentPane().add(jLabel1, java.awt.BorderLayout.CENTER); } private javax.swing.JLabel jLabel1;}
CODE LISTING HelloWorldApp.java
CS3283 - Hugh Anderson’s notes. Page number: 257
Example applet
✔ This code follows the same structure,
✔ Class extends a JApplet instead of a JFrame .
✔ Compile to get a HelloWorldApp.class file,
✔ Has to be referenced in a web page
CS3283 - Hugh Anderson’s notes. Page number: 258
Example applet
<BASE HREF="http://www.comp.nus.edu.sg/~hugh/swing/"><!DOCTYPE HTML PUBLIC "−//W3C//DTD HTML 3.2//EN"><html>The HelloWorld Applet <p><EMBED type = "application/x−java−applet;version=1.1.2" java_CODE = "HelloWorldApp.class" java_ARCHIVE = "applets.jar" WIDTH = 400 HEIGHT = 50 ></EMBED></HTML>
CODE LISTING HelloWorldApp.txt
CS3283 - Hugh Anderson’s notes. Page number: 259
Example applet
CS3283 - Hugh Anderson’s notes. Page number: 260
Netbeans IDE
CS3283 - Hugh Anderson’s notes. Page number: 261
Summary of topics
In this module, we introduced the following topics:
Tool sets for Java/Swing
The relationship between JFC, Java and Swing.
Simple first programs
CS3283 - Hugh Anderson’s notes. Page number: 262
Chapter 8
Java continued
CS3283 - Hugh Anderson’s notes. Page number: 263
ALERT
✔ MCQ test next week
✔ This time
✔ This place
✔ Closed book
CS3283 - Hugh Anderson’s notes. Page number: 264
ALERT
✔ Assignment #2 is for groups of 3
✔ Like extended version of tkpaint, but has
✔ menus✔ persistence✔ compound objects
CS3283 - Hugh Anderson’s notes. Page number: 265
Last week
• Tool sets for Java/Swing
• The relationship between JFC, Java and Swing.
• Simple first programs
CS3283 - Hugh Anderson’s notes. Page number: 266
This week
• Heirarchy
• Layout managers
• Simple first programs
CS3283 - Hugh Anderson’s notes. Page number: 267
Containment heirarchy
Top level provides panes for descendants to paintthemselves
Control-Shift-F1 to view
t2[frame0,954,518,126x43,layout=java.awt...javax.swing.JRootPane[,4,24,118x15,la...
javax.swing.JPanel[null.glassPane,...javax.swing.JLayeredPane[null.laye...
javax.swing.JPanel[null.content...javax.swing.JLabel[,0,0,118x...
CS3283 - Hugh Anderson’s notes. Page number: 268
Containment heirarchy
CS3283 - Hugh Anderson’s notes. Page number: 269
Containment heirarchy
The glass pane: Intercepts input events for the root pane.
The layered pane: Serves to position its contents, whichconsist of the content pane and the optional menu bar.
The content pane: The container of the root pane’s visiblecomponents, excluding the menu bar.
The menu bar: The home for the root pane’s container’smenus.
CS3283 - Hugh Anderson’s notes. Page number: 270
Containment heirarchy
Level ContainerTop-level JFrame
JAppletJDialog
Mid-level JPanelJScrollBar
JTabbedPaneComponent-level JButton
JLabel...
CS3283 - Hugh Anderson’s notes. Page number: 271
Containment heirarchy
Every GUI component must be part of a containmenthierarchy4.
Each top-level container has
• a content pane, and an
• optional menu bar
4To view the containment hierarchy for any frame or dialog, click its border to selectit, and then press Control-Shift-F1. A list of the containment hierarchy will be writtento the standard output stream.
CS3283 - Hugh Anderson’s notes. Page number: 272
Containment heirarchy
Java/Swing components are added to either the contentpane or the menu bar.
Every component must be placed somewhere in thiscontainment heirarchy, or it will not be visible.
CS3283 - Hugh Anderson’s notes. Page number: 273
Layout management
✔ Every container has a default layout manager
✔ It may be over-ridden
✔ A range of layout managers supplied
✔ These are AWT components, not Swing
CS3283 - Hugh Anderson’s notes. Page number: 274
BorderLayout
BorderLayout is the default layout manager for every contentpane, and assists in placing components in the north, south,east, west, and center of the content pane.
contentPane.add(new JButton("B1"), BorderLayout.NORTH);
CS3283 - Hugh Anderson’s notes. Page number: 275
BoxLayout
BoxLayout puts components in a single row or column. Hereis code to create a centered column of components:
pane.setLayout(new BoxLayout(pane, BoxLayout.Y AXIS));pane.add(label);pane.add(Box.createRigidArea(new Dimension(0,5)));pane.add(...);
CS3283 - Hugh Anderson’s notes. Page number: 276
CardLayout
CardLayout is for when a pane has different components atdifferent times. You may think of it as a stack of same-sizedcards.
cards = new JPanel();cards.setLayout(new CardLayout());cards.add(p1, BUTTONPANEL);cards.add(p2, TEXTPANEL);
CS3283 - Hugh Anderson’s notes. Page number: 277
CardLayout
You can choose the top card to show:
CardLayout cl = (CardLayout)(cards.getLayout());cl.show(cards, (String)evt.getItem());
CS3283 - Hugh Anderson’s notes. Page number: 278
Creating menus
The menu classes are descendants of JComponent , and maybe used in any higher-level container class (JApplet and soon).
CS3283 - Hugh Anderson’s notes. Page number: 279
Creating menus
public class menutest extends javax.swing.JFrame { public menutest() { initComponents(); } private void initComponents() { jMenuBar1 = new javax.swing.JMenuBar(); jMenu1 = new javax.swing.JMenu(); jMenuItem1 = new javax.swing.JMenuItem(); jMenuItem2 = new javax.swing.JMenuItem(); jMenuItem3 = new javax.swing.JMenuItem(); jMenu2 = new javax.swing.JMenu(); jMenuItem4 = new javax.swing.JMenuItem(); jMenu1.setText("File"); jMenuItem1.setText("Open"); jMenu1.add(jMenuItem1); jMenuItem2.setText("Close"); jMenu1.add(jMenuItem2); jMenuItem3.setText("Quit"); jMenuItem3.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { jMenuItem3ActionPerformed(evt); } }); jMenu1.add(jMenuItem3); jMenuBar1.add(jMenu1); jMenu2.setText("Edit"); jMenuItem4.setText("Cut"); jMenu2.add(jMenuItem4); jMenuBar1.add(jMenu2); addWindowListener(new java.awt.event.WindowAdapter() { public void windowClosing(java.awt.event.WindowEvent evt) { exitForm(evt); } }); setJMenuBar(jMenuBar1); pack(); }
private void jMenuItem3ActionPerformed(java.awt.event.ActionEvent evt) { System.exit(0); } private void exitForm(java.awt.event.WindowEvent evt) { System.exit(0); } public static void main(String args[]) { new menutest().show(); } private javax.swing.JMenuBar jMenuBar1; private javax.swing.JMenu jMenu1; private javax.swing.JMenuItem jMenuItem1; private javax.swing.JMenuItem jMenuItem2; private javax.swing.JMenuItem jMenuItem3; private javax.swing.JMenu jMenu2; private javax.swing.JMenuItem jMenuItem4;}
CODE LISTING menutest.java
CS3283 - Hugh Anderson’s notes. Page number: 280
Menus
The end result is:
CS3283 - Hugh Anderson’s notes. Page number: 281
Threads in Swing
✔ Java supports multi-threading
✔ We may have critical sections
✔ To create threads use SwingWorker or Timer .
CS3283 - Hugh Anderson’s notes. Page number: 282
Threads
Most Swing components are not thread safe - this meansthat if two threads call methods on the same Swingcomponent, the results are not guaranteed.
The single-thread rule:
Swing components accessed by only one thread at a time.
CS3283 - Hugh Anderson’s notes. Page number: 283
Threads
A particular thread, the event-dispatching thread, is the onethat normally accesses Swing components.
To get access to this thread from another thread we can useinvokeLater() or invokeAndWait() .
CS3283 - Hugh Anderson’s notes. Page number: 284
Threads
Many applications do not require threading, but if you dohave threads, then you may have problems debugging yourprograms. However, you might consider using threads if:
Your application has to do some long task, or wait for anexternal event, without freezing the display.
Your application has to do someting at fixed time intervals.
CS3283 - Hugh Anderson’s notes. Page number: 285
Implementing threads
The following two classes are used to implement threads:
1. SwingWorker 5: To create a thread
2. Timer : Creates a timed thread
5If you find that your distribution does not include SwingWorker.class, downloadand compile it.
CS3283 - Hugh Anderson’s notes. Page number: 286
SwingWorker
To use SwingWorker , create a subclass of it, and in thesubclass, implement your own construct( ) method.
When you instantiate the SwingWorker subclass, the runtimeenvironment creates a thread but does not start it.
The thread starts when you invoke start() on the object.
CS3283 - Hugh Anderson’s notes. Page number: 287
Example
Here’s an example of using SwingWorker from the tutorial -an image is to be loaded over a network (given a URL).
This may of course take quite a while, so we don’t block ourmain thread - (if we did this, the GUI may freeze).
CS3283 - Hugh Anderson’s notes. Page number: 288
SwingWorker example
private void loadImage(final String imagePath, final int index) { final SwingWorker worker = new SwingWorker() { ImageIcon icon = null; public Object construct() { icon = new ImageIcon(getURL(imagePath)); return icon; } public void finished() { Photo pic = (Photo)pictures.elementAt(index); pic.setIcon(icon); if (index == current) updatePhotograph(index, pic); } }; worker.start();}
CODE LISTING ImageLoader.java
CS3283 - Hugh Anderson’s notes. Page number: 289
Timer
The Timer class is used to repeatedly perform an operation.
When you create a Timer , you specify its frequency, and youspecify which object is the listener for its events.
Once you start the timer, the action listener’s actionPerformed()method will be called for each event.
CS3283 - Hugh Anderson’s notes. Page number: 290
Event dispatching thread
The event-dispatching thread is the main event-handlingthread. It is normal for all GUI code to be called from thismain thread, even if some of the code may take a longtime to run. However - we have already mentioned that weshould not delay the event-dispatching thread.
Swing provides a solution to this - the InvokeLater() methodmay be used to safely run code in the event-dispatchingthread.
CS3283 - Hugh Anderson’s notes. Page number: 291
InvokeLater
The method requests that some code be executed in theevent-dispatching thread, but returns immediately, withoutwaiting for the code to execute.
Runnable doWorkRunnable = new Runnable() {public void run() { doWork(); }
};SwingUtilities.invokeLater(doWorkRunnable);
CS3283 - Hugh Anderson’s notes. Page number: 292
Handling events
Actions associated with Java/Swing components raiseevents - moving the mouse or clicking a JButton all causeevents to be raised. The application program writes alistener method to process an event, and registers it as anevent listener on the event source. There are different kindsof events, and we use different kinds of listener to act onthem.
CS3283 - Hugh Anderson’s notes. Page number: 293
Listener types
Action Listener type
Button click ActionListener
A window closes WindowListener
Mouse click MouseListener
Mouse moves MouseMotionListener
Component becomes visible ComponentListener
Keyboard focus FocusListener
List selection changes ListSelectionListener
CS3283 - Hugh Anderson’s notes. Page number: 294
Listeners
The listener methods are passed an event object whichgives information about the event and identifies the eventsource.
CS3283 - Hugh Anderson’s notes. Page number: 295
Event handlers
When you write an event handler, you must do the following:
• Specify a class
• Register an instance of the class as a listener
• Implement the methods
CS3283 - Hugh Anderson’s notes. Page number: 296
Specify class
Specify a class that either implements a listener interface orextends a class that implements a listener interface.
public class MyClass implements ActionListener { ...
CS3283 - Hugh Anderson’s notes. Page number: 297
Register it
Register an instance of the class as a listener upon thecomponents.
Component.addActionListener(instanceOfMyClass);
CS3283 - Hugh Anderson’s notes. Page number: 298
Implement method
Implements the methods in the listener interface.
public void actionPerformed(ActionEvent e) {...//code that reacts to the action...
}
CS3283 - Hugh Anderson’s notes. Page number: 299
Event handling
Make sure that your event handler code executes quickly, oryour program may seem to be slow.
In the sample code given so far, we have used windowlisteners to react if someone closes a window, but not tocapture other sorts of events.
CS3283 - Hugh Anderson’s notes. Page number: 300
Handling events
public class CheckBoxDemo extends JPanel { JCheckBox chinButton; JCheckBox glassesButton; StringBuffer choices; JLabel pic; public CheckBoxDemo () { chinButton = new JCheckBox (" Chin"); glassesButton = new JCheckBox (" Glasses"); CheckBoxListener myListener = new CheckBoxListener (); chinButton.addItemListener (myListener); glassesButton.addItemListener (myListener); choices = new StringBuffer (" −−ht"); pic = new JLabel ( new ImageIcon (" geek−" + choices.toString () + " .gif")); pic.setToolTipText (choices.toString ()); JPanel checkPanel = new JPanel (); checkPanel.setLayout ( new GridLayout (0, 1)); checkPanel.add (chinButton); checkPanel.add (glassesButton); setLayout ( new BorderLayout ()); add (checkPanel, BorderLayout.WEST); add (pic, BorderLayout.CENTER); setBorder (BorderFactory.createEmptyBorder (20, 20, 20, 20)); } class CheckBoxListener implements ItemListener { public void itemStateChanged (ItemEvent e) { int index = 0; char c = ’−’; Object source = e.getItemSelectable (); if (source == chinButton) { index = 0; c = ’c’; } else if (source == glassesButton) { index = 1; c = ’g’; } if (e.getStateChange () == ItemEvent.DESELECTED) c = ’−’; choices.setCharAt (index, c); pic.setIcon ( new ImageIcon (" geek−" + choices.toString () + " .gif")); pic.setToolTipText (choices.toString ()); } } public static void main (String s[]) { JFrame frame = new JFrame (" CheckBoxDemo"); frame.addWindowListener ( new WindowAdapter () { public void windowClosing (WindowEvent e) { System.exit (0);} } );
CODE LISTING CheckBoxDemo.java frame.setContentPane (new CheckBoxDemo ()); frame.pack (); frame.setVisible (true); } }
CODE LISTING CheckBoxDemo.java
CS3283 - Hugh Anderson’s notes. Page number: 301
Example code
When you change either checkbox, an itemListener respondsto the event and changes the graphic.
CS3283 - Hugh Anderson’s notes. Page number: 302
Summary of topics
In this module, we introduced the following topics:
The containment heirarchy
Layout managers
Menus
Threading
Event handling
CS3283 - Hugh Anderson’s notes. Page number: 303
Chapter 9
Module7
CS3283 - Hugh Anderson’s notes. Page number: 304
MCQ Test
✔ Closed book
✔ Closed computer
✔ 20 questions
✔ Leave if finished, but come back at 1:00 for lecture
CS3283 - Hugh Anderson’s notes. Page number: 305
MCQ Test
✘ Any questions?
CS3283 - Hugh Anderson’s notes. Page number: 306
Java
✔ No more lecture material, but
✔ I will respond to questions with material as needed
✔ Following few weeks will have Java/Swing centeredquestions, and
✔ Assignment 3 (announced next week) will requireJava/Swing, so get some practice in...
CS3283 - Hugh Anderson’s notes. Page number: 307
Common Gateway Interface
✔ CGI is a standard for helping web servers run externalprograms,
✔ and return dynamic web pages.
For example, a simple dynamic web page might returnthe current date and time, calculated by running the ’date ’program, and formatting the results as a web page.
CS3283 - Hugh Anderson’s notes. Page number: 308
CGI script
#!/bin/sh
cat <<EOM1 Content−type: text/html
<HTML><HEAD> <TITLE>Output of data in HTML from CGI script</TITLE> </HEAD><BODY> <H1>Date:</H1> EOM1 date cat <<EOM2 </BODY></HTML> EOM2
CODE LISTING mydate.cgi
CS3283 - Hugh Anderson’s notes. Page number: 309
CGI script
When this script is placed in the directory public cgi in yourhome directory on one of the UNIX systems, then you mayrefer to
http://www-cgi.comp.nus.edu.sg:8000/~yourid/mydate.cgi
CS3283 - Hugh Anderson’s notes. Page number: 310
CGI script
CS3283 - Hugh Anderson’s notes. Page number: 311
CGI script
CS3283 - Hugh Anderson’s notes. Page number: 312
CGI scripts
✔ No requirement for CGI program to be a shell script.
✔ Perl is very commonly used in this role.
✔ It should not take too long to process.
CS3283 - Hugh Anderson’s notes. Page number: 313
Environment variables
#!/usr/local/bin/perl
print "Content−type: text/html\n\n";print <<EndOfHTML;<html><head><title>Print Environment</title></head><body>EndOfHTML
foreach $key (sort(keys %ENV)) { print "$key = $ENV{$key}<br>\n";}
print "</body></html>";
CODE LISTING env.cgi
CS3283 - Hugh Anderson’s notes. Page number: 314
Environment variables
DOCUMENT ROOT = /usr/local/apache/htdocsGATEWAY INTERFACE = CGI/1.1HTTP USER AGENT = Mozilla/4.79 [en] (X11; U; Linux 2.2.16 i686)...QUERY STRING =...TZ = Singapore
CS3283 - Hugh Anderson’s notes. Page number: 315
CGI forms - GET
The form contents are found inside an environment variablecalled QUERYSTRING, as a series of name/value pairs.
This mechanism is known as the GET mechanism, and atypical URL would look like this:
.../myform.cgi?name1=value1&name2=value2
CS3283 - Hugh Anderson’s notes. Page number: 316
POST
An alternative mechanism is the POSTmechanism, in whichthe STDIN of the CGI program is used to process the formdata.
CS3283 - Hugh Anderson’s notes. Page number: 317
CGI form
<html><head>Simple form</head><body><form action="env.cgi" method="GET"> First Name: <input type="text" name="First" size=30><p> Last Name: <input type="text" name="Last" size=30><p> <select name="Home"> <option>Singapore <option>Malaysia <option>Indonesia <option>New Zealand <option>The rest of the world! </select> <input type="submit"></form> </body></html>
CODE LISTING form.html
CS3283 - Hugh Anderson’s notes. Page number: 318
CGI form
CS3283 - Hugh Anderson’s notes. Page number: 319
CGI form
When the form is submitted, the QUERYSTRING looks likethis:
QUERY STRING = First=Hugh&Last=Anderson&Home=New+Zealand
Within a CGI program, this series of name-value pairs maybe used to return a dynamic web page based on this formdata.
Perl is a particularly useful language to use in this context -the QUERYSTRINGcan be split quickly into its componentparts.
CS3283 - Hugh Anderson’s notes. Page number: 320
Security
✔ There are security issues with unrestricted CGIprograms - since they run powerful programs (like perland csh) with arbitrary parameters, they may be a sourceof (hacker) intrusion.
✔ It is for this reason that CGI usage is restricted here atNUS.
CS3283 - Hugh Anderson’s notes. Page number: 321
PHP
✔ PHP is a server-side scripting language.
✔ It looks very like standard HTML scripts, but the serverautomatically interprets the PHP.
✔ There are no enhancements needed for browsers.
CS3283 - Hugh Anderson’s notes. Page number: 322
PHP
✔ The two tags <?php and ?> start and end a PHP script,and identify a PHP code segment.
✔ The PHP code itself is a reasonably powerfulprogramming language similar to Java, C and Perl, withfunctions, variables and so on.
PHP stands for PHP - Hypertext Preprocessor, a recursiveacronym.
CS3283 - Hugh Anderson’s notes. Page number: 323
PHP
✔ Particularly useful to access databases.
✔ It is common to pair up PHP with MySQL, but PHP is notlimited to one database type.
✔ For example if you wish to use PHP to access a MicrosoftSQL server, you can install the ODBC support in theserver machine, and access the server directly.
CS3283 - Hugh Anderson’s notes. Page number: 324
PHP code
<?php...mysql pconnect("host","user","password")
or die("Unable to connect to SQL server");mysql select db("dbasename")
or die("Unable to select database");$numguests = mysql query("SELECT COUNT(*) FROM guests")
or die("Select Failed!");...
?>
CS3283 - Hugh Anderson’s notes. Page number: 325
PHP security
✔ PHP suffers less from the security issue than perl or cshCGI scripts do.
CS3283 - Hugh Anderson’s notes. Page number: 326
Java
/* @(#)Lissajous.java * Original version was written in 0.4 95/04/09 * by Hugh Anderson for HotJava browser. * * Updated by L. Gladney to Java 1.0 JDK on 4/13/97. * * Patrick Chan ([email protected] ) has suggested that it * would be nice if every point had a different display, so mouse * X motion now controls the ratio of frequencies, and mouse Y motion * controls the amplitude. */
import java.applet.Applet;import java.awt.*;
public class Lissajous extends Applet implements Runnable { Thread animate= null; double pi=3.14159265359; int fx=50; int fy=100; int diffx=0; int amp=50,phase=0; // amplitude, phase int delay = 50; // speed set by length // of sleep between refreshes public void init() { resize(200, 200); // resize to fixed width,height }
public void paint(Graphics g) { int X,Y,YY=0,lastx=0,lasty=0,temp=0,rev=0; g.drawRect(0, 0, size().width − 1, size().height − 1); // outline if ( fy < fx ) { // frequency temp = fx; fx = fy; fy = temp; rev = 1; } for ( int x = 0 ; x <= 360 ; x += 4) { // loop X = ( int) ( amp*Math.sin( x*2.0*pi/360.0 )); // x pos YY = (x*fy/fx)+phase; Y = ( int) ( amp*Math.sin( YY*2.0*pi/360.0 )); if (x==0) { lastx=X; lasty=Y; } if (rev==1) { g.drawLine(lastx+100,lasty+100,X+100,Y+100); } else { g.drawLine(lasty+100,lastx+100,Y+100,X+100); } lastx=X; lasty=Y; } if ( rev==1 ) { temp=fx; fx = fy; fy = temp; } phase = YY; /* Fix an error ... phase shouldn’t increase forever..... */ if ( phase < 0 ) { phase += 360; }; if ( phase >= 360 ) { phase −= 360; }; g.drawString( fx + " :" + fy,10,20); }
CODE LISTING Lissajous1.java
CS3283 - Hugh Anderson’s notes. Page number: 327
Java
public void run() { while ( true) { repaint();
try { Thread.currentThread().sleep(delay); // delay } catch (Exception e) { };
} }
public void start() { if ( animate == null ) { animate = new Thread( this); animate.start(); } } public void stop() { if (animate != null ) { animate.stop(); animate = null; } } public boolean mouseDown(Event e, int x, int y ) { Graphics gc; gc = getGraphics();
diffx = fx−x; System.out.println(" Got a mouse event at " + x + " , " + y);
return true; }
public boolean mouseDrag(Event e, int x, int y) { fx = x+diffx; if ( fx <= 0 ) { fx = 1; }; amp = y;
return true; }
public String getAppletInfo() { return " Lissajous by Hugh Anderson/Larry Gladney "; }
public String[][] getParameterInfo() { String [][] info = { {" delay "," int ", " delay, default=50"} }; return info; }
}
CODE LISTING Lissajous2.java
CS3283 - Hugh Anderson’s notes. Page number: 328
Java
This code may be found at
http://olddept.physics.upenn.edu/courses/gladney/minicourse/lectures/lecture2.html
or locally at
http://www.comp.nus.edu.sg/~hugh/Lissajous/Lissajous.html
CS3283 - Hugh Anderson’s notes. Page number: 329
Java
CS3283 - Hugh Anderson’s notes. Page number: 330
Summary of topics
In this module, we introduced the following topics:
Web-based application architectures
CGI, PHP and Java
CS3283 - Hugh Anderson’s notes. Page number: 331
Chapter 10
Module 8
CS3283 - Hugh Anderson’s notes. Page number: 332
Visualization
✔ In visualization, we are concerned with exploration
✔ In computer-graphics, we are concerned with rendering
CS3283 - Hugh Anderson’s notes. Page number: 333
The use of 3D
✔ Analog with real-world physics.
✔ 10-fold improvement in item density with 3D.
✔ Familiarity with spatial location helps reduce visualclutter.
✔ Need sufficient visual cues.
CS3283 - Hugh Anderson’s notes. Page number: 334
Use of 3D
CS3283 - Hugh Anderson’s notes. Page number: 335
OpenGL
✔ SGI in-house graphics system
✔ Now a widely accepted graphics standard
✔ Standard on UNIX and Windows
✔ API supports rendering, buffering, anti-aliasing, shading,colouring, texture-mapping, a display list, Z-buffering...
CS3283 - Hugh Anderson’s notes. Page number: 336
OpenGL Application
CS3283 - Hugh Anderson’s notes. Page number: 337
OpenGL source
#include <GL/glut.h> void Teapot ( long grid) { /* ... code to construct drawlist of teapot here. */ } static void Init ( void) { glEnable (GL_DEPTH_TEST); glLightModelfv (GL_LIGHT_MODEL_LOCAL_VIEWER, local_view); /* Lighting model, materials... */ } static void SpecialKey ( int key, int x, int y) { switch (key) { case GLUT_KEY_UP: rotX −= 20.0; glutPostRedisplay (); break; /* Move in other directions */ } } static void Draw ( void) { glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glPushMatrix (); /* ... translations ... */ glCallList (teaList); glPopMatrix (); glutSwapBuffers (); } int main ( int argc, char **argv) { glutInit (&argc, argv); type = GLUT_RGB | GLUT_DEPTH; type |= (doubleBuffer) ? GLUT_DOUBLE : GLUT_SINGLE; glutInitDisplayMode (type); glutInitWindowSize (300, 300); glutCreateWindow (" TeaPot"); Init (); glutReshapeFunc (Reshape); glutKeyboardFunc (Key); glutSpecialFunc (SpecialKey); glutDisplayFunc (Draw); glutMainLoop (); }
CODE LISTING teapot.c
CS3283 - Hugh Anderson’s notes. Page number: 338
Java3D & VTK
✔ 3D OO toolkits
✔ VTK is open source
✔ C++ class library, and✔ interface layers for Tcl/Tk, Java, and Python.
CS3283 - Hugh Anderson’s notes. Page number: 339
Network traffic application
To help answer questions such as the following:
Which segments carry the most traffic?
Which sections of the network are down?
At what times, and where do traffic bottlenecks occur?
...
CS3283 - Hugh Anderson’s notes. Page number: 340
Application elements
Following elements are represented:
Background: - to convince the viewer that the display isthree dimensional ...
Nodes: - a computer, a network device...
Traffic: - the amount of traffic flow...
Protocol: - the type of traffic...
...
CS3283 - Hugh Anderson’s notes. Page number: 341
Node representation
CS3283 - Hugh Anderson’s notes. Page number: 342
Rendering speed
Machine Rendering speed Computer (a) Computer (b) Computer (c)
Workstation 485,000 ∆/sec 0.485 frames/sec 11.5 frames/sec 69 frames/sec
PC1 30,000 ∆/sec 0.03 frames/sec 0.71 frames/sec 4.3 frames/sec
PC2 11,000 ∆/sec 0.011 frames/sec 0.26 frames/sec 1.6 frames/sec
CS3283 - Hugh Anderson’s notes. Page number: 343
Levels of Detail
✔ Some representation methods allow different levels ofdetail .
✔ In VRML an object may be represented in different waysdepending on how large it is.
✔ If the object is near you, it could be represented in detail,but if it is a long way away, the representation could beas simple as a coloured square.
CS3283 - Hugh Anderson’s notes. Page number: 344
LOD
LOD {range [20]level [
Shape{ #full detail 16 sided coneappearance Appearance { material Material { ... } }geometry Extrusion{ ... }.
}Shape{ #low detail 4 sided cone
appearance Appearance { material Material { ... } }geometry Extrusion{ ... }
}]
}
CS3283 - Hugh Anderson’s notes. Page number: 345
LOD
✔ If the distance from the user to the object is smaller thanthe first range value specified, then the first version isdrawn.
✔ If the distance is greater than the last range specified,the last version is drawn.
CS3283 - Hugh Anderson’s notes. Page number: 346
Traffic and protocols
Draw a line between nodes.
A line indicates source and destination, but not the amountof traffic:
1. Colour coding (black through red to white for maximumtraffic),
2. Line width, and
3. The length of partial lines, as discussed in Eick’s papers.
CS3283 - Hugh Anderson’s notes. Page number: 347
Partial lengths
CS3283 - Hugh Anderson’s notes. Page number: 348
Trend representation
✔ Graphing
✔ 4D visualization methods
✔ Encode previous on-top-of the current - visual echoes.
CS3283 - Hugh Anderson’s notes. Page number: 349
Display
CS3283 - Hugh Anderson’s notes. Page number: 350
Systems
✔ CosmoPlayer VRML viewer,
✔ geomview .
The visualization is not dependant on the navigation orimplementation method.
CS3283 - Hugh Anderson’s notes. Page number: 351
Aggregation
Aggregation Nodes
CS3283 - Hugh Anderson’s notes. Page number: 352
Implementation #1
✔ A data collector
✔ A web page with... a
✔ Java program loaded as an applet, and a✔ VRML view of the network.
CS3283 - Hugh Anderson’s notes. Page number: 353
3DVNT
CS3283 - Hugh Anderson’s notes. Page number: 354
Web page
<html><head> <title>Sample 3DVNT Page</title> </head><center><H1>Sample 3DVNT Page </H1></center><center> <embed src="root.wrl" height="600" width="700"> </center><center> <applet code="View1.class" width="100" height="10" mayscript><PARAM name="segment" value="MACS"><PARAM name="port" value="9876"><PARAM name="host" value="opo.usp.ac.fj"> </applet> </center>OK?</html>
CS3283 - Hugh Anderson’s notes. Page number: 355
VRML
PROTO CLUSTER [] { ... } # Cluster definitionPROTO KEYBOARD [] { ... } # Keyboard definitionPROTO SCREEN [] { ... } # Screen definitionPROTO GLOBE [] { ... } # Traffic sphere definition# Some setting up declarationsBackground { skyColor .4 .66 1 }NavigationInfo { type [ "EXAMINE", "ANY" ] speed 400 }Viewpoint { position 0 400 0 orientation 0 1 0 4 description "Camera 1" }# Lines, floors and roofsDEF LINES Transform { ... }DEF FLOORS Transform { ... }DEF ROOFS Transform { ... }# and then the nodesDEF node1 Transform { ... }DEF node2 Transform { ... }# ... and so on ...
CS3283 - Hugh Anderson’s notes. Page number: 356
VRML nodes
DEF node1 Transform {translation 4350 150 4365rotation 0 1 0 4.71238children [
KEYBOARD {}SCREEN {}DEF node1box Transform {
children [Shape { ... }
] }DEF node1sphere Transform {
scale 1 1 1children [
Shape { ... }] } ] }
CS3283 - Hugh Anderson’s notes. Page number: 357
Java 1
// using the VRML External Interface.
import java.applet.*;import java.awt.*;import java.util.*;import vrml.external.field.*;import vrml.external.exception.*;import vrml.external.Node;import vrml.external.Browser;import java.io.*;import java.net.*;
public class View1 extends Applet {// public static final int DEFAULT_PORT = 9877; Browser browser; Socket s = null; DataInputStream in = null; String line;
public void init() { System.out.println("Test.init()..."); } void SocketStart () throws java.io.IOException { String port = this.getParameter("port"); int p = Integer.parseInt(port); try { String host = getCodeBase().getHost(); System.out.println("Request came from: " + host); s = new Socket(host, p); } catch (UnknownHostException e) { System.out.println("No socket: " + e); } } public void start() { int count=0; Node node2sphere=null; Node appear=null; EventInSFVec3f[] scalein=new EventInSFVec3f[100] ; EventInSFColor[] appears=new EventInSFColor[100] ; float[] val = new float[3]; int[] lastval = new int[100]; int n; String id,vl;
while (count != 100) { scalein[count] = null; appears[count] = null; lastval[count] = 0; count=count+1; } try { SocketStart(); } catch (java.io.IOException e) { System.out.println("No socket: " + e); }
System.out.println("Test.start()..."); browser = (Browser) vrml.external.Browser.getBrowser(this); System.out.println("Got the browser: " + browser);
count = 0; try { in = new DataInputStream(s.getInputStream());
Mar 05, 99 11:51 Page 1/3View1.javaPrinted by Hugh Anderson
Thursday August 26, 1999 1/3
CS3283 - Hugh Anderson’s notes. Page number: 358
Java 2
while( true ) { line = in.readLine(); if (line == null ) { System.out.println(" Server closed connection."); break; } if (line.regionMatches(0," n",0,1)) { n = line.indexOf(32,2); id = line.substring(2,n);// System.out.println(">>>"+id+"<<<"); vl= line.substring(n+1);// System.out.println("+++"+vl+"−−−"); Integer a = Integer.valueOf(id); Integer b = Integer.valueOf(vl); if (scalein[a.intValue()]== null ) { try { node2sphere = browser.getNode(" node"+id+" sphere"); System.out.println(" Got the sphere node: " + node2sphere); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! node2sphere: " + e); } try { scalein[a.intValue()] = (EventInSFVec3f) node2sphere.getEventIn(" scale"); System.out.println(" Got the sphere scale node: " + appears[a.intValue()]); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! (scalein): " + e); }
try { appear = browser.getNode(" node"+id+" boxcolor"); System.out.println(" Got the Boxcolor node: " + appear); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! appearance: " + e); } try { appears[a.intValue()] = (EventInSFColor) appear.getEventIn(" set_diffuseColor"); System.out.println(" Got the Boxcolor color node: " + appears[a.intValue()]); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! appearance color: " + e); } } if (b.intValue()==−1) { val[0] = ( float )1.0; val[1] = ( float )1.0; val[2] = ( float )1.0; } else { val[0] = ( float )(b.intValue()*20)+1; val[1] = ( float )(b.intValue()*20)+1; val[2] = ( float )(b.intValue()*20)+1; } scalein[a.intValue()].setValue(val);
if ((b.intValue()==0) != (lastval[a.intValue()]==0)) { if (b.intValue()==0) { val[0] = ( float )0.8; val[1] = ( float )0.8; val[2] = ( float )0.8; appears[a.intValue()].setValue(val);
Mar 05, 99 11:51 Page 2/3View1.javaPrinted by Hugh Anderson
2/3 Thursday August 26, 1999
CS3283 - Hugh Anderson’s notes. Page number: 359
Java 3
} else { if (b.intValue()==−1) { val[0] = ( float)0.1; val[1] = ( float)0.1; val[2] = ( float)0.1; appears[a.intValue()].setValue(val); } else { val[0] = ( float)0.0; val[1] = ( float)1.0; val[2] = ( float)0.0; appears[a.intValue()].setValue(val); } } }
lastval[ a.intValue()]=b.intValue(); }// System.out.println(line); } } catch (IOException e) { System.out.println(" Reader: " + e); }
}
public Browser getBrowser() { return browser; }
}
Mar 05, 99 11:51 Page 3/3View1.javaPrinted by Hugh Anderson
Thursday August 26, 1999 3/3
CS3283 - Hugh Anderson’s notes. Page number: 360
Summary of topics
In this module, we introduced the following topics:
Visualization versus computer-graphics
OpenGL
(Briefly) Java3D, VTK
VRML/Java/EAI
CS3283 - Hugh Anderson’s notes. Page number: 361
Chapter 11
Code Samples
CS3283 - Hugh Anderson’s notes. Page number: 362
Assignment 2 - Code quality?
#!/usr/local/bin/wishif {![ info exists widgetDemo]} { error " This script should be run from the \"widget\" demo."}set w .plotcatch {destroy $w}toplevel $wwm title $w " Plot Demonstration"wm iconname $w " Plot"positionWindow $wset c $w.clabel $w.msg −font $font −wraplength 4i −justify left −text " This window ..."pack $w.msg −side topframe $w.buttonspack $w.buttons −side bottom −fill x −pady 2mbutton $w.buttons.dismiss −text Dismiss −command " destroy $w"button $w.buttons.code −text " See Code" −command " showCode $w"pack $w.buttons.dismiss $w.buttons.code −side left −expand 1canvas $c −relief raised −width 450 −height 300pack $w.c −side top −fill xset plotFont {Helvetica 18}$c create line 100 250 400 250 −width 2$c create line 100 250 100 50 −width 2$c create text 225 20 −text " A Simple Plot" −font $plotFont −fill brownfor { set i 0} {$i <= 10} { incr i} { set x [ expr {100 + ($i*30)}] $c create line $x 250 $x 245 −width 2 $c create text $x 254 −text [ expr 10*$i] −anchor n −font $plotFont}for { set i 0} {$i <= 5} { incr i} { set y [ expr {250 − ($i*40)}] $c create line 100 $y 105 $y −width 2 $c create text 96 $y −text [ expr $i*50].0 −anchor e −font $plotFont}foreach point {{12 56} {20 94} {33 98} {32 120} {61 180}
{75 160} {98 223}} { set x [ expr {100 + (3*[ lindex $point 0])}] set y [ expr {250 − (4*[ lindex $point 1])/5}] set item [$c create oval [ expr $x−6] [ expr $y−6] \
[ expr $x+6] [ expr $y+6] −width 1 −outline black \ −fill SkyBlue2]
$c addtag point withtag $item}
$c bind point <Any−Enter> " $c itemconfig current −fill red"$c bind point <Any−Leave> " $c itemconfig current −fill SkyBlue2"$c bind point <1> " plotDown $c %x %y"$c bind point <ButtonRelease−1> " $c dtag selected"bind $c <B1−Motion> " plotMove $c %x %y"set plot(lastX) 0set plot(lastY) 0proc plotDown {w x y} { global plot $w dtag selected $w addtag selected withtag current $w raise current set plot(lastX) $x set plot(lastY) $y}
CODE LISTING Page 1/1lect9.1.tcl
CS3283 - Hugh Anderson’s notes. Page number: 363
Assignment 2 - Code quality?
#!/usr/local/bin/wish## This demonstration script creates a canvas widget showing a 2−D# plot with data points that can be dragged with the mouse.## RCS: @(#) $Id: plot.tcl,v 1.2 1998/09/14 18:23:29 stanton Exp $
if {![ info exists widgetDemo]} {error " This script should be run from the \"widget\" demo."}set w .plotcatch {destroy $w}toplevel $wwm title $w " Plot Demonstration"wm iconname $w " Plot"positionWindow $wset c $w.ccanvas $c −relief raised −width 450 −height 300pack $w.c −side top −fill xset plotFont {Helvetica 18}$c create line 100 250 400 250 −width 2$c create line 100 250 100 50 −width 2$c create text 225 20 −text " A Simple Plot" −font $plotFont −fill brownfor { set i 0} {$i <= 10} { incr i} {set x [ expr {100 + ($i*30)}]$c create line $x 250 $x 245 −width 2$c create text $x 254 −text [ expr 10*$i] −anchor n −font $plotFont}for { set i 0} {$i <= 5} { incr i} {set y [ expr {250 − ($i*40)}]$c create line 100 $y 105 $y −width 2$c create text 96 $y −text [ expr $i*50].0 −anchor e −font $plotFont}foreach point {{12 56} {20 94} {33 98} {32 120} {61 180}} {set x [ expr {100 + (3*[ lindex $point 0])}]set y [ expr {250 − (4*[ lindex $point 1])/5}]set item [$c create oval [ expr $x−6] [ expr $y−6] \[ expr $x+6] [ expr $y+6] −width 1 −outline black \−fill SkyBlue2]$c addtag point withtag $item}$c bind point <ButtonRelease−1> " $c dtag selected"bind $c <B1−Motion> " plotMove $c %x %y"set plot(lastX) 0set plot(lastY) 0# plotDown −−# This procedure is invoked when the mouse is pressed over one of the# data points. It sets up state to allow the point to be dragged.## Arguments:# w − The canvas window.# x, y − The coordinates of the mouse press.
proc plotDown {w x y} {global plot$w dtag selected$w addtag selected withtag current$w raise currentset plot(lastX) $xset plot(lastY) $y
CODE LISTING Page 1/2lect9.2.tcl}
CODE LISTING Page 2/2lect9.2.tcl
CS3283 - Hugh Anderson’s notes. Page number: 364
Assignment 2 - Code quality?
#!/usr/local/bin/wish## This demonstration script creates a canvas widget showing a 2−D# plot with data points that can be dragged with the mouse.## RCS: @(#) $Id: plot.tcl,v 1.2 1998/09/14 18:23:29 stanton Exp $
set w .pxcatch {destroy $w}label $w.m −font $font −wraplength 4i −justify left −text " This window ..."pack $w.m −side topframe $w.bspack $w.bs −side bottom −fill x −pady 2mbutton $w.bs.dismiss −text Dismiss −command " destroy $w"canvas $c −relief raised −width 450 −height 300pack $w.c −side top −fill xset pf {Helvetica 18}$c create line 100 250 400 250 −width 2$c create line 100 250 100 50 −width 2for { set i 0} {$i <= 10} { incr i} { set x [ expr {100 + ($i*30)}] $c create line $x 250 $x 245 −width 2 $c create text $x 254 −text [ expr 10*$i] −anchor n −font $pf}for { set i 0} {$i <= 5} { incr i} { set y [ expr {250 − ($i*40)}] $c create line 100 $y 105 $y −width 2 $c create text 96 $y −text [ expr $i*50].0 −anchor e −font $pf}
foreach pt {{12 56} {20 94} {33 98} {32 120} {61 180}{75 160} {98 223}} {
set x [ expr {100 + (3*[ lindex $pt 0])}] set y [ expr {250 − (4*[ lindex $pt 1])/5}] set im [$c create oval [ expr $x−6] [ expr $y−6] \
[ expr $x+6] [ expr $y+6] −width 1 −outline black \ −fill SkyBlue2]
$c addtag pt withtag $im}
$c bind pt <Any−Enter> " $c itemconfig ct −fill red"$c bind pt <Any−Leave> " $c itemconfig ct −fill SkyBlue2"
CODE LISTING Page 1/1lect9.3.tcl
CS3283 - Hugh Anderson’s notes. Page number: 365
Assignment 2 - debugging?
Write code clearly: Edit, document, comment...
######################################################### GetCommandString( x,y,itemID ):string# Returns a string that is later executed as a# command# The parameters x and y are the current cursor# position, and itemID is the closest visible# item on the canvas .canv# Requires: Uses global variable canvas .canv# Ensures: Always returns a command of some sort# Sets global variable ErrorID if there is# any error...# Last modified: 12/2/2004 - by Hugh########################################################
CS3283 - Hugh Anderson’s notes. Page number: 366
Assignment 2 - debugging?
✔ Run wish, and then use source x.tcl
✔ ... then interact with running program...
CS3283 - Hugh Anderson’s notes. Page number: 367
Assignment 3
3 options:
1. Re-implement YOUR assignment 2
2. A simple (but actually useful) visualization
3. Image library assistant...
CS3283 - Hugh Anderson’s notes. Page number: 368
Assignment 3 (option a)
✔ The tricky thing is the graphics component
✔ Some help with it...
CS3283 - Hugh Anderson’s notes. Page number: 369
Java Graphics API
public void paintComponent(Graphics g) {super.paintComponent(g); //paint background//Paint a filled rectangle at user’s chosen point.if (point != null) {
g.drawRect(point.x, point.y, rectWidth-1, rectHeight-1);g.setColor(Color.yellow);g.fillRect(point.x+1,point.y+1,rectWidth-2,rectHeight-2);
}}
CS3283 - Hugh Anderson’s notes. Page number: 370
Graphics API
1. Basic/AWT - Abstract Graphics class
2. Java2D
CS3283 - Hugh Anderson’s notes. Page number: 371
Coordinate system
✔ Upper left of each component is (0,0)
✔ Behind the title bar of a window
✔ Container class has getInsets method
✔ Graphics objects contain methods for drawing
CS3283 - Hugh Anderson’s notes. Page number: 372
Graphics API
✔ Swing components have a method paintComponentwhich takes a graphics object as an argument
public void paintComponent( Graphics g )
✔ Overide this to draw your objects.
✔ Also may call the repaint() method
CS3283 - Hugh Anderson’s notes. Page number: 373
Graphics class methods
clearRect(int x, int y, int width, int height);draw3DRect(int x, int y, int width, int height, boolean raised);drawImage(Image img, int x, int y, Color bgcolor, ImageObserver observer);drawLine(int x1, int y1, int x2, int y2);drawOval(int x, int y,int width, int height);drawPolygon(int xPoints[], int yPoints[], int nPoints);drawRect(int x, int y,int width, int height);drawRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight);drawString(String str, int x, int y);
CS3283 - Hugh Anderson’s notes. Page number: 374
Graphics class methods
fill3DRect(int x, int y, int width, int height, boolean raised);fillArc(int x, int y, int width, int height, int startAngle, int arcAngle);fillOval(int x, int y, int width, int height);fillPolygon(int xPoints[], int yPoints[], int nPoints);fillRect(int x, int y, int width, int height);fillRoundRect(int x, int y, int width, int height, int arcWidth, int arcHeight);
CS3283 - Hugh Anderson’s notes. Page number: 375
Graphics class methods
Color getColor();Font getFont();FontMetrics getFontMetrics();setColor(Color c);setFont(Font font);
CS3283 - Hugh Anderson’s notes. Page number: 376
Graphics API
✔ Use JPanel instead of JComponent
✔ UI delegate (for look-and-feel painting) is called in JPanel
✔ UI delegate not called in JComponent
CS3283 - Hugh Anderson’s notes. Page number: 377
Text in Graphics API
✔ Note - you paint text using drawString()
✔ getFontMetrics() to get a FontMetrics object
getHeight()getAscent()getDescent()charWidth()
✔ and so on...
CS3283 - Hugh Anderson’s notes. Page number: 378
Assignment 3 (option b)
✔ Start with a large number (>1000000) points to beplotted, explored, displayed.
✔ If only a 1024*768 screen there are <1000000 points onscreen.
✔ In some small region with (say) 10*10 points, there mightbe no difference between a display with 100 dots and onewith 100000 dots.
CS3283 - Hugh Anderson’s notes. Page number: 379
Assignment 3 (option b)
✔ So...
✔ Tile the display
✔ Black and white? Colour?
CS3283 - Hugh Anderson’s notes. Page number: 380
Assignment 3 (option b)
CS3283 - Hugh Anderson’s notes. Page number: 381
Assignment 3 (option b)
CS3283 - Hugh Anderson’s notes. Page number: 382
Assignment 3 (option b)
CS3283 - Hugh Anderson’s notes. Page number: 383
Assignment 3 (option b)
CS3283 - Hugh Anderson’s notes. Page number: 384
Assignment 3 (option b)
✔ Must use a slider to change the tiling.
✔ May show different zoom levels, and locations of data
✔ Processing of other tilings in background using threads...(i.e. no pauses)
CS3283 - Hugh Anderson’s notes. Page number: 385
Assignment 3 (option c)
✔ Java application or a Java applet
✔ User interface to assist in the management of largenumbers of images.
✔ Principally display TEXT information (spreadsheet),
✔ May also display small (thumbnail) versions of theimages
CS3283 - Hugh Anderson’s notes. Page number: 386
Assignment 3 (option c)
✔ Database
✔ Special purpose editor for ...
✔ classifying,✔ annotating and✔ querying a large number of images.
CS3283 - Hugh Anderson’s notes. Page number: 387
Assignment 3 (option c)
✔ Image DSCN0100.JPG (Tim at a party): It is in
• “Friends”• “Trip to NZ in Dec 2003”, which is itself in the section
“Trips”• “Hooligans”
✔ Main screen shows a list of images.
CS3283 - Hugh Anderson’s notes. Page number: 388
Assignment 3 (option c)
Editable and fixed annotation fields:
• The date and time the image was entered into the section(not editable).
• A unique identifier for the image
• A scrollable text box with (say) 5 visible lines of textdescription.
CS3283 - Hugh Anderson’s notes. Page number: 389
Assignment 3 (option c)
Minimum flow of operation:
1. create, locate and delete new sections,
2. import image(s), using selection or cut and paste.
3. edit image/section information annotations,
4. save and load new databases,
5. query the system with a text search.
CS3283 - Hugh Anderson’s notes. Page number: 390
Deliverables:
✔ Single (zipped) file with sourcecode, README, docs inPDF
✔ Documentation:
✔ A title page, Table of contents...✔ A one page introduction to the application✔ A one page technical section✔ A one to three page section describing the interface
CS3283 - Hugh Anderson’s notes. Page number: 391
Assessment:
The assessment is as follows:
Documentation 15%Code style/quality 35%Operation of the interface 50%
CS3283 - Hugh Anderson’s notes. Page number: 392
Assignment 3 - code quality?
CS3283 - Hugh Anderson’s notes. Page number: 393
Debugging Java
✔ Netbeans debugger
✔ The java debugger jdb
CS3283 - Hugh Anderson’s notes. Page number: 394
Debugging Java
On suns...difficulty with versions of java and jdb and ddd
PATH=/usr/local/java/j2sdk1 3 1 02/bin:$PATH;export PATH
CS3283 - Hugh Anderson’s notes. Page number: 395
MFC
✔ Microsoft Foundation Classes - classes needed toproduce GUI Windows programs.
✔ Development cycle - RAD, then editing.
CS3283 - Hugh Anderson’s notes. Page number: 396
MFC menus
A resource file for a simple File/Quit menu:
#define MYAPP EXIT 3210MyApp MENU
POPUP “File”{
MENUITEM “Exit”,MYAPP EXIT}
}
CS3283 - Hugh Anderson’s notes. Page number: 397
Menus
In the Create call, you can do something like this:
Create( NULL, “Example”, ..., CRect(...), NULL, “MyApp” );
The MYAPPEXIT message may be bound using theDECLAREMESSAGEMAP() macro, and with the followingdeclaration:
ON COMMAND( MYAPP EXIT,OnExit )
CS3283 - Hugh Anderson’s notes. Page number: 398
Message handler
afx msg void CMenusWin::OnExit(){
SendMessage( WM CLOSE );}
CS3283 - Hugh Anderson’s notes. Page number: 399
MFC Program
CS3283 - Hugh Anderson’s notes. Page number: 400
MFC program
#include <afxwin.h>
class CFirstWindow : public CFrameWnd {public: CFirstWindow(); ~CFirstWindow(); private: CStatic *m_pGreeting; };
CFirstWindow::CFirstWindow() { Create( NULL, " First Application", WS_OVERLAPPEDWINDOW, CRect( 100, 100, 400, 220 ) ); m_pGreeting = new CStatic; m_pGreeting−>Create( " Hello World!", // text WS_CHILD | WS_VISIBLE | WS_BORDER | SS_CENTER, CRect( 80, 30, 200,50 ), this ); }
CFirstWindow::~CFirstWindow(){ delete m_pGreeting;}
class CFirstApp : public CWinApp {public: BOOL InitInstance() { m_pMainWnd = new CFirstWindow(); m_pMainWnd−>ShowWindow( m_nCmdShow ); m_pMainWnd−>UpdateWindow(); return TRUE; }
} FirstApp;
CODE LISTING FirstApp.cpp
CS3283 - Hugh Anderson’s notes. Page number: 401
Hungarian notation
Prefix Meaning
C Class declaration
m Class member variable
p Pointer
n or i Integer
On Event or message handler
CS3283 - Hugh Anderson’s notes. Page number: 402
MFC class hierarchy
CS3283 - Hugh Anderson’s notes. Page number: 403
Chapter 12
Blending...
CS3283 - Hugh Anderson’s notes. Page number: 404
FLOOPS
CS3283 - Hugh Anderson’s notes. Page number: 405
Blending languages
✔ SWIG - Simplified Wrapper and Interface Generator
✔ S/W tool that connects C and C++ with scriptinglanguages
✔ Generates wrapper code that scripting languages use toaccess C/C++.
✔ Perl, Python, Tcl/Tk, Ruby, Java, OCAML, C# ...
CS3283 - Hugh Anderson’s notes. Page number: 406
Today though...
✔ Perl and Tk
✔ C and Tk
✔ VRML and Java
✔ Java and Tk
CS3283 - Hugh Anderson’s notes. Page number: 407
Perl and Tk
✔ Have to install the Tk module for perl
✔ Download Tk-804.026.tar.gz, and then
✔ perl Makefile.pl XFT=1✔ make✔ make install
CS3283 - Hugh Anderson’s notes. Page number: 408
GUI
CS3283 - Hugh Anderson’s notes. Page number: 409
Perl/Tk code
Perl has a Tk module:
use Tk; my $currentslice = 0; my $currentpp = 0; my $disptype = 2; my $main = new MainWindow;
<<SetupMenu>> <<SetupFileMenu>> <<SetupEditMenu>> <<SetupViewMenu>>
$main−>configure(−menu =>$menubar);
<<SetupScrolledMainArea>>
MainLoop;
<<FileOpenDialogBox>>
CODE LISTING mainline.pl
CS3283 - Hugh Anderson’s notes. Page number: 410
Menu bar
$menubar = $main−>Menu; $filemenu = $menubar−>cascade(−label=>" File" ); $editmenu = $menubar−>cascade(−label=>" Operate" ); $viewmenu = $menubar−>cascade(−label=>" View" ); $helpmenu = $menubar−>cascade(−label=>" Help"); $helpmenu−>command(−command => \&about_choice, −label => " About TkMenu...", −underline => 0);
CODE LISTING SetupMenu.pl
CS3283 - Hugh Anderson’s notes. Page number: 411
Menu items
$filemenu−>command(−command => sub { fileDialog( $main, ’ open’ ); printf " Opening $thisfile\n"; readfile($thisfile); writefile($thisfile . " .ppx");}, −label => " Open...", −underline => 0); $filemenu−>separator; $filemenu−>command(−label => " Exit", −command => \&exit_choice, −underline => 1);
CODE LISTING SetUpFileMenu.pl
CS3283 - Hugh Anderson’s notes. Page number: 412
Edit menu
$editmenu−>command(−command => sub {Tp($currentslice,1,1);}, −label => " Crank with widening...", −underline => 0); $editmenu−>command(−command => sub {Tp($currentslice,1,10);}, −label => " Crank with widening (10X)...", −underline => 0); $editmenu−>command(−command => sub {Tp($currentslice,0,1);}, −label => " Crank...", −underline => 0); $editmenu−>command(−command => sub {Tp($currentslice,0,10);}, −label => " Crank (10X)...", −underline => 0); $editmenu−>command(−command => sub {Cousot($currentslice);}, −label => " Cousot...", −underline => 0); $editmenu−>separator; $editmenu−>command(−command => sub {widening($currentslice);}, −label => " Widen...", −underline => 0);
CODE LISTING SetUpEditMenu.pl
CS3283 - Hugh Anderson’s notes. Page number: 413
View menu
$viewmenu−>command(−command => sub {$disptype=0;display($currentslice,0);}, −label => " Show LRS...", −underline => 0); $viewmenu−>command(−command => sub {$disptype=1;display($currentslice,1);}, −label => " Show Actual Transform...", −underline => 0); $viewmenu−>command(−command => sub {$disptype=2;display($currentslice,2);}, −label => " Show Equations...", −underline => 0); $viewmenu−>command(−command => sub {$disptype=3;display($currentslice,3);}, −label => " Show Default Transform...", −underline => 0); $viewmenu−>command(−command => sub {$disptype=4;display($currentslice,4);}, −label => " Show Full formulae...", −underline => 0); $viewmenu−>command(−command => sub {$disptype=5;display($currentslice,5);}, −label => " Show only the program...", −underline => 0); $viewmenu−>separator; $viewmenu−>command(−command => sub { if ($currentslice>0) { $currentslice=$currentslice−1; if ($currentpp==0) { $currentpp=$codesize; } $currentpp=$currentpp−1; display($currentslice,$disptype); }}, −label => " Go back...", −underline => 0); $viewmenu−>command(−command => sub { if ($currentslice+1<$maxslice){ $currentslice=$currentslice+1; $currentpp=$currentpp+1; if ($currentpp==$codesize) { $currentpp=0; } display($currentslice,$disptype); }}, −label => " Go forward...", −underline => 0);
CODE LISTING SetUpViewMenu.pl
CS3283 - Hugh Anderson’s notes. Page number: 414
Dialog box
sub exit_choice { exit; }
sub fileDialog { my $w = shift; my $operation = shift; my $types; my $file; @types = ([" Code files", ’ .pp’], [" Work files", ’ .ppx’], [" All files", ’ *’] ); $file = $w−>getOpenFile(−filetypes => \@types); if ( defined $file and $file ne ’’) {
$thisfile = $file; } }
CODE LISTING FileOpenDialogBox.pl
CS3283 - Hugh Anderson’s notes. Page number: 415
Code
http://www.comp.nus.edu.sg/˜cs3283/ftp/original.pl
It may be run by typing “perl original.pl ”.
CS3283 - Hugh Anderson’s notes. Page number: 416
C and Tk
✔ There are various ways...
✔ Call C within Tk✔ Call Tk within C✔ Communication
CS3283 - Hugh Anderson’s notes. Page number: 417
C and Tk
✔ This one is a C program
✔ It loads and runs a Tk program along with its interpreter.
✔ Tk in turn can call-back C procedures if needed
CS3283 - Hugh Anderson’s notes. Page number: 418
Viewer
CS3283 - Hugh Anderson’s notes. Page number: 419
C and Tk
#include <stdio.h> #include <tcl.h> #include <tk.h> char tclprog[] = " \ proc fileDialog {w} {\ set types {\ { \"Image files\" {.gif} }\ { \"All files\" *}\ };\ set file [tk_getOpenFile −filetypes $types −parent $w];\ image create photo picture −file $file;\ set glb_tx [image width picture];\ set glb_ty [image height picture];\ .c configure −width $glb_tx −height $glb_ty;\ .c create image 1 1 −anchor nw −image picture −tags \"myimage\";\ };\ frame .mbar −relief raised −bd 2;\ frame .dummy −width 10c −height 0;\ pack .mbar .dummy −side top −fill x;\ menubutton .mbar.file −text File −underline 0 −menu .mbar.file.menu;\ menu .mbar.file.menu −tearoff 1;\ .mbar.file.menu add command −label \"Open...\" −command \"fileDialog .\";\ .mbar.file.menu add separator;\ .mbar.file.menu add command −label \"Quit\" −command \"destroy .\";\ pack .mbar.file −side left;\ canvas .c −bd 2 −relief raised;\ pack .c −side top −expand yes −fill x;\ bind . <Control−c> {destroy .};\ bind . <Control−q> {destroy .};\ focus .mbar"; int main (argc, argv) int argc; char **argv; { Tk_Window mainWindow; Tcl_Interp *tcl_interp; setenv (" TCL_LIBRARY", " /cygnus/cygwin−b20/share/tcl8.0"); tcl_interp = Tcl_CreateInterp (); if (Tcl_Init (tcl_interp) != TCL_OK || Tk_Init (tcl_interp) != TCL_OK) { if (*tcl_interp−>result) ( void) fprintf (stderr, " %s: %s\n", argv[0], tcl_interp−>result); exit (1); } mainWindow = Tk_MainWindow (tcl_interp); if (mainWindow == NULL) { fprintf (stderr, " %s\n", tcl_interp−>result); exit (1); } Tcl_Eval (tcl_interp, tclprog); Tk_MainLoop (); exit (1); }
CODE LISTING CplusTclTk.c
CS3283 - Hugh Anderson’s notes. Page number: 420
Compilation
On a Win32 system, we compile this as:
gcc -o myexe CplusTclTk.c -mwindows -ltcl80 -ltk80
On a UNIX system we use:
gcc -o myexe CplusTclTk.c -ltk -ltcl -lX11 -lm -ldl
CS3283 - Hugh Anderson’s notes. Page number: 421
VRML and Java
VRML is a scene description language
“The EAI allows you to control the contents of a VRMLbrowser window embedded in a web page from a Java(tm) applet on the same page.”
http://www.frontiernet.net/˜imaging/eaifaq.html
(People poser and Tiny3D are OK but there are problems...)
CS3283 - Hugh Anderson’s notes. Page number: 422
VRML and Java3DVNT
CS3283 - Hugh Anderson’s notes. Page number: 423
VRML software
<html> <head> <title>Sample 3DVNT Page</title> </head><center><H1>Sample 3DVNT Page </H1></center><center> <embed src="root.wrl" height="600" width="700"> </center><center> <applet code="View1.class" width="100" height="10" mayscript><PARAM name="segment" value="MACS"> <PARAM name="port" value="9876"><PARAM name="host" value="opo.usp.ac.fj"> </applet> </center>OK?</html>
CODE LISTING Page 1/1defaulthtml.txt
CS3283 - Hugh Anderson’s notes. Page number: 424
The root.wrl file
PROTO CLUSTER [] { ... } # Cluster definitionPROTO KEYBOARD [] { ... } # Keyboard definitionPROTO SCREEN [] { ... } # Screen definitionPROTO GLOBE [] { ... } # Traffic sphere definition# Some setting up declarationsBackground { skyColor .4 .66 1 }NavigationInfo { type [ "EXAMINE", "ANY" ] speed 400 }Viewpoint { position 0 400 0 orientation 0 1 0 4 description "Camera 1" }# Lines, floors and roofsDEF LINES Transform { ... }DEF FLOORS Transform { ... }DEF ROOFS Transform { ... }# and then the nodesDEF node1 Transform { ... }DEF node2 Transform { ... } # ... and so on ...
CODE LISTING Page 1/1root.wrl
CS3283 - Hugh Anderson’s notes. Page number: 425
VRML nodes
DEF node1 Transform { translation 4350 150 4365 rotation 0 1 0 4.71238 children [ KEYBOARD {} SCREEN {} DEF node1box Transform { children [ Shape { appearance Appearance {
material DEF node1boxcolor Material { diffuseColor 0.8 0.8 0.8 }
} geometry Box { size 50 50 50 } }
] } DEF node1sphere Transform { scale 1 1 1 children [ Shape { appearance GLOBE {} geometry Sphere { radius 1 } }
] } ]}
CODE LISTING Page 1/1node.wrl
CS3283 - Hugh Anderson’s notes. Page number: 426
Java
The java software maintains a link to a remote data collector,
Uses the EAI to modify the images in the VRML view.
CS3283 - Hugh Anderson’s notes. Page number: 427
Java 1Java 1
// using the VRML External Interface.
import java.applet.*;import java.awt.*;import java.util.*;import vrml.external.field.*;import vrml.external.exception.*;import vrml.external.Node;import vrml.external.Browser;import java.io.*;import java.net.*;
public class View1 extends Applet {// public static final int DEFAULT_PORT = 9877; Browser browser; Socket s = null; DataInputStream in = null; String line;
public void init() { System.out.println("Test.init()..."); } void SocketStart () throws java.io.IOException { String port = this.getParameter("port"); int p = Integer.parseInt(port); try { String host = getCodeBase().getHost(); System.out.println("Request came from: " + host); s = new Socket(host, p); } catch (UnknownHostException e) { System.out.println("No socket: " + e); } } public void start() { int count=0; Node node2sphere=null; Node appear=null; EventInSFVec3f[] scalein=new EventInSFVec3f[100] ; EventInSFColor[] appears=new EventInSFColor[100] ; float[] val = new float[3]; int[] lastval = new int[100]; int n; String id,vl;
while (count != 100) { scalein[count] = null; appears[count] = null; lastval[count] = 0; count=count+1; } try { SocketStart(); } catch (java.io.IOException e) { System.out.println("No socket: " + e); }
System.out.println("Test.start()..."); browser = (Browser) vrml.external.Browser.getBrowser(this); System.out.println("Got the browser: " + browser);
count = 0; try { in = new DataInputStream(s.getInputStream());
Mar 05, 99 11:51 Page 1/3View1.javaPrinted by Hugh Anderson
Thursday August 26, 1999 1/3
CS3283 - Hugh Anderson’s notes. Page number: 428
Java 2
while( true ) { line = in.readLine(); if (line == null ) { System.out.println(" Server closed connection."); break; } if (line.regionMatches(0," n",0,1)) { n = line.indexOf(32,2); id = line.substring(2,n);// System.out.println(">>>"+id+"<<<"); vl= line.substring(n+1);// System.out.println("+++"+vl+"−−−"); Integer a = Integer.valueOf(id); Integer b = Integer.valueOf(vl); if (scalein[a.intValue()]== null ) { try { node2sphere = browser.getNode(" node"+id+" sphere"); System.out.println(" Got the sphere node: " + node2sphere); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! node2sphere: " + e); } try { scalein[a.intValue()] = (EventInSFVec3f) node2sphere.getEventIn(" scale"); System.out.println(" Got the sphere scale node: " + appears[a.intValue()]); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! (scalein): " + e); }
try { appear = browser.getNode(" node"+id+" boxcolor"); System.out.println(" Got the Boxcolor node: " + appear); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! appearance: " + e); } try { appears[a.intValue()] = (EventInSFColor) appear.getEventIn(" set_diffuseColor"); System.out.println(" Got the Boxcolor color node: " + appears[a.intValue()]); } catch (InvalidNodeException e) { System.out.println(" PROBLEMS! appearance color: " + e); } } if (b.intValue()==−1) { val[0] = ( float )1.0; val[1] = ( float )1.0; val[2] = ( float )1.0; } else { val[0] = ( float )(b.intValue()*20)+1; val[1] = ( float )(b.intValue()*20)+1; val[2] = ( float )(b.intValue()*20)+1; } scalein[a.intValue()].setValue(val);
if ((b.intValue()==0) != (lastval[a.intValue()]==0)) { if (b.intValue()==0) { val[0] = ( float )0.8; val[1] = ( float )0.8; val[2] = ( float )0.8; appears[a.intValue()].setValue(val);
Mar 05, 99 11:51 Page 2/3View1.javaPrinted by Hugh Anderson
2/3 Thursday August 26, 1999
CS3283 - Hugh Anderson’s notes. Page number: 429
Java 3
} else { if (b.intValue()==−1) { val[0] = ( float)0.1; val[1] = ( float)0.1; val[2] = ( float)0.1; appears[a.intValue()].setValue(val); } else { val[0] = ( float)0.0; val[1] = ( float)1.0; val[2] = ( float)0.0; appears[a.intValue()].setValue(val); } } }
lastval[ a.intValue()]=b.intValue(); }// System.out.println(line); } } catch (IOException e) { System.out.println(" Reader: " + e); }
}
public Browser getBrowser() { return browser; }
}
Mar 05, 99 11:51 Page 3/3View1.javaPrinted by Hugh Anderson
Thursday August 26, 1999 3/3
CS3283 - Hugh Anderson’s notes. Page number: 430
Java/Tk code
✔ As for C.... we have
✔ Java calls to Tk✔ Tk calls to Java
✔ Partial implementation of Tk inside Java/Swing
CS3283 - Hugh Anderson’s notes. Page number: 431
Tk code
CS3283 - Hugh Anderson’s notes. Page number: 432
Java/Tk code
CS3283 - Hugh Anderson’s notes. Page number: 433
Tk code
canvas $c −relief raised −width 450 −height 300 set plotFont {Helvetica 18}... $c create line 100 250 100 50 −width 2 $c create text 225 20 −text " A Simple Plot" −font $plotFont −fill brown... for { set i 0} {$i <= 10} { incr i} { set x [ expr {100 + ($i*30)}] $c create line $x 250 $x 245 −width 2 $c create text $x 254 −text [ expr 10*$i] −anchor n −font $plotFont }... $c bind point <Any−Enter> " $c itemconfig current −fill red"... proc plotMove {w x y} { global plot $w move selected [ expr $x−$plot(lastX)] [ expr $y−$plot(lastY)] set plot(lastX) $x set plot(lastY) $y }
CODE LISTING Page 1/1tkplot.tcl
CS3283 - Hugh Anderson’s notes. Page number: 434
The JavaKit code
C = new canvas(jf, width, height, bgColor); plotFont = " −font [fontName Helvetica fontSize 18 fontStyle plain]";... C.create(" −item line −coords [100 250 100 50] −width 2.0"); C.create(" −item text −coords [225 20] −text \"A Simple Plot\" " + plotFont );... for( int i = 0; i <= 10; i++) { int x = 100 + (i*30); C.create(" −item line −coords [" + x + " 250 " + x + " 245] −width 2.0"); C.create(" −item text −coords [" + (x+9) + " 264] −text " + (10*i) + " " + plotFont ); }... C.bind(" point", new command(" enter") { public void action(eventInfo ei) { C.itemConfig(" current", " −fill red"); }});... public void plotMove(canvas w, double x, double y) { w.move(" selected", x − lastX, y − lastY); lastX = x; lastY = y; }
CODE LISTING Page 1/1tkplot.java
CS3283 - Hugh Anderson’s notes. Page number: 435
Summary of topics
✔ Tk blended with C
✔ Tk blended with perl
✔ VRML, Java and the EAI
✔ Tk blended with Java
CS3283 - Hugh Anderson’s notes. Page number: 436
Outline
1 Module 1 - GUI concepts
2 Module 2 - Design
3 Architecture
4 First steps
5 Tcl/Tk - 1
CS3283 - Hugh Anderson’s notes. Page number: 437
6 Tcl/Tk - 2
7 Tcl/Tk - 3, Java
8 Java continued
9 Module7
10 Module 8
11 Code Samples
12 Blending...
CS3283 - Hugh Anderson’s notes. Page number: 438