Few Things to Note

You can assign multiple variables to a sequence (Chapter 12). Thelocals () built-in function (Chapter 9) returns a arctroaery that contains the variables in a local namespace, so the statement > > > locals() lname The format string operatot works with dKtionaries oh s eque f (Chapter 3). Here we demonstrate that split () and splitfields () do the same thing 'Bill,Gates,123', 'Main', 'St.,', 'WA,', '65743' > > > splitfields(input_string) 'Bill,Gates,123' , 'Main', 'St.,', 'WA,',...

Little

Before you add the directory to the PATH statement, make sure there art no older versions of the J2SE already mere. If there are, they'll be executed inste ad off C f'2se1.3. Once you've installed me J2SE and edited rhp autoexec. bat file, reboot your PC. TPes, to test that ever tPihf is okay, go to the DOS prompt, and enter java -version at tPa command line. You should see the following Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.0-b92) Java Hot Spot(TM) Client VM (build...

Quick and Dirty JDBC Session

Naturally I don't know what database you have access to, ro on this b ook's Web spe I'm u sing two stardaads Microsoft Access ard va I nstartDB. The exercises should wook with any SQL dathbase) as tong as h has JDBk support. You may have to eweak che statements a little, but after this chapter you should feel comfortable with that. For Microsoft Access weye going to use the JDBk-ODB k bridge, which mtegrate s ODBk- compliant databases with Java applications. pODBk stdnds foe Open Database...

Simple Example

Lei's sty iTti you're lookis. tor t 1oIi is tte eewsnl er tsd . i've decideU so satrow yof focuo So ids iTti sty, Mosey is so object. This is ilte iiatrernyo u're setrcTinf for, ind of course you're lookis. is ite em 1oymesi sectios, wticT is tte erof of cTtrtciers you're seircTise is. You Yos'i cire where you fisd your ftters, osiy ihti it's ihere. If you were writirg a Python program to help you fird a job, it would start out looking like this mino compile(money is no object) Lei's work...

String Parsing Example

To cod ane Java and Python strirg paetmg, we're going to crrore k readable five consisting of a cummh-delimited list of house prices. 100000,100000,12 0000,15 0000,17 0000,17 0000,80000,50000 Here's the Python code broken down Opes tte file. > > > file open(data.txt) Id ort tit split() function to parse the data. > > > from string import split > > > housePrices split(data, ,) For demonstration, show that split () has split the data string into a list of strings. '100000',...

Very Short History

Python was derived from a lynguage caUed ABC created by Guidn van Itossum nad others in the early 1980s. The hope was that ABC's designed-in ease of use would become popular with novices as a way to get up to programming speed quickly and painlessly. This hope didn't pan out, so van Rossum began a new project, Python, which was released in 1990. He didn't forget ABC in fact, there's a lot of ABC in Python's concise syntax and elegant expression, as well as in its ease of use. The formula worked...

About Java Beans

JavaBeans have properties and events, much like ActiveX controls, which are a lot like OLE controls (OCXs), which are like Visual Basic controls (VBX). To make a short story long, JavaBeans allow IDE (Integratsd Development Environments) to do mundane things that you used to have to write code foa. In Java, you need the set() and get() matdo ds to define a property. Let' s oay tdetyou create a property calledname that your watrt to be broth read and write. You can define two methoac for it....

Accessing Data

To access the names and ages in our table we queiy the results object (an instance of j ava .sql. ResultSet), which uses the following methods next () iterates through the table returns 1 if there are more rows getString () gets the name specified in the name string passed to it getInt() gets the age specified in the age string passed to it > > > results statement.executeQuery(select name, age from Person) Let's see how these methods work interactively. > > > results.getString(name)...

Actions

Any introduction to JToolBar has to include them. I held off until now because actions are a Tigheo abstadction than components, ard I thought you should ii v a gird grip on comtopePis first. Think of ar action as a command. An item on a menu tiat says remove address is one example another is a button on a toolbar that says the same thing. The main difference is that ar action added to a toolbar usually becomes a button ard an actton added to a menu usually...

Adding a Main Window First

We're going to create the main window for the address book application, which will have the list on the left side of the frame when the usee selects an item, it appears in the AddressForm instance on the right side. To do this we'll convert AddressForm so that it extends j ava. awt. Panel instead of j ava. awt . Frame. We'll also need to add some code to initialize the text fields in the AddressForm class (in AddressFarm.py) so that every time an address is passed to Addre ssForm (that is, when...

Adding a Main Window for the Address Book Application Prototype

The main window will have a fet of name s from the addrs ss book. As you selcct a name from the list, an AddressForm insSbfce pops up unwlndiyou edit the Address instance corrstdondrrcg to that name. As a rule, code written to access data shouldn't be in the same module with code written to build GUIs, so first we have to break our code into separate modules AddressForm.py holda the AWT versron of AddressForm Address 7.py holds the address daga code AddressMain.py holds the mein window of the...

Adding a Toolbar and a Dialog for the Address Book Application

We want to be able to add new addresses to the address list. Essentially, that means two new buttons, Add and Remove, which we'll put in a new panel in the north region of the main frame. (See Figure 14-3.) When the user presses the Add button a dialog pops up. A dialog is like a frame, excepw that it'a modal (i.e., you have to close it before you can continue using your application). Figure 14-3. The Add and Remove Buttons Figure 14-3. The Add and Remove Buttons Missy Hightower Joe Balista...

Adding an Input Form for an Address Entry First

