Chapter Outline
Programming for X
Copyright © 2001 by James L. Fuller, all rights reserved.What is X?
X Server
X Window Manager
X Protocol
Xlib
X Clients
X Toolkits
The X Programming ModelStart Up
The Tk Toolkit
Main Loop
Clean UpWindows Programming
An Application in Tk
Configuration Files
Tk Widgets
Bindings
Geometry Management
Option Database
Inter-application Communication
Window Manager
Miscellaneous CommandsInput
Java
Output and Requirements
What do We Need to Code?
The Bitmap File
Where Now?Where Did Java Come From?
What is Java?
Applications and Applets
PackagesX Programming with Java Summary Lecture Notes
Programming for X
Now we look at writing programs to run thhe UNIX graphical environment, the X Windows system.
Here are some of the things from a programmer's view of X that we will look at.
![]()
What is X?
X was created at MIT as a way of providing a uniform environment for graphical programs.
The X Windows system comprise four major components that we'll briefly mention in turn.
These are:
![]()
X Server
The X server, or X display server, is a program that runs on the application user's computer and is responsible for controlling the graphical display hardware and looking after input and output.
X Protocol
All interaction between X client applications and the X display server take place via message exchanges.
Xlib
Most X applications ultimately use a C function library (Xlib) as a programming interface.
X Clients
X clients are application programs that use the display and input resources of a computer that may not be the one they're running on.
X Toolkits
Collections of elements, also known as widgets, are generally called X toolkits, are available to help make programming X program applications easier.
![]()
xedit is a very simple editor that runs under X but doesn't make use of X toolkits.
![]()
textedit was written with the OpenLook toolkit and has a better user interface.
![]()
X Window Manager
The X window manager is a special X client that is responsible for dealing with other clients.
Examples of window managers are:
![]()
The X Programming Model
The X programming model, does some initializing, has a loop for controling events, and does some clean up.
![]()
Start Up
A typical X application will start by initializing any resources it may need.
XOpenDisplay and XCloseDisplay are used by client programs for connecting to and disconnecting from an X server.
![]()
The environment variable DISPLAY is used to direct the application to a particular display server.
$ DISPLAY=alex:0.0 xedit &
The file .Xresources is used to configure the X application.A typical entry in a user's .Xresources file, stored in his or her home directory might be:
![]()
This entry changes the behavior of edit with respect to making backup files while editing.
Each entry has the general format:
![]()
Main Loop
The bulk of an X application is made up of a main loop and code written to react to events.
There are over 30 events that an application may have to deal with. Here are three typical ones.
![]()
Clean Up
when it exits, a well-behaved X program will free up any X display resources it has allocated while it was running.
Fast Track X Programming
We will use interpreted languages such as Tcl and the Tk (Tool Kit) extensions to make X programs.
The Tk Toolkit
Tk, creted by John Ousterhout to be the companion of Tcl, is a rich collection of graphical user interface abstractions.
Most scripts for UNIX windows should work under MS-Windows or on the Macintosh. However, some UNIX window manager's features are not implemented under MS-Windows or Macintosh.
![]()
Over the next few sections, we'll take a look at:
![]()
Windows Programming
Using Tk, you can quickly create a graphical interface, using the widgets provided to deal with the underlaying window system.
For example, the widget command,
![]()
creates a new widget and a widget command named .b.
You can use this new command to communicate with the widget, so,
![]()
will set the title of the button .b to Hello.
![]()
Try It Out - Saying Hello
Type in the following script file:
![]()
Make the script executable and run the hello1.tk program:
$ hello1.tk
This program creates the window shown below and outputs the string Hi each time you click on the button.![]()
How It Works
The program creates a multiple line label on a large button.
Configuration Files
Now let's add one more line before the widget's creation:
![]()
Now the button is created with teh default activeforeground color set to brown
![]()
We can also make it into a more realistic X application by saving the line,
![]()
into a file called hello.def, and then adding the following line into the hello3.tk script before we create the widget:
![]()
More Commands
Now to do some event binding. If the user presses Ctrl along with the mouse button, the widget will output the string Help!.
Here's how to do this:
![]()
Our final Hello World program, hello4.tk, with all these modifications, reads:
![]()
Tk Widgets
Here's a simple way to find out all the methods and arguments a widget provides. Note that the symbol % denotes Tk's wish command shell prompts.
Try It Out - Learning More
1. First interactively create a scale widget .s:
$ wish
2. Call the config method of the widget and see its output to check out what the widget offers:
% scale .s
.s% .s config
You should see this output:![]()
Each list pair follows this combination:
![]()
Frames
Frames are the simplest of all the Tk widgets. They are only used as containers, as you can see in the following example:
![]()
This scripts creates five frames with different 3D boarders:
![]()
How It Works
In the above, the -relief option is used to set the border relief of the frame, while the -bd 2 option sets the widget border width ti two pixels..
Toplevel
Toplevel widgets are like frames, except they have their own toplevel windows, whereas frames are internal windows within a toplevel.
The following:
% toplevel .t -width 1.5i -height 1i -relief ridge -bd 4
will create a toplevel window that looks like the following:![]()
Labels
A label is simple widget which can display multiline text.
We can create a lebel using the label command:
% label .l -wraplength 1i -justify right -text "Hello Tk World!"
This creates a multiline label widget with a text length of one inch for each line.Once you pack the label using,
% pack .l
it will create a widget which looks like this:![]()
Buttons
Tk provides three kinds of buttons, ordinary push buttons, check boxes, and radio buttons.
Try It Out - A Choice of Buttons
1. After the script header and a couple of global variables, we create a check button.
![]()
2. Next, we create a radio button panel, with one button for each language:
![]()
3. We need two push buttons to control the output:
![]()
4. Having configured the buttons, we need to arrange them on screen. It's time for a bit of geometry management.
![]()
5. The check button needs a callback procedure, changeState. This was called by the check button's -command option.
![]()
6. The push buttons need a similar procedure, showVars:
![]()
When you run the program, you should see this:
![]()
How It Works
The program starts off by setting up two global variables, lang and state, to serve as the initial values of the check boxes and radio buttons.
Then the program composes the radio button and two push buttons.
![]()
Messages
Messages are similar to abels and are used to display multiple text. They automatically break the text up into lines.
Message widgets can justify the text displayed and they can also handle non-printable characters.
![]()
This example will create a simple message widget containing control characters.
![]()
Entrys
entrys are single line text widgets which we can use to type in and is play a single line of text.
Try It Out - Gaining Entry
Now let's look like a program, login.tk, which handles user logins.
1. First, set up the look of the login window. We also define a global loginName variable:
![]()
2. Then we select all the text from .nameEntry:
![]()
3. Lastly, we arrange the widgets on the screen--We'lll explain it later!
![]()
If you run the program, you'll see this:
![]()
How It Works
It creates two lables and two entry widgets on the screen in agrid.
![]()
Here are a few of the more common key bindings.
![]()
List Boxes
A list box widget can display a collection of strings and allows the user to select one or more items.
Try It Out - Lists
1. First we create the user-interface elements:
![]()
2. To give widgets that Motif-ish look and feel, we use the grid geometry manager:
![]()
3. We initialize the list box with the contents of the current directory:
![]()
4. We bind an event hand;er to the list box.
![]()
If you run the program, you'll see this:
![]()
How It Works
The program creates two scrollbars and then attaches them to the list box.
Scrollbars
Scrollbars are usually connected to other widgets.
In the list box example, the viewing area is controlled by the two scrollbars, .h and .h, like this:
scrollbar .h -orient horizontal -command ".list xview"
scrollbar .v -command ".list yview"Scales
Scales display an integer value and allow the user to select that value by moving a slider.
Here is a simple example progra.
![]()
When you run this program, you'll see this screen:
![]()
Here, the scale and the entry share an implicit interconnection through the global variable foo.
![]()
Text
Text widgets support three types of annotations: tag, marks, and embedded windows.
![]()
Try It Out - Manipulating Text
Leet's look at a demonstration of some of the text widget features.
1. First we create a vertical scrollbar which we attach to the text widget.
![]()
2. We want to create embedded windows.
![]()
3. We configure all the tags that we're going to associate with the text window:
![]()
4. We insert the text with those tags to show off the widget's potential.
![]()
Here is the output from running the program.
![]()
How It Works
The text window and a scrollbar are created and managed to create the basic interface.
![]()
We then insert text using tags with the following format:
![]()
Indices have the syntax:
![]()
The base for the index must have one of the following forms:
![]()
Modifiers can have these forms:
![]()
In text, indices can also be tags and marks, so the text command:
![]()
will insert the text right justification at the end of all the text in text widget and will right justify it.
![]()
Canvases
Tk's canvas widget is used to implement structured graphics.
When we create any item on the canvas, we specify its location. The locations are floating point numbers optionally suffixed with one of the letters m, c, i, p:
![]()
In the following commands, the pathName identifier refers to the canvas path name:
![]()
The following command is similar to the -configure widget command.
![]()
This command will return the type of first item in the list of items referred to by tagOrId.
![]()
This is like the bind command, but instead of applying the sequence to the whole canvas, it just applies to the item specified by tagOrId.
![]()
If neither sequence nor command is given, all the sequences bound to the itme are returned. For example:
![]()
Try It Out -Text on Canvas
Here is a sample program showing a few of the canvas features.
1. We create the canvas and then some objects to display on it.
![]()
2. We bind the canvas so that we can operate on the items shown on it.
![]()
3. For the procedures' benefit, we need to define tow global variables, lastX and lastY.
![]()
This program produces this output:
![]()
How It Works
We created a few canvas item types and bound the mouse buttons so that the user could move them with the mouse.
For example, the line,
![]()
creates an image on the canvas at location (150, 150).
Here are a few of the canvas object properties:
![]()
Images
Tk can display images of two built in types: photo and bitmap.
The general format of the image command is:
![]()
Try It Out - Manipulating Images
Here is an example program called image.tk.
1. We create the image, then confige the frame to hold the pieces of the image in the form a of a puzzle.
![]()
2. Now we create the individual pieces of the puzzle.
![]()
3. We have the event handler that deals with the user's input.
![]()
Here is the output from the puzzle program.
![]()
How It Works
We create a photo image and copy portions of it on to the buttons. The rest of the program deals with event handlers to arrange the buttons when the user clicks on them.
Option Menus
Tk's option menu is written completely in Tk to emulate the Motif option button and has the following syntax:
![]()
Try It Out - Menu Options
Let's use the option buttons to re-implement our earlier buttons example.
1. We set the global variable state equal to 1, create a check button and an options menu.
![]()
2. We need a procedure to handle the application's event:
![]()
the line
set lang C++
sets the selection to C++ by setting the variable.Here is what the output ot the program looks like:
![]()
Dialogs
dialogs are used extnesively in a user interface design cycle.
Tk provides a custom dialog called tk_dialog, which has the syntax:
![]()
Here's a somple example program:
![]()
Bindings
Bindings are used to attached event handlers to widgets.
The general syntax is:
![]()
The tag argument determines to which window or window class the binding applies.
The first form returns all the bindings associated with the tag:
![]()
The second form of bind command on one of these bindings:
![]()
says that key-space binding in the button widget class will invoke the Tcl script tkButtonInvoke with the button path as the argument.
Geometry Management
The Geometry manager arranges the widgets on the screen.
Tk currently supports three explicit geometry managers:
![]()
Packer
We use the pack command to arrange the slave widgets of a master window or widget in order around the edges of the master.
The syntax of the pack command is one of these forms:
![]()
Let's look at an example and explore some of the pack options:
![]()
This will produce the following output:
![]()
Here is one more pack sequence:
![]()
Here is its output:
![]()
Placer
Placer geometry manager is used for fixed placement of windows.
The following code fragment shows how the buttons are created in the puzzle.
![]()
If you decipher the loop code, you'll see how all the buttons are arranged to form the puzzle.
![]()
Grid
The grid geometry manager arranges widgets (slaves) in rows and columns inside another window, called the geometry master.grid.
Let's see how simple it is to creatre an entry for personnel information using ten lines of Tk code:
![]()
Here is the output of the above program:
![]()
Option Database
Just as in Motif or Xt, every widget in Tk has a class which can be retrieved using the command:.
![]()
Tk uses a special database, called the option database, to store and retrieve application resources.
For example, in the very first program, we used the line:
option add *b.activeForeground brown
We could specified the button class instead and still has the same effect:![]()
We can use the option command to query the options stored, using the syntax:
![]()
We can use option database to simulate the same application default loading mechanism that is supported by any XT-based application. The code for this emulation would look something like this:
![]()
Inter-application Communication
Tk provides a mechanism for two applications which share the same display server to communicate with each other, using the send command.
For example, application a can send application b a command to output the string Hello:
![]()
Window Manager
Tk provides the wm command so that windows can communicate with the window manager. For example:
![]()
This command will iconify the toplevel window.
Miscellanous Commands
Tk provides the winfo command which can be used to retrieve information about windows managed by Tk. For example.
![]()
will return all the children of the parent.
![]()
An Application in Tk
Let's design a small Tk application to display bitmaps.
Input
The input for the program will be a bitmap file.
Output and Requirements
We have to display the bitmap.
What do We Need to Code?
The basic functions we need to code are:
![]()
Try It Out - The User Interface
Here is the code.
1. Let's first add in some global variables:
![]()
We need two variables bitmapData and bitmapArray to sot==tore the bitmapData.
![]()
2. We design the application user interface. This consists of a menu:
![]()
3. We add a Motif-like status bar at the botton of the window.
![]()
4. We use the grid geometry manager to ensure that the application resizes as the master window is altered.
![]()
After the geometry management, the interface should look like:
![]()
How It Works
This routine creates a menu bar and adds two menu buttons.
![]()
Try It Out - Updating Status and Loading Files
Here is the support functions.
1. We need to write the code for displaying status messages:
![]()
2. The loadFile callback function, which creates the .load dialog:
![]()
3. We also want a routine todisplay error or information message. For this we use Tk's internal dialog box:
![]()
4. We use the showMessage procedure that we've just created to show the version menu entry:
![]()
The second of these routines creates a toplevel window and creates a simple interface that looks like this:
![]()
How It Works
The Load button loads the file, parses it and displays it in the camvas.
![]()
The Bitmap File
The parsing of the bitmap uses more Tcl than Tk.
Here is what a simple bitmap file looks like.
![]()
When you display it, the bitmap file will look like this:
![]()
so, while we're parsing the file, we need to look for:
![]()
Try It Out - Parsing the Bitmap File
Let's see how we code this.
1. We redeclare the variables, unset the data they contain before loading the bitmap file passed as an argument.
![]()
2. Now for the big parsing routine that dissects thge bitmap file:
![]()
3. Now we deal with C-comments:
![]()
4. We read in the contents of the bitmap file.
Once the parsing is complete, we call the display routine, displayBitmap.
![]()
5. Wee delete any bitmap currently display and draw small rectangles on the canvas.
![]()
6. We read bitmapData and create bitmapArray.
![]()
7. Here is the main application code that runs the buildInterface function.
![]()
when we load the file 1x1, the program displays the following image:
![]()
How It works
The guts of the code, parseAndDisplayBitmapfile, eliminates lines with comments and looks for #defined lines to collect the information.
![]()
Once the data is collected, the data is in the format:
![]()
We need to split this list to eliminate the curly braces.
After all this processing, bitmapData looks like:
![]()
Where Now?
There is the Tk Widget Tour with its examples of how to use the Tk widget set. Run the program by typing widget.
Tix
Tix extends Tk with over 40 professional Motif look-and-feel widgets.
[incr Tcl]
{incr Tcl] and [incr Tk] form an objected oriented extension to Tcl/Tk.
BLT
The BLT-2.1 toolkit extends Tk by providing many new widgets.
Java
It can be used to develop graphical programs for hte X Window system.
Where Did Java Come From?
Java came from Sun as a project for set top control box for home interactive TV.
What Is Java?
Java is: A simple, object-orientated, distributed, interpreted, robust, secure, architecture neutral, portable, hifh-performance,multithreaded and dynamic language.
Applications and Applets
Java applets are executed as an embedded program inside a web browser.
Packages
Java has built-in libraries or packages. The principal ones are:
![]()
X Programming with Java
Java has an Abstract Windowing Toolkit, AWT.
Try It Out - An Example Java Program
Here is an example of X programming usinng Java.
1. First we state that we wish to have access to all classes in the AWT package.
![]()
2. We implement our main class, blp_demo. We declare some private variables.
![]()
3. Here is the start of the class constructor.
![]()
4. First, we call the parent class with the title to add it to the title bar of the window:
![]()
5. We now create some window objects called panels.
![]()
6. Next is a menu bar, to which we add some menu items:
![]()
7. We can now start creating 'real' window objects and adding them to the panels that we creaated earlier:
![]()
8. We add the panels to the window.
![]()
9. We overload the event handling function.
![]()
10. We check whether open and if so, invoke the FileDialog method.
![]()
11. Lists maintain a record of which elements are selected. We simply ask for the list and then display each one in turn:
![]()
12. If you want to be able to close your windoow in a clean way, trapping the WINDOW_DESTROY event is a good idea!
![]()
13. If we haven't handled the event, it's important to pass the event on to the parent class, tp allow the parent an opportunity to handle it.
![]()
14. This 'signature' public static void main(String[]) is the trigger for Java to know where to start execution.
![]()
15. We create the blp_demo class, resize it, then call show to put it on the screen.
![]()
Try It Out - Java Dialog
Now for the dialog code. This is in a file demo_dialog.java.
1. This is a similar arrangement to the main code, but rather simpler:
![]()
2. In the dialog box, we need much simpler event handling. We make our own by declaring an action function.
![]()
3. Again, we must catch the WINDOW_DESTROY event, to ensure the window can be closed.
![]()
We compile the two programs.
![]()
This creates two file: bip_demo.class and demo_dialog.class.
Finally we execute the code by invoking the Java interpreter on the main class:
java blp_demo
Here is the output from executing the program:![]()
![]()
Summary
This chapter looked at doing X windows programming useing Tk and Java.
CS 248 - UNIX Programming Web Site Menu
Information | Syllabus | Schedule | Online "Lectures" | Projects | Quizzes | Web Board