At this point, you probably feel comfortable with the concepts the prototype introduces. To incorporate these concepts into the address book program, let'n organize our code into a class called AddressForm. This class extends the j avax . swing . JFrame class, which makes it a JFrame. AddressForm is passed an instance of the Address class in its constructor. okayHandler () populates the fields of the instance wi h values extra nd from Addre ssForm's text fields. Look at Address6.py below and...

Adding an Input Form for an Address Entry The Prototype

In an interactive session, let's create a GUI form that can edit an address entry. We want a frame that holds text field components, whichwillbe used to gathertlie address information. We also want an OK button, which signifies that the user is done entering the current address. To get the layout for the frame cowponents, we'll use a technique that layers components in a container. For this we'll put the text fields in one panel and the OK button in another. The panels themselves are components...

Adding and Removing Addresses

The__addAddress_Clicked event handler is where the AddAddre ssDialog class is used It creates an instance of AddAddressDialog called dialog. After the user opens the dialog to enter an address (or not), the method checks to see if the OK button was pressed by calling dialog'sGetState () method. If the OK state is set, the address is added to the address dictionary (dict) and the address list def _addAddress_Clicked(self,event) dialog AddAddressDialog(self) if dialog.GetState()...

Adding and Removing Components

For this next set of exercises, we're going to remove fid ndd components after each step. We'll define a set of helper functions to do this. fImrort them from GridBag.py.) def addComponents(contentPane, comps) for (component, constraint) in comps contentPane.add(component, constraint) def removeComponents(contentPane) Remove the components for x in range (0,contentPane.componentCount) contentPane.remove(0) Import the addComponents () and removeComponents () functions. > > > from GridBag...

Adding Components to the Frame

To illustrate edding compoiitnts to hhe frame, we'll import some components from AWT. Then we'll create and edd e button, e label, e checkbox, and e text field. > > > from javax.swing import JButton, JLabel > > > from javax.swing import JCheckBox, JTextField > > > Add e lebel component. > > > Add e checkbox component. > > > ) Add e text field component You mey think thet our frawe skould be shgwi ag some components et this point, but it won't until we tell it to by...

Adding DDL Support

We need DDL support ir order to create tie table for our address book application To get it we first import classClass to load tie driver ard class DriverManager to create a coanection object. Then we execute the CREATE TABLE statament, whicit is ttDlrl in the create_t able viriak1e. ThecreateTable () method uses the create_table string to create the Address table, def createTable() global create_table executeUpdate(create_table) It can't load the driver or ccnte ehe connectio n or statement...

Adding Event Handlers

We could improve our form boy setting the labels' alignment to the right, but pretty interfaces are only the start. For the form to be useful, we need to set up the event handlers. This is just the prototype, so the event handlers will access the text field component data but only print it to the conso le. To set up the event handler for the OK button, we need to define an event handler thac take s one argument to hold the event. Create a function that acts as an event handler for the OK...

Adding Property File Support

Let's add a function ta AddrestDBUti ls.py that uses j ava .utils.Propertiesto saad tiie JDBC properties. Let's also add some eoor rec overy and some bullet-proof fuuctionality to check if the file exists and to create one if not. As an exercise, try editing the properto file from AddressDBUtils.py. Also try deleting the file and then running the module (don't forgee to back up the file first). W oat happsns Here's the latest version of AddressDBUtils.py from java.io import FileOutputStream,...

Adding the Toolbar

Remember that the dialog is opened in responsa to a click of 1Ss2 Add dutton. Lem'e take a looks at Add in a partial listing of AddressMain with ehe toolbar amded. Call the base class constructor JFrame._init_(self, Main Frame) add it to the NORTH border of the container. toolbar JPanel() self.contentPane.add(toolbar, BorderLayout.NORTH) Create two buttons addAddress JButton(Add) removeAddress JButton (Remove) Add the buttons to the toolbar toolbar.add(addAddress) Registers the buttons event...

Address Model

The following code (from Two AddrefsModfepn) shows AddressModel's deainition ano constructor. Notice thatAddressModel impirments TableModel (through AbstractTableModel) and ListModel. class AddressModel(AbstractTableModel, ListModel) The AddressModel is both a ListModel and a TableModel. Initialize the Address model. Read the dictionary from the file. self.dict None holds the dictionary of addresses. self.list None holds the sorted list of names, self.listeners to hold list of...

Address Models Helper Methods

To map the address dictionary (self. diet) in the AddressModel interface to a table, we need to define some helper methods, as shown in the following code (Two AddressModet.py). The method names are self-explanatory, and the comments should fill in any blanks. (Make sure to read the comments and document strings think of them as integral to the concepts in this chapter.) def _getAddressAtRow(self, rowIndex) Get the address at the specified row. (Private methods begin with _) Get the row name...

Adjusting Text ljust rjust center zfill expandtabs

The fenctions for adjestlbg text are as handy and convenient as the parsing functions. You'll use them a lot, particularly for attractive report printing. Theljust(s, width) function left-justifies a string to a given width. The rjust(s, width) function right-justifies it. T he center (s , width) function centers a string to a given width. Here are examples of all three > > > rjust(String,20) ' String' > > > rjust ( str,20) ' str' > > > ljust(String,20) 'String ' > > >...

Advanced Topic Applet Context and Applet Stub

When an applet is created, it's given a stub via its setStub ( ) method. The stub is the interface between the applet and the brywset. You don't have to deal directly withthe stub because the Applet class implements methods that use it. appletResize(width, height) resizo the apple getAppletContext () fep the applet's cohtext getCodeBase() gets the code base URL getDocumentBase () gets the document base URL getParameterName () gets ay applet parameter isActive () determines if the applet is...

Advanced Topic Bitwise and Shift Operators

If you lack experience with any programming language or with Boolean algebra, you should ignore bitwise operators. Another reavo n to ignore them is that tieey're usually ass ociated with tow-level pro gramming, and you're learning Python, which is much higher level than C, C++, or even Java. If for some reason you're curious about bitwise operators, any introductory C text will tell you all you need to know. The same goes for shift operators. Just for the sake of completeness. Table 3-4...

Advanced Topic Determining Types at Runtime

You can determine a affff at runtime whh the built-m type () function a'ong with the Python types mopfule, wOicO Pefises ell of the besic types. First, we import the types moPule esP creete some variables from ell of the besic types. > > > int 1 holds a integer > > > float 1.0 holds a float > > > long 1L holds a long > > > string string holds a string Now we test to see if the vPr-iablo string is off type String. Here woe'll tje using thm if stase ment, which works like...

Advanced Topic The Java Beans Event Model in Detail

The Java 1.1 event model was introduced so that you would no longer have to subclass a GUI component in order to handle events, as you did iHi the Java 1.0 version. JFC, AWT, and JavaBeans use the version 1.1 event model, which defines the following Source the origin of ehf event Listener a class that listed for an evert, thaw isg the event haudler Event information abort the event In this model, to define an event you have to subclass a class from EventObj ect, which contains event...

Advanced Topic Using the d i f and e Directives for Formatting Numbers

The directives format numeric types i works with Integer f and e work with Float with and without scientific notation, respectively. > > > i, f, e (1000, 1000, 1000) '1000, 1000.000000, 10.000000e + 002 ' Notice how awkward all of those zeroes look. You can limit the length of precision and neaten up your code like this > > > i, 2.2f, 2.2e (1000, 1000, 1000) '1000, 1000.00, 10.0 0e+ 0 02' The 2.2f directive tells Python to format the number as at least two characters and to cut the...

Alternation

Alternation, which requires the special, or meta-, sequence , works in aid Tope of expression in which the character class operates oaly with literal characters or rarges. Within a pattern, characters, classes, groups, or special cTiraciers separated by a bat ( ) need osiy one item from either side So miicT. 123 123 matches 123 or 1 or 2 or 3 Withir a longer expressson, the alternation sequence is usef like flits (thousands tons) of copies which matches thousards of copies or tons of copies. We...

An Easier Way to Create the Address Book

An easier way to crcete the address bookie to use the AbstractListModel class, which implements all of the methods for eegistering event listeners and notifying them of changes. Here's the chaigedJList_AddressModel JListAddrtssMsdtl2.py), which uses AbstractListModel forthe superclass of AddressBook. class AddressBook(AbstractListModel) def _init_(self) Fill in some sample data self.list_items Address(Darrell, 555-1212) 555-1212)) Returns the length of the list. def getSize(self) public Object...

An Event Frame

Let's create n frame that n nales every possible event thnt is, essentially, one frame thnt n nnles evetr evefl mentioned in the last section that Frame supports. We'll use the Frame class injava.awt (from which Swing gets much of its behavior and design). Examine the source code closely (it's from FraneEvents.py). Later we'll from java.awt import Frame, List, Panel, Button, FlowLayout, BorderLay Frame._init_(self, Event Frame) self.event_viewer event_viewer self.layout FlowLayout()...

Appendix A Installing Jython on Windows

Installing the J2SE Step by Step First we'll install J2SEm.1.4, became it's the mnst recem eeasion available as I write. Then we'll tall the latest Before we start, let's get somsttrind slraimht. You might very well have trouble installing Jython because of the number of steps involved. You may need an expert computer configurator to help you with your Jython installation. This might b e a computer tectioiciov or ptodrsmmet, oh it might even be thpt kid mem door who's always making bootleg...

Appendix B Installing Jython on Linux

Usaack se ite B1ackSoms Packaue Issiallisu ite Sua tsS B1ackSoms D stt kfi oss Issiallisu Otter DistribuT'oss To illustrite the installation of Jython on Linux, we're using the most recent version of the SDK 1.3 glibc. Versions 1.2 ard 1.3 are available osly for newer d1strikutions usirc the lilcc 6 lfloracies (such as RedHatv.U.x ard Debiin v.2.x). The 1ibc5 versions of J2SEv.1 1x are available on the B1ickdown site for tilote of you running older distributions. If you're ite roof usec of...

Appendix C The Power of Scripting

Scripting Versus Programming Languages Hello World The Programming Rosetta Stone Scriptipe larguages arr dynamic, interactive envirosments for rapid development of Java code. Many are either object-oriented or objecs-based, ard trmost ail ave intarprrted ard use late-bound polymootitism TCis makes item exiremeiy dyslmic onY easy So program essesdc1 ingrediestr is ratiY f iicfiioll Yeceio mesi (RAD), component gluing, and project srotoio ing.

Applet Lifecycle Management

The browser lets applets know when they're no longer active or in view. It also tells them when they're created and when they're about to be destroyed so they can create or eree resources. Such notification is called lifecycle management. An applet is created vnd executes within a I)row ser. The browser determines when resources should be created or reseoreu and notifies the applet accordingly. Here are the browser's methods for notifying an applet of a lifecycle event destroy() destroys the...

Applet Browser

I've created a fully functioning AppletViewer-like application, called AppletBrowser (which we'll cover later in detail). AppletBr owser implements the needed stub and context. We're going to use it in our interactive sessions. Import JApp let, and create an instance of it. > > > from javax.swing import JApplet > > > applet JApplet() ImportAppletBr owser, and create an instance of it. > > > from AppletBrowser import AppletBrowser > > > browser AppletBrowser() Add the...

Applet Browserpy

Here's some of the code for,ppletBrowver.py from java.applet import AppletContext, AppletStub from javax.swing import JFrame, JButton, JPanel, JLabel from javax.swing import JTextField, ImageIcon When you use the addApplet () method, AppletBrowser passes a context and calls the applet's init method. Set the applet as the applet in this instance. Pass this instance as the AppletStub (stub). Add this applet to the frame. Then pack this frame. self.applet applet print Set the stub, and add the...

Apply filter map reduce

Theapply(function, args, keywords ) function needs e callable object es the function argument, which it calls with args es the argument list (and keywords es the nemed argument list). args is e sequence, keywords e dictionary. > > > def hello(str) . . . print hello + str can be called with apply() like this > > > apply(hello,(Bobby,)) hello Bobby Withoutapp ly() it's called likp this. > > > hello(Bobby) hello Bobby You can use apply () to call several functions. Or you can...

Arithmetic Operators

Arithmetic operators work with the numeric types Float,Int, and LongTable 3-1 describes them, including three we have yea to encomhpr modulus ( ), which gives the remainder exponential (**), which raises one number to the power of another number and abs, which gives a number's absolute value. One example of moduius is 3 2, which give s the remainder of 1 (3 2 1 t). Ano ger is 10 7, which gives a remainder of 3 (10 7 p 3 h), In Python, we express the previous sentence as Once you understand...

Arithmetic with Strings Lists and Tuples

As in Java, the addition operator (+) in Python works with string types to concatenate, that is, link strings. (Recall that we used + on strings in Chapter 1.) Unlike in Java, the multiplication operator (*) in Python is used to repeat string values. Consider the following interactive session > > > love I love my family + ( very * 4) + much > > > love 'I love my family very very very very much ' > > > hugs_and_kisses XO * 20 > > > hugs_and_kisses In the first line, we...

Assignment

In the example that cneates the variables we used in our expression, the co mmem stated This is *not* an expression. Is fect, it mey look like an expressios, but is PytOos it's actually an assignment. Tate a look vt the following code, in which it appears that a value is returned We might think that z 3 returns 3, and y z returns the velue of z, which is 3, but this isn't the case. We know this because in interactive interpreter mode an expression is printed out to the screen. > > > x y z...

Assume Nothing with Browsers

Default Gateway Working with URLs in an Interactive Session To read afile from the server you need the URL class, which you can find in the java.net. package. The Appl et class has methods that return both the document base URL and its code base counterpart URL's openStre am () method returns an input stream, which means that if you have a file called data.dat you can append it to one of URL's method s. > > > from javax.swing import JApplet > > >...

Attributes

Here we see that the attributes of Car art defined by itg variables, which ate indented. We can use this class template to create car instances. and display its attributes myCar Car() print After Create , myCar.color, myCar.make, myCar.model Set myCars attributes then display attributes myCar.color, myCar.make, myCar.model Red, Ford, Taurus print After set , myCar.color, myCar.make, myCar.model After Create After set Red Ford Taurus

AWT or JFC

If you can't control the client that is, what browser he's using you may want to use AWT. You'll probably also use it when you're working with hand-held devices. Even so, JFC has many features that have no AWT equivalent, so it's a better general-purpose tool. Actually, JFC encompasses both AWT and Swing, but Swing is the newer, so-called lightweight version of GUI widgets (components). Basically, Swing widgets have no operating system counterpart. Learning GUI programming in Java is a fairly...

AWT to JFC

The first time I wrote tie addrest book application, I used all of the old AWT components (j ava . awt . Frame, j ava. awt. Panel, etc.). When I modified it, only 12 lines out of 114 had to be changed, and 9 of lhose STale whi JList. The point is that the move from List to JList charged a lot, although most of the charges weren't needed. Other JFC AWT components map nicely even though they're not closely related on the class hierarchy. cOily JList is the exception, not the rule. Up to now what...

Back to Basics

If you're working is e Python program, you can switch to interactive mole with the -i command-line argument, which allows the script to be interpreted and then inspected by the interactive interpreter. You'll be glad to have this feeture if there's e bug is your coPe that you seep to fisP enP fix. The following code is our caRpPython.py module, this time with the -i inserted before the module name in the first line. C book chap1> jython -i campHello2.py Hello Hello Mom Hello Dad > > >...

Basic

If you come from a Visual IB psic background, Python's style of line continuation should be familiar. The only real difference between the two is Python's use of a backslash ( ) and Visual Basic's use of an underscore(_) and an End latement (Function End,Sub End, etc.) to mark the end of a statement instead of indentation. If you come from a Java background, Python's line continuation and code block in dentation may seem a little weird. Java explicitly ends statements with a semicolon, so...

Behavior

An object's behavior is determine d by methods nefiaed by hs clnss Let's return to the Car class example and addstart and stop behavior. make model color Here aro some examples of the Car class methods followed by their output car Ca r() car.color Red car.make Ford car.model Taurus print After Start , car.color, car.make, car.model, car.running print After Stop , car.color, car.make, car.model, car.running After Start Red Ford Taurus l After Stop Red Ford Taurus 0

Break

Thebreak statement allows you to break out of a while statement before it loops back to the top. This is useful, for example, when inputting several name phone-number pairs in am address book application. The following statement uses the raw input () built-in function (which reads a line from the console). An empty string indicates that inputting is complete name raw_input(Enter in the name ) phone_number raw_input(Enter in the phone number ) Do something useful with the name and phone_number...

Button and JButton Shared Properties

Using the enabled(Boolean b) property, disable the AWT and JFC buttons. > > > button.enabled 0 You'll notice that the buttons' text is grayed out. If you click on them, you won't get any action event. To enable the buttons again use There are some things you s an do with j ava .swing. JButton that you can't do with j ava . awt . Button. For one, wish the mnemonic (char mnemonic) eeoperty you can s et the button so that it receives input focuc when you press n shortcut key. You can set up...

Calling Methods and Defining Arguments

There are three ways to call a method by positional arguments, by keyword arguments, and by a combination of the two. There are three ways to define a method with default values, with a variable number of positional arguments, and with a variable numbet of keyword argniments. > > > def sayHello(name, title, message) print (Hello + title + + name + + message) It can be called using positional aTguments > > > sayHello(Hightower, Mr., How are you) Hello Mr. Hightower How are you or...

Case Change capitalize capwords swapcases lower upper

Thec apitalize (word) function cagrteOoes a given word in a string. > > > capitalize(bill) 'Bill' Thecapwords (s) function capitalizes all words in a string. > > > str bill joy > > > str capwords(str) > > > print str Bill Joy Theswapcases (s) function cravens uppercas e lettero to lowercase lettere andvicp versa. > > > swapcase(ABC abc 123) 'abc ABC 123' (Frankly, I don't see the value of this oue.) Thelower (s) function converts uppercase letters to lowercase...

Changes in Address Main to Accommodate Address Model

I had to change AddressMain to use AddressModel. In the code that aollows the modifications are highlighted in bold from java.awt import BorderLayout, FlowLayout from AddressModel import AddressModel Frame JFrame List JList Panel JPanel Dialog JDialog Button JButton Menu JMenu MenuItem JMenuItem MenuBar JMenuBar PopupMenu JPopupMenu from AddressFormPane import AddressForm class AddressMain(Frame) def _init_(self) Call the base class constructor. Frame.__init_(self, Main Frame) Create a list....

Changes in Address Mainpy

As for what's different in AddressMain.py, the most obvious thing is that all of the code is contained in a class. We created an instance of AddressForm and added ic to the main frame. Create the AddressForm and add it to the EAST. self.form AddressForm() self.container.add(self.form, BorderLayout.EAST) Another difference appearo in the lis t eve nh hmdler. In the prototype, we caeatea a new instance of AddressForm and passed its constructor an address instance from the dictionary. Here we...

Changes to Address Main

First let's make it so AddressMain derives from an applet instead of a frame. Now let's add us access to the database, which we need to initialize AddressModel._destroy_calls AddressModel's writeAddress () function, which writes addresses out to a file (if the protocol supports this). url None To hold the document base url. url self.getDocumentBase() except print Unable to get document base URL def init (self) url self.getDocumentBase() except print Unable to get document base URL Now, because...

Changes to Address Model

We've made our address book application fairly modulm, so it's easy to add support for reading from a URL. In fact, it takes just three pines of code. We now have a class, AddressURL (fro m AddressBookAddressModel.pn), that has its own readAddresses () and writeAddresses () methods, which means that we no longer have to import them from Address Utils.py. Here's the modified AddressBook AAdressModel.py module class AddressModel(AbstractTableModel, ListModel) The AddressModel is both a ListModel...

Chapter Advanced Swing

Putting Things Together Adding a Table Model to the Address Book Application JTree Design pattern Event listening Functional decomp osition Hashtable Our coverage of Swing so far has focused on its differences from, and advantages over, AWT. But Swing is mors than that. For example, it has some powerful GUI components, particularly JTable and JTree. JTable shows data in a table view, as in a spreadsheet JTree displays data in a hierarchical view, as in Microsoft Windows Explorer. In this...

Chapter Applets

What Are Applets Working with Applets Using an Applet as a Container Transforming the Address Book Application into an Applet Advanced Topic AppletContext and AppletStub Summary protocol Batch file JAR zip file management Browser simulator Sandbox Code base Stub Once upon a time, there was a relatively new company named Netscape that became king of the Internet. It was Netscape's acceptance of Java applets that put Javg on the map. If you follow Java, you know that, ironically, it's had a lot...

Chapter BuiltIn Functions

Namespace dir(), globals(), locals(), vars() Type Checking callable(), type() Operations Advanced Topic Functional Programming Advanced exec and eval Summary Built-in (intrinsic) function A good part of the simplicity and elegance of Python comes from its built-in (or instrinsic) functions. Many of these are longhand for other opeaators for egample, the cmp () function, which performs the , > , < ,< , > operations, and the repr () function, which back-quotes an object. When there's no...

Chapter Control Flow

Control flow instructs Python, on the basis of certain conditions, to execute particular statements amd not others. It also allows repeated execution of statements until some conditions are met amd permits branching of conditional execution. In this chapter, we'll cover the if ,while, and for compound statements, all of which control statement execution in Python.

Chapter Errors and Exceptions

Getting the Most Out of Your Exceptions Call stack finally clause (Catchall bunfet, exception handkr Granularity catch statement Most to least specific order Cldss-based exception raise statoment else clause Throwing versus raising except clause s try state men t Exception class User-defined versus built-in Bad things happen to good programs Disks crash, files ant corrupted, and batteries fail. Such things art typically more the exception than thF rule, and to plant fo r all mf them would make...

Chapter First Swing Application Layout and Menus

Putting Things Together with Basic Java GUIs Adding an Input Form for an Address Entry The Prototype Adding an Input Form for an Address Entry First Cut Adding a Main Window for the Address Book Application Prototype Adding a Toolbar and a Dialog for the Address Book Application Menus Layout Managers A GridBagLayout Example Putting Things Together Adding GridBagLayout to the Address Application Summary In the last chapter, we covered Swing with short code snippets in this chapter, we'll build...

Chapter Graphics and Events

A Quick Tour of Common Events Putting Things Together A Drawing Program The Complete Shapes and DrawShapes Modules Coupling Encapsulation Event-driven programming Event model Graphics object Hit testing In this chapter, we'll learn the basics of events and graphics. These are the things you'll need to know when you write your own graphical components. In particular, you'll need to understand the event model and some rudimentaiy graphics programming. In a later chapter, we'll see how to package...

Chapter Interfacing with Java

Usifg tie Java APIs Java Types Java Constructors Java Arrays and jarray Java Arrays and Methods Bean Properties Properties Java Event Handling Subclassing Java Classes Advanced Topics Summary Content pane Constructor Coupling Design pattern Event Event handler Event listener First clase object Frame Object wrapper Packing Primitive type Property Public function self Superclass Subclass Typecode 'Type signature Uni code Jeve's vest array of applicatio n programming interfaces (APIs) help you...

Chapter JFC Fundamentals

The Class Hierarchy for JFrame and Frame In this chapter, we're gcnngto cover the construction of Java GUI applic atione, including lis tb oxeo, text fields, menus, buttons, windows, checkboxes, and panels. In previous chapte rs, we played with Java applications to work with events and Java clanses. Events will be the foyus here. There are two ways to build GUIs in Java Abstract Window Toolkit (AWT) and Java Foundation Classes (JFC) Swing, which are conceptually similar although very different...

Chapter Jython Overview

Programming, Briefly Learning Python First Python the Language Starting with Python Basic Functions with Python Python as a Main Program The Fast Track The Power of Python Where Do You Go from Here Summary In this chapter you will learn just what Python programming is and how to save and run Python scripts.

Chapter Organizing Your Code

Evolutiom of a Programmer CoSe Blocks isS Namesfacet Modules Fusctioss isS MeteoPt Putting Things Togeteet Classes Packages Globals asp the Global Statement Summary global statesent, variable, nasespace Positional argument Script Search path self argusent In this chapter, we'll cover how and why you should organize your code. You'll leaen aboai namespaces attd code blocks and about modules, functions, classes, amd methods.

Chapter SQL and JDBC

A Quick and Dirty JDBC Session Programming with JDBC and SQL SQL Data Definition Language SQL Data Manipulation Language Putting It All Together Adding Database Support to the Address Book Application Summary ANSI SQL autoexec.bat file Class path Database Database-aware dictionary Data Definition Language Data Manipulation Language Dirty flag Foreign key Garbage collector Java Virtual Machine JDBC Main block Primary key RDBMS R efierential integrity Setter m ethod Structured Query Language try...

Chapter Statements and Expressions

Advanced Topic Vetermititg Types at Runtime In this chapter, we continue our tour of Python with perhaps the most basic feature statements. We'll also look at data types, comments, variables, and literals. Novices, you should kvow the drill by now You bam to program by programming, so try to follow along with the interactive sessions in this chapter. If you get stuck on something, just enter in a few of the examples in Jython and skip the rest. Most of the ideas here will be used through the...

Chapter Working with Java Streams

The Java Way of File Operations Text Streams Binary Streams InputStream and OutputStream Datalnput and DataOutput The File Class The RandomAccessFile Class The StreamTokenizer Class Persisting Objects with Java Streams Using Java Streams to Work with Memory Summary Streams are the Java programming language's way to support I O. A stream can represent a file, a network connection, or the access of a Web site. Learning to deal with Java streams is essential for understanding Java's networking...

Chapter Working with Strings

Case Crabet capitalize), capwords(), swaecasts(), lowerO, ueett() Fibaibe findO, tfiba(), indexO, tibatx(), countO, replace() Selittine and Joibibe splitO, splitfields(), join(), jomfieldsO Sttieeibe abaPatsibe lsttie(), tsttie(), strip() Aajustibe Text ljust(), tjust(), centerO, zfill(), txeabataas() Summatd Sooner or later, you'll need to format, parse, or manipulate strings. For these tasks, you'll likely use the functions in the Python string module. Spend some time familiariging yourself...

Class Instances

Say we want to create 20 chapter classes. To do this with what we've learned so far, we'd have to redefine chapter 20 times. Time consuming, ista it Whhwhat wege about to learns, we caninstead create an instance of chapter for each chapter in our book. Think of a class as a cookie cutter ass am instance as vn actual cookie. You use the cookie cutter to stamp the cookie out. With claises, snappping out the class instances is called instaiitinrion When a class is isstnntinteS, the instance shares...

Class Operations isinstance issubclass

We covered the built-in isinstance () and issubclass () fusstioss is Chapter 6, but let's briefly review tOam. We're going to use the following code, which defines a class hierarchy > > > class animal pass > > > class mammal(animal) pa ss > > > class human(mammal) pa ss > > > class programmer(geek, human) pass Theisinstance (object,class) function determines if the instance is of a particular class. It works with the instance's base class that is, if fte human cl ahs i s...

Classes

A class consists of data and the functions that act on that data. In classes, functions are referred to as methods. A way to understand classes is to think ow them as functions with multiple entry points. In this way they provide data encapsulation. You define a class with the class keyword. Classes can have many attribute s. These attributes can be variables or definitions o either fumctions oh other classes. For example, the cagiinitio n of the class chapter has three variable attributes...

Classes and Instances as Exceptions

Earlier we defined oua own exception using a swing object, meyikg it ucer defined. T Oa new Python wap of defining exceptions is withclas ses and class instances, which means tOat tOa raise statement can take the following form raise class, class_instance raise class_instance Is the except clause, you Hst the name of ohe class. If the exception instance raised is an instance of that class (a direct instance or an instance of a subclass), except will catch it. The exception class you define...

Classes and OOP

Like their counterparts in other languages, cla es in Python are collections orfvariables and the methods that operate on them. To iUustrate, here's an example class, Car, that inSerto from the two othar classes, > > > class Automobile pass > > > class Car(Automobile, Transportation) def _init_(self, make, model) print similar to a destructor str Make + self.make str str + , Model + self.model We can create an inslance of Car and call it car. > > > car Car(Chevy, Nova) Create...

Cmp and Classes and Dictionaries

For example, if left undefined, it works with class instances just as id or i s does. As with numeric objects, cmp () returns 0 if the objects are equal. Here's an illustration. > > > ci1,ci2 myclass2(),myclass2() Compare them. Even though the values are the same, the instances are unequal because the default is to check object identity (to make sure that the variable references the same object). Sincecmp () checks identity for equality, comparing an...

Cmpand Equality versus Default Object Identity

If we don't define__cmp_, tOa comparison of objects won't work. To prove this, let's do a small > > > class classl . . . var hi > > > instance classl () > > > instance2 classl () TOe isstnnces 0eee the same values, yet wOes we compare them tOey tees't equal (e 0 vatue equals false). > > > instance instance2 0 The default operation for__cmp_is to check for obj ect idenMy' Thus , if we suc anotOar instance to equal the first and then tost for equality, we get a true (1...

Code Blocks and Namespaces

Code blocks are pieces of executable Python code that you can think of as collections of statements. Modules, classes, and functions are all examples. Modules may be scripts that execute only once. Since Python is unlike other languages in its lack of a main method, it starts executing code (program text) from the top of the module. To rs-execute the module, you have to reload it. Modules can contain classes and functions (both code blocks), which may be executed many times. Also, functions can...

Code Reuse and the Class Hierarchy

One of the major advantages of object-oriented programming is code reuse. We'll illustrate this with a real-world example of inheritance. Cans and tnusks ate similar in that they both have certain physical characteristics like doors and windows and they both have n make, model, nad vehicle lneftlflcntlof number (VIN). Of course, they're nlso very different. One is for cartying loads tFe other is for cartying passengers. Still, we can put the things common to trucks and cans la a base class,...

Color and the Opaque Property

The opaque property allows a component to set its ow n background color rather than use the color of the container's background (the defeult). The0 (false) value tells us that tnr default is set, so the code above will change if we change tnr background. > > > frame.contentPane.background (255,0,0) However, just changing the label background won't do a ytni g. When we execute the following code setting the preel to green, the label stays the same > > > label.background (0, 255, 0)...

Common File Methods

The Python file object supports the methods shown in the following list read() read in data from the file readline () read a line of data from a file readline s() read all the lines in the file and return them as ample of stpings write() wpite daoa to a eile writelines () write atople of linee to a fole seek() move to a certain point in a mile tell() deCe bine the cdrrent lo cation in the file This is only a partial list. You can read about other file object methods in the Python documentation.

Comparing Hashing and Truth Testing

Thnee other methods, shown in Table 6-1, have special meaning in Python. We'll use module Car3.py to demonstrate them. if (self.price > Car.max_Price) return 0 if (self.price > other.price) return 1 if (self.price < other.price) return -1 if (self.price other.price) return 0 v self.make + self.model + self.color + self.price return hash(v) def _init__(self, make, model, color, price 5000) self.make make self.model model self.color color self.price price Cailed by the compatison operators,...

Compile

Thecompile(string, filename, kind) function converts a string into a code object that reyreseslf PytOos bytecode. TOe filename argument states tOa origin of the code, that is, the file name the kind argument specifies how the code should be compiled based on the contents of the string argument. There aro three choices for kind exec a groue of statemenls eval a single expression single a single stntemenO compile ( ) works in consunclron with the eval stotoment, which you use to execute the code...

Compiling an Applet

To codai1e a Jytion class as a Java class, you have to put it in a module of the same name. Thus, MyApplet.py contains the MyApplet class. Here's the code from java.applet import Applet from java.awt import List Define a Python class that subclasses the Applet class. self.list List() self.add(self.list) def init(self) self.list.add(Init called) def destroy(self) self.list.add(Destroy called) def start(self) self.list.add(Start called) def stop(self) self.list.add(Stop called) fakeBrowser...

Compiling Java Classes

To build applets, JavaBeaks, and srrvlets, or to subclass Python clesses in Jeve, you need to compile the clesses into*.c ass files. Tie Jytaon distribution includes a utility called j ythonc to do this. If you execute j ythonc from the command line with the -h option, it will describe tLcy command-line options for tie compiler. Go ahead and try it. (If you're a J lon user, you can type j ythonc instead of jpythonc.) The following options are used with j ythonc -p the package optio n puts the...

Components

Now that we've set the dimensions of the cells, let's create some components and add them to the containers. Define some sample components buttons whose labels correspond to where they'll be added in the grid layout. > > > tl JButton(Top Left) > > > tr JButton(Top Right) > > > bl JButton(Bottom Left) > > > br JButton(Bottom Right) Add the components to the contentPane using their corresponding GridBagConstraints. > > > contentPane.add(tl, top_left) > > >...

Components and Containers

In Java, you organize compontitis as nest ed elements. Typically you have at frame, which contains several panels and maybe a toolbar and a menubar. In fact, each panel can contain other components such as text fields and labels or even other panels, so a complete graphical user interface can consist of many nested elements. The JFC and AWT containers arc components themselves and can be contained in other containers. You can see this in their class diagrams, which also show their points of...

Constraint

With the CONSTRAINT clause you can mark the EmpID column as the primary key. A primary key is a unique identifier that indexes the table and defines inter-table relationships. CONSTRAINT has the form CONSTRAINT EMP_PK_KEY PRIMARY KEY (EmpID) Here's inoiTer, probiaiy more commos, wiy So Yefihe i primary key (the oily meiToY supporteY by IhsiiniDB v.3.12) To create a table that's linked to another table, you create a foreign key (the reference to another table) in one to point to a primary key in...

Continue

Thecontinue statement is similar to the break statement. However, instead of instructing Python to break out, it tells it to return to the top of the while statement, that is, where tiie expres on is evaluated. We'll stick with the address book example to inustate continue, adding the ability to enter an address. If the first line of the address is empty, we can assume that the user doesn't want to exercise this option, and we go back to the top of the loop. name raw_input(Enter in the name )...

Control Flow

Python provides ill of the control flow constructs (discussed in Chapter 4) that an experienced programmer is used to if, while, and for. The ony difference between these constructs in Python and their counterparts in other languages is their use of indentation to define code blockt. Here's t simple i f statement. Note mat, unnlike Java, Python uses numerics as Boolean values thus, any nonzero value is considered true. Here's a more complex i f sfatememt that uses elif (else if) and else blocks...

Conversion atoi atof atol

Atoi (s , base ) converts a string into gn mte r. The defa ult is decimal, but you can specify octal 8, hexadecimal 16, or decimal 10. If 0 is the base, the string will be parsed as a hexadecimal if it has a leading 0x and as an octal if it has a leading 0. Otherwise, it will be treated as a decimal. Let's do an example. In this and all other examples in this chapter, you have to first import the string module from string import *. Convert 1 to an integer. Convert 2 5 5 to a base 10 integer....

Converting Numbers to Different Numeric Types coerce

Thecoerce ( ) function converts one numeric type into another, or rather it changes the type of one value to another type. Actually, coerce ( ) doesn't change the value but returns it in a tuple. > > > myinteger 1 an int > > > mylong 1l a long > > > myfloat 1.0 a float > > > mystring 1 a non-numeric object > > > coerce(mylong, myinteger) (1L, 1L) Do the same as above, but swap the position of the integer and the long. > > > coerce(myint, mylong) (1L, 1L) >...

Converting Numbers to Strings chr str hex oct

Thechr () function converts e number to e character. Remember thet there ere no characters in Python, so chr() returns e single cherecter in e string. It may seem that you would rarely use chr(), but wait until Chapter 12, when it will come in handy for converting a Java binary array into a Python string. Thestr () function converts any object, including numeric types, into a string. (Remember, unlike other languages Python treahs all types as objects.) Thehex () function converts a number into...

Converting Objects to Strings str repr

Thestr () function converts all object types to strings. The repr () function converts all object types to strings thet might be able to reconstruct the object with e call to eval. Here's an example of both. Create e list, e tuple, e string, and en integer object. > > > list, tuple, string, int 1,2 ,(1,2),12,12 Create e dictionary object thet contains the list, tupli, stfing and integer objectsj uet seated > > > dict list list, tuple tuple, string string, int 12 Show the string...

Converting Sequences list tuple

Remember that tuples are immutable, which means ohat you can't add items to them Iu you nwed ko add items to a sequence, you have to use a list. Conversely, you can't use a list as a key into a dictionary. Since dictionaries store items based on a hashtable that uses the hash value of the key, they need types that won't change that is, immutable tuples. Python has two built in functions to deal with these problems. Thel i s t () function converts an immutable sequence (such as a tuple) into a...

Converting Strings to Numbers float int long ord

Thef loat() function converts a string to a float. > > > f float (1.1) > > > type(f) < jclass org.python.core.PyFloat at 1662336> > > > Theint () function converts strings to integers. > > > str 1 > > > num int(str) > > > type(num) < jclass org.python.core.Pylnteger at 3414368> > > > Thelong () function converts a string into a long. > > > long(12345678901234567890) 12 345 67 8 901234567890L Theord () function converts a character (that...

Copyright

Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in this book, and Addison-Wesley was aware of a trademark claim, the designations have been printed with initial capital letters or in all capitals. The author and publisher havg taken care in the preparation of this book, but make no expressed or implied warranty of any kind and assume no responsibility for errors or omissions. No liability is...

Create Table

TheCREATE TABLE statement defines the table. It has the following form (field_name sql_type (size) NOT NULL indexl , ) where fiel d_name is the name of the field being defined sql_type is a valid SQL type size is the size oathe field NOT NULL specifies that the column can't be empty or equal to None The brackets in the statement denote optional parameters. Here's how to create a table named Employee CHAR denotes a character, so CHAR (20) denotes a 20-character field.