Contents. 18 Algorithms Case study: network search The search algorithm Case study: automatic language recognition 57

Size: px
Start display at page:

Download "Contents. 18 Algorithms Case study: network search The search algorithm Case study: automatic language recognition 57"

Transcription

1 0 Contents 17 Object oriented design Abstract classes and interfaces Collections Extensions of AWT Application: a sketch program File input/output Non-window programs Algorithms Case study: network search The search algorithm Case study: automatic language recognition 57

2 1 Chapter 17 Object oriented design 17.1 Abstract classes and interfaces The Once and only once principle Good programmers always try to keep their programs compact. Instead of copying code fragments using a text editor and pasting them repeatedly, possibly making minor modifications to the copies, a programmer should try to put the code in a suitably parameterized method. That way, the once and only once principle is adopted: never write the same code more than once in a program. Object oriented languages are the tools par excellence for this principle. Not only it is possible to set aside groups of statements for multiple use in a method, also you can reuse variable declarations by putting them in a class, which can be instantiated many times, giving many objects. By means of the subclassing mechanism you can furthermore make additions and/or modifications to classes that were written before. Nevertheless, the copy/paste programming temptation still persists. This has disastrous consequences for the maintainability of programs. The reasons for that could be discussed here in depth. However, we won t do that, as that discussion is available elsewhere. Practising the once and only once principle we won t copy the discussion here, but refer to it instead. Surf to for a thorough discussion, and while being there, have a look at related programming principles linked there. Seen enough? Then we are ready to pursue even more subtle mechanisms to formulate ideas once and only once in our programs. Classes and interfaces In an earlier chapter, we introduced the notion of a class in two different ways: a class is a group of related methods a class is the type of an object Later, these ideas turned out to be two sides of the same coin. When calling a method, an object is involved an object that has the class the method is part of as its type. For example, you can determine the length of a String-object, but not of a Color-object. On the other hand, a Color-object is involved when calling darken, which cannot be done to a String-object. Method applicable to a certain object, are methods residing in the class of that object. When using a class, three issues arise: what is an object of this type? (this is described by variable declarations in the class: each object that has this class as its type has a set of these variables at its disposal); what can be done to objects of this type? (this is described by the method headers in the class: a method header describes in what way the object is handled, and what additional parameters are needed for that); how do these methods operate? (this is described in the method bodies). Not always are all three issues relevant. When dealing with Color-objects it might be useful to realize that they consist of three numbers each (the amounts of red, green and blue); however, you barely need to know the internal structure of a Graphics-object. It suffices to know that you can use a Graphics-object for calling method drawline. You don t need to know how the method does the trick. Unless, of course, you happen to be the programmer of the method: then, the details are of major importance. Often, methods have parameters that are an object themselves. In their bodies, they probably use the objects (otherwise, we could have done without the trouble of passing them as a parameter... ). The object can be used by passing it further to another method. Another sensible way of using an

3 2 Object oriented design object, is calling methods, involving the object. For making the choice of what method to call, it suffices to know what you can do with the object, not how this is done, or what the structure of the object is internally. This is the reason that in Java, the notion of an interface is used. While a class is a group of methods and declarations; an interface is just a group of method headers. Thus, an interface is a wish list for the capabilities of an object. Example: interface ActionListener An example of an interface in the Java library is ActionListener. follows: interface ActionListener { public void actionperformed(actionevent e); It is defined (roughly) as As an interface only consists of method headers, such a definition tends to be short (unless we have a very long wish list). There are methods that, as their parameter, expect an object of type ActionListener. An example is method addactionlistener in class Button, that is used in almost every interactive program. Its purpose is that the button, when pressed, can notify anyone who is interested. The notification is done by calling method actionperformed. Any object that can be involved with that method is welcomed as a listener. The nice thing is that method addactionlistener in fact accepts parameters having various classes as their type; the only requirement is that those classes contain method actionperformed, which is intended to be called when time is ready. This way, only one definition of addactionlistener suffices, simply taking an ActionListener. Without the notion of an interface, we would need a separate definition of actionperformed for any feasible class that happens to contain a method actionperformed. Such a scheme would not only be tedious and anti-once and only once, it would even be impossible for the author of class Button (in which method addactionlistener occurs) to predict which classes supporting actionperformed might be written in the future. Thanks to interfaces we can still adhere the once and only once principle: there is one, and only one, method addactionlistener. Implementation of interfaces In a class header, you can promise that a class will fulfill the wish list of an interface. We have frequently done so for interface ActionListener, using a construct like class MyListener implements ActionListener { public void actionperformed(actionevent e) { react adequately when an action occurs An interactive program can let a MyListener-object react upon the pressing of a button: class ProgramWithButton extends Applet { public void init() { MyListener ear = new MyListener(); Button b = new Button("click here!"); this.add(b); b.addactionlistener(ear); In example programs in earlier chapters, we have been economizing on the number of classes. Therefore, we combined these two elements in a single class, thus creating programs that listen to their own buttons: class ProgramListeningToItsOwnButton extends Applet implements ActionListener { public void init() { Button b = new Button("click here!"); this.add(b); b.addactionlistener(this);

4 17.1 Abstract classes and interfaces 3 public void actionperformed(actionevent e) { react adequately when an action occurs The program, thanks to the presence of method actionperformed (which is promised in the class header by implements ActionListener), can listen to its own buttons. Therefore, we don t need an ear, as this role is taken by object this. Real programmers tend not to be economizing on classes that heavily. It is quite common that a program consists of various classes, each implementing ActionListener in their own way, and that objects of these classes are used as listeners for various buttons. An extreme case would be that each button has its own listener object, which might be instances of a single class; or maybe each listener is even an instance of a separate, custom build class. In the example program in section 17.4 there will be seven buttons, each having their own listener object, and the listener objects belong to two different classes, each providing an implementation of interface ActionListener. Once and only once implementation of interfaces The use of interfaces enables us to write methods that can take parameters of various types (as long as all these types implement the interface). This promotes a once and only once style of programming: the method needs to be defined only once, instead of separately for any feasible parameter type. However, the use of interfaces still tempts us to practice copy/paste programming, the natural nemesis of once and only once programming. This is particularly the case for interfaces that require multiple methods, like MouseListener and MouseMotionListener. In a program that should react upon pressing the mouse, you ll write a class that implements MouseListener. You can define an implementation of mousepressed, but you ll find yourself faced to the bundled obligation of implementing four more methods that were specified in the interface: mousereleased, mouseclicked, mouseentered and mouseexited. You are obliged to implement them, even if your program is not at all interested in these types of events. In programs that should just respond to pressing the mouse, you ll often write constructs like: class MyMouseReaction implements MouseListener { public void mousepressed (MouseEvent e) { react adequately to pressing the mouse public void mousereleased(mouseevent e) { public void mouseclicked (MouseEvent e) { public void mouseentered (MouseEvent e) { public void mouseexited (MouseEvent e) { When later you write another program that just needs mousepressed, it is tempting to copy and paste the other four methods, along with their empty bodies. However, that would be copy/paste programming which is A Bad Thing! Another example is interface MouseMotionListener. It requires implementation of two methods: mousemoved and mousedragged. The former reacts upon mouse motion without pressing the button, the latter upon mouse motion while pressing the button, also known as dragging the mouse. In programs that are interested in mouse motion regardless the mouse button state, you might write: class MyMotionReaction implements MouseMotionListener { public void mousemoved(mouseevent e) { react adequately to moving the mouse public void mousedragged(mouseevent e) { mousemoved(e); Method mousedragged just calls mousemoved, which makes dragging to have the same effect as

5 4 Object oriented design moving-without-button-pressed. This way, duplication of the adequate reaction is prevented. Yet, still the copy/paste monster lies in wait: in another program that reacts to mouse motion regardless button state, you might be tempted to copy and paste the definition of method mousedragged. Abstract classes To resist the copy/paste temptation, and thereby remain faithful to the once and only once principle, in Java we can partially implement an interface. For example, it is possible to create a class that does define mousedragged but noy (yet) method mousemoved. Such a class would be a partial implementation of interface mousemotionlistener. In order not to upset the compiler, the header of such a class should announce that it will be an abstract class: abstract class MouseReactionRegardlessButton implements MouseMotionListener { public void mousedragged(mouseevent e) { mousemoved(e); While programming you might have unwillingly met the phenomenon of abstract classes. When you accidentally omit one of the methods while implementing an interface, the compiler doesn t complains you forgot a method!, but if you want to omit a method, make the class abstract. Making a class abstract has its price: you cannot instantiate abstract classes, that is: you cannot create new objects of it. Again, you might have stumbled upon this fact accidentally. When, after forgetting to implement one of the required methods, you slavishly follow the suggestion of the compiler to make the class abstract, you d probably get another error message that you cannot instantiate abstract classes, that is: you cannot create new objects of the class. So, what s the use of an abstract class, if you can not even create intstances of it? As a stand alone construct, an abstract class indeed is pointless. The intended use of abstract classes is to serve as a (common) base class to (multiple) class extensions. The subclasses should provide the missing methods. The subclasses thus are not abstract (one could say they are concrete, but there is no need to mention that in the class header), and therefore you can instantiate them. For example, in a program we can define two subclasses, that react differently to mouse motion: class MyMouseMotion1 extends MouseReactionRegardlessButton { public void mousemoved(mouseevent e) { react adequately upon mouse motion class MyMouseMotion2 extends MouseReactionRegardlessButton { public void mousemoved(mouseevent e) { react alternatively upon mouse motion Both subclasses benefit from the fact that in their common abstract superclass it is defined that mousedragged does the same as mousemoved. And note that this is done without copy/pasting mousedragged! Adapters Abstract classes are commonly used to, as in the example above, define a default implementation, that may be refined in subclasses. The most basic default behaviour is to do nothing. Many listener-interfaces, like MouseListener and WindowListener specify countless methods, of which often only a few are needed. It would be useful to define an abstract class corresponding to every interface, which gives a default, nothing-doing, implementation for the methods. Because this is so useful for every Java programmer, these abstract classes are available from the Java library. For example, corresponding to interface WindowListener interface WindowListener { void windowclosing (WindowEvent e); void windowclosed (WindowEvent e); void windowopened (WindowEvent e);

6 17.2 Collections 5 void windowiconified (WindowEvent e); void windowdeiconified(windowevent e); void windowactivated (WindowEvent e); void windowdeactivated(windowevent e); there is an abstract class that trivially implements all methods: abstract class WindowAdapter implements WindowListener { public void windowclosing (WindowEvent e) { public void windowclosed (WindowEvent e) { public void windowopened (WindowEvent e) { public void windowiconified (WindowEvent e) { public void windowdeiconified(windowevent e) { public void windowactivated (WindowEvent e) { public void windowdeactivated(windowevent e) { Although all methods are implemented, the class is still made to be abstract, because it is not meant to be possible to create new WindowAdapter objects. It is intended that concrete subclasses of WindowAdapter are made, in which one or more methods are redefined with a non-trivial body. For example: class WindowCloser extends WindowAdapter { public void windowclosing(windowevent e) { System.exit(); That concrete class can be instantiated, and the object can be used in a context where a WindowListener is needed: mainwindow.addwindowlistener( new WindowCloser() ); Apart from WindowAdapter as a trivial implementation of WindowListener the Java library also provides MouseAdapter as a trivial implementation of MouseListener, and MouseMotionAdapter as a trivial implementation of MouseMotionListener. The name of the trivial implementation of KeyListener is not hard to guess Collections The limitations of arrays If you need to process large quantities of data of a single type, you can store them in an array. Using a counter in a for-statement you can enumerate all elements of the array, but you can also access the elements non-linearly at will. For each element, you can inspect or modify its value. Arrays are a powerful tool, and therefore the history of arrays goes as far back as the very first programming languages. Yet, from an object oriented point of view, arrays might be considered superfluous and (therefore) obsolete. In the language, special notations are built-in for handling arrays: for creating: int [] a = new int[100]; for updating elements: a[n] = x; for inspecting elements: x = a[n]; for determining the size: x = a.length; If these are just the ones you need, there is no problem. But when you need to do other things to arrays, for example inserting elements between two other elements, or extending its size beyond the length determined at its creation, we our out of options. And although an array is an object, it has no class, and therefore we cannot define a subclass where we could add methods for the additional operations. The basic operations are provided by special-purpose notations using funny brackets. It is surprising that the access to array objects is not done by means of methods. In some cases, on the other hand, arrays are providing too much operations. For example, if you need to build a data set (say, some strings that the user has typed in), and later you need to recall them in the same order (say, for displaying them). Of course, we can use an array for this. But we

7 6 Object oriented design Figuur 1: Classes and interfaces for collections might pay a price for the versatility of arrays (random access), that is not even needed here (we just need sequential access). The price that is paid here, is that arrays have a fixed length. Some limitations of arrays can be circumvented. For example: the fixed length limitation. If the array is about to overflow, we might create a new array of double size, and copy the old elements to the expanded array, which will replace the old array afterwards. A possibility for inserting elements might be created by shifting the other elements up. Doing these things might be complicated, involving all kinds of indices and auxiliary counters, but when the operations that are needed are nicely put in methods, you can define a class that behind the scenes uses arrays, but where the actual storing of elements in the array is completely hidden to the class library user. Or maybe you will use another storing mechanism instead of arrays, if that would be more efficient in some sense. Interfaces for Collection, List and Set Of course, you don t have to write classes like this yourself. Any programmer sooner or later needs arrays of flexible size, or arrays where elements can be inserted in between of existing elements. The Java libraries therefore provide some classes for this purpose. Even better: the capabilities that might be needed are definied in the library, without needing to have a particular implementation in mind. In other words, there are some interfaces that specify groups of methods that may be needed in particular situations. Of course the library also provides various implementations of these interfaces. But let s first discuss the interfaces themselves. In package java.util a total of nine interfaces are defined for the purpose. some of these interfaces extend other ones: the augment the wish list with additional methods. In figure 1 these interfaces are schematically drawn as ovals. Below, we ll discuss some of the methods in these interfaces (not of of them, just to keep it graspable; refer to the online documentation for a full list). Interface Collection describes the basic properties of a data set: interface Collection { boolean add (Object o); boolean remove (Object o); boolean contains (Object o); int size (); boolean isempty ();

8 17.2 Collections 7 void clear (); Iterator iterator (); With method add you can add an object to the collection, method remove deletes a particular element, and method contains checks whether a particular element is present in the collection. The boolean result of add and remove reflects whether the collection was changed in the process. So, if you try to remove an object that is not present in the collection, remove will yield false as result value. Comparing objects by contains and remove is done by calling equals of the corresponding objects (unless the object to be compared is null: in that case, null is equal to another null, and to nothing else). Method size yields the number of elements currently in the collection, method isempty determines whether the size is greater than zero. Using method clear you can make the collection empty. Finally, method iterator yields a special object, by which you can easily enumerate all elements of the collection. The type of the object yielded by method iterator may vary, but it certainly implements interface Iterator. So, the following specifies how you can enumerate a collection: interface Iterator { boolean hasnext (); Object next (); Method hasnext determines whether there are any elements left; if so, you can safely call method next for retrieving the next element. Thus, enumeration is normally done as in: Iterator iter; iter = coll.iterator(); while (iter.hasnext()) processinsomeway( iter.next() ); or, more compactly, using a for-statement: for (Iterator iter=coll.iterator(); iter.hasnext(); ) processinsomeway( iter.next() ); Data in a Collection is not necessarily stored in a particular order. Therefore, the Iterator returned by iterator might enumerate the elements in a different order than they were inserted in the collection. If, in a particular application, order is important, you ll want to use interface List. In a List, elements are numbered: from 0 up to and including size()-1, or put differently: from 0 up to, but not including, the size() of the list; just as in arrays. Interface List is an extension of Collection, so the aforementioned methods add, remove, contains, size, isempty and iterator are still present. Method add of a List will add the element at the end of the list, and iterator will enumerate them in order. Also, there are some additional methods: interface List extends Collection { Object get (int index); Object set (int index, Object o); boolean add (int index, Object o); Object remove (int index); Method get yields the element having the indicated number; method set replaces a numbered element by the given object. These operations are the things that can be done with arrays using the square-bracket notations. But in lists, there are even more possibilities: methode add (having two parameters) puts an element at a particilar location, but unlike set, it first creates space by shifting up the rest of the elements. Method remove removes an an element at a certain position, and fills the resulting gap by shifting down the rest of the elements. Another sub-interface of Collection is Set. As in List, method add behaves special in Set. This time, add guarantees that every element is inserted in the collection at most once, so it refuses to insert duplicates. Equality is tested by equals. When an element is already present, add will yield false. Apart from the redefinition of add, there are no additional methods in interface Set, relative to its super-interface Collection. Additional methods are present in sub-sub-interface SortedSet. Here, method add guarantees

9 8 Object oriented design that added elements are stored in increasing order. The iterator will enumerate them in this order. Additional methods determine the smallest and largest value: interface SortedSet extends Set { Object first (); Object last (); To be able to order them, elements that are stored in a SortedSet need to implement interface Comparable. Some standard classes, like Integer and Date do so, and for your own classes you can make it so. Alternatively, you can pass a Comparator object to the constructor of your SortedSet, which can do the comparison. See the online documentatie for further details. Interfaces for Map Imagine that array elements would not be indexed by numbers, but by strings instead. That would be quite useful: we could, for example, make a table for translating English words to their Dutch equivalents. For translating a word, you just pass it as an index to the translation table. Such a translation table is what is specified by interface Map. It resembles List, but where List indexes elements with int-values, a Map uses an arbitrary Object as index. In practice, Stringvalues are often used. Interface Map specifies (among others) the following methods: interface Map { int size (); boolean isempty (); void clear (); Object put (Object key, Object value); Object remove (Object key); Object get (Object key); Set keyset (); Collection values (); Using put you can add new translations to the table, using remove you can withdraw them, and by get you can do a lookup in the dictionary. A Map does not provide an iterator, but you can determine all keys or all values. This will yield a Set or a Collection respectively, of which you can get an interator. This way you can, in our dictionary example, enumerate all English or all Dutch words in the table. Sub-interface SortedMap ensures that the table is ordered by increasing keys, and provides two additional methods: interface SortedMap extends Map { Object firstkey (); Object lastkey (); Abstract classes for collections It s rather hard to define new implementations for interfaces like Collection and List, because they specify so many methods (there are even more than were discussed in the previous subsection). To make life easier for would-be Collection-implementing programmers, for all interfaces discussed there is a corresponding abstract class, in which some (though not all) methods have a default implementation. The partial implementation of interface Collection is abstract class AbstractCollection. Amongst others, it contains a default impementation of method isempty: abstract class AbstractCollection implements Collection { boolean isempty() { return this.size()==0; A programmer wanting to define real, concrete implementations of Collection can define a subclass of AbstractCollection. A definition of size is still needed, but the implementation of isempty is inherited form the abstract superclass. Note that isempty in turn calls method size,

10 17.2 Collections 9 which was not yet known to the author of the abstract class that s what makes it abstract, after all. Although you don t need to define isempty in the concrete class, it is allowed to do so nevertheless. This might be useful in situations where calling size would be costly, because the elements would actually be counted. Counting them all would be a waste of time if, for isempty s sake, you just want to know wheteher the count is non-zero. So here, you might want to have an alternative implementation of nonempty. Apart form AbstractCollection there are abstract classes AbstractList, AbstractSet and AbstractMap. Refer to the online documentatie to see which methods to implement if you d need to define concrete implementations. Concrete implementations of collections For now, it is not necessary to define implementations of Collection, List or Map yourself, as the Java library already provides some. For the above mentioned abstract classes, multiple concrete subclasses are available. They differ in which methods are fast, and which are costly. Depending on your needs you can pick your choice. The following concrete implementations are available: Subclasses of AbstractList, and hence implementations of List: class ArrayList. Behind the scenses, it uses an array, so it can do get and set quite fast. Inserting elements, lookup by contains and removing elements with remove are more costly. class LinkedList. Behind the scenes, it uses a chain of references. Getting an element with a particular number is costly, but inserting new elements in between of others is relatively fast. Subclasses of AbstractSet, and hence implementations of Set: class HashSet. Operations are relatively fast, but occasionally can take a long time. class TreeSet. Operations are slower compared to HashSet, but no extreme cases exist. This class also implements interface SortedSet, so is the choice to make when the order of elements matters. Subclasses of AbstractMap, and hence implementations of Map: class HashMap. class TreeMap. Here, the same efficiency considerations apply as in the case of Set. Example of use of collections In listing 1 a short example is given of how collections might be used in a complete program. The page 10 program will show a textfield to the user. Alle texts entered are saved in a collection, and painted to the screen in method paint. The class has two member variables: a textfield for interaction, and a Collection as a model for all accumulated strings. It is indeed declared as a Collection; in the declaration you need not yet fix a concrete implementation. The choice is made in the constructor, where the Collection-variable coll is initialized: coll = new TreeSet(); This is an allowable assignment, because TreeSet is indeed an implementation of Collection, which is the type of variable coll. In method paint the iterator of the collection (which actually is a treeset, but paint doesn t need to know that) is requested. Of that iterator, repeatedly method next is called. Method next yields an Object as result value. But in this particular case, we as a programmer know better: we only added string-objects to the collection, so the result of next is certainly a string. Therefore we can use as cast to guarantee that the Object returned by next indeed is a String. (Otherwise, the compiler would refuse to assign iter.next() to a String-variable.) Finally, the String can be simply drawn to the screen. When working with iterators such a cast is often necessary, so you ll find (and write) this idiom in many programs. While running the program, the user will soon notice the behaviour of TreeSet: the strings are always displayed in (alphabetical) order, and duplicate items are not shown. If the initialisation of coll would have been

11 10 Object oriented design 5 import java.awt.*; import java.awt.event.*; import java.applet.*; import java.util.*; public class CollDemo extends Applet implements ActionListener { TextField invoer; Collection coll; 10 public void init() { invoer = new TextField(20); this.add(invoer); invoer.addactionlistener(this); coll = new TreeSet(); 15 public void actionperformed(actionevent e) { coll.add( invoer.gettext() ); invoer.settext(""); 20 this.repaint(); public void paint(graphics g) { Iterator iter; 25 String s; int y = 50; for (iter = coll.iterator(); iter.hasnext(); ) { s = (String) iter.next(); g.drawstring(s, 10, y); 30 y += 20; Listing 1: CollDemo/CollDemo.java

12 17.3 Extensions of AWT 11 coll = new ArrayList(); the strings would not have been sorted, and duplicates would be allowed. Speaking of once and only once: it is very nice that by a single change to the program (the initialization of coll), it is possible to change its behaviour. No adaptations to the declarations, or to methods actionperformed and/or paint are necessary. Vector: a historical mistake The large and well-designed library for collections that was described in this section is an innovation in Java 1.2. Before that, some simpler classes were in use. In older Java programs you might encounter them, and therefore we ll mention them here. However, their use is deprecated in new programs. Class Vector was used where today we would use an ArrayList. Its methods didn t comply to interface List: instead of set they used setelementat, instead of get they used elementat. Today, Vector indeed does implement List, by defining additional methods get and set (that just call elementat and setelementat). But why not just use an ArrayList? Abstract class Dictionary was the predecessor of what today is interface Map. Class Hashtable was a concrete subclass of Dictionary. In new programs, rather use HashMap. To iterate over a Vector an interface Enumeration existed. Rather use an Iterator Extensions of AWT The limitations of AWT In practically all of our programs, we ve been using java.awt to create a graphical user interface (GUI). The framework of an interactive program which uses AWT is relatively simple at least once you understood how ActionListeners work... An additional advantage is that the Java philosophy is used: a program is not specific for a particular platform; you can view an applet with (practically) any browser using (practically) any operating system. It explains the A in AWT : it is an abstract toolkit, that can be used without even knowing which concrete windowing system underlies it. Yet, as soon as you write more serious projects, which have to meet professional standards, you ll suffer from the limitations of AWT. Two of its major shortcomings are: with class Graphics you can draw lines, circles, symbols and even bitmaps, but some operations are impossible. Most irritating is that you can t set the width of the lines that are drawn by drawline. in package java.awt there are classes for buttons, textfields, choice lists and check boxes, but that s about it. A standard combobox, as is often seen in MS-Windows programs, is not possible, let alone a fancy treeview by which you can visualize hierarchical structures. The limitations of Graphics are a result of bad design. The problems are solved in the new class Graphics2D, which will be described below. The limitations of AWT stem from the principal choice for a heavy weight GUI library. With modern fast computers, this choice is not a necessity any more, so alternative GUI libraries have become possible. Heavy weight and light weight GUIs All modern operating systems support the programming of a graphical user interface (GUI). Apple was the first commercial provider of GUIs, having a Macintosh look&feel, Microsoft followed with Microsoft Windows, for Unix we have Motif, and Linux has KDE. GUIs tend to be addictive: once you get used to a particular look&feel, you know what you can expect from various controls: when menus pop up, how to use keyboard shortcuts, etc. As these things differ among platforms, a Macintosh user feels a stranger when forced to work on a Windows system, and vice versa. As long as everyone sticks to his own platform, there is no problem. But in the case of Java, which claims to be platform independent, there is a problem. Various platforms offer different primitives for composing GUIs. That is why in Java the window toolkit is abstract, i.e., as a programmer you do not directly access the primitives for the platform. The toolkit translates abstract ideas from the program to concrete operating system calls. This approach has two advantages: the GUI can be fast, as it uses the highly optimized primitives the operating system provides. the user feels at home: buttons etc. exacly look and feel as they do in other programs.

13 12 Object oriented design But there are also some drawbacks: Java can only provide the controls that are common to all platforms. Buttons are available on any platform, but a Macintosh doesn t provide a combobox as MS-Windows does, and MS-Windows doesn t provide the slider controls that are available in Motif. So AWT restricts itself to the lowest common denominator of all systems. as a Java programmer you can t control the exact look of a GUI: it might be different on any system. This may result in unpleasant surprises. A GUI toolkit that heavily uses the underlying operating system is known as a heavy weight GUI toolkit. AWT is a heavy weight GUI toolkit. So, what is a light weight toolkit? Here, the usage of the underlying operating system is restricted to a minimum. It needs to pass keyboard and mouse events, and be able to draw graphics to the screen, but doesn t need to have controls. The entire lay out of the controls, including the 3D suggestion that a button is pressed, is determined by the Java library. Is this a good idea? A possible problem might be that it is slow. A simulation of a button can never be just as fast as the built in buttons of the operating system. In the early days of Java this was a reason to make AWT a heavy weight toolkit. But even a low end computer of today can easily handle light weight GUI toolkits. An advantage of a light weight GUI toolkit is that it can provide all sorts of fancy controls. A newly designed toolkit can do so adhering to the latest object oriented ideas. A dilemma is how a light weigt GUI should look (and feel): à la Microsoft? à la Motif? or neither of the two, but entirely new? Since version 1.2, Java provides a light weight GUI toolkit, by means of package javax.swing, affectionately known as Swing. It is fast enough, and has many interesting controls. The designers solved the above mentioned dilemma by providing a configurable look&feel. Standard there are three: Motif, Windows, and another one which didn t exist before, named Metal. In principle any look&feel can be used on any system that s the whole idea about a light weight GUI: it simulates all controls without using the operating system primitives for them. Cool: we could have a Metal-look on a Windows computer, a Motif-look on a Macintosh, or a Windows-look on a Unix system. Unfortunately, Microsoft wasn t amused on foreign systems having a Windows look&feel. Consequently, the Microsoft-look is now disabled on non-windows systems. The default look&feel is Metal. The user can make another choice by some rather cryptic options to the Java interpreter. But the programmer can overrule that by calling a method from main that selects the look&feel of the target computer: UIManager.setLookAndFeel( UIManager.getSystemLookAndFeelClassName() ); or enforce the Metal look&feel with: UIManager.setLookAndFeel( UIManager.getCrossPlatformLookAndFeelClassName() ); In class UIManager more methods are available, a.o. to inquire whether non-standard additional look&feels are present. You may become an expert in these matters by reading a lot in the online documentation or you can just stick to the default settings... Classes in Swing As in AWT, Swing provides a class for each type of interaction component. For distinguishing them from the corresponding classes in AWT, their names begin with a J. So whereas Button is an AWT-button, JButton is a Swing-button. The classes for a top level window, such as JApplet and JFrame, are the only heavy weight components of Swing. They are an immediate extension of the corresponding classes in AWT. All other components are light weight; they are an extension of the abstract class JComponent, which in turn is an extension of AWT-class Container. The latter fact is a bit surprising, because not every JComponent is designed to actually contain things. But some of them, like JPanel and Box can, and for other controls, like JButton and JSlider it doesn t harm. Indirectly all components are a subclass of Component as well. In contrast with AWT, also menu related classes (like JMenu and JMenuBar) are part of the JComponent hierarchy. As a result, menus can be a standard part of the layout. So even applets can have a menu now: let the applet have a BorderLayout and add a JMenuBar-component in the north. A small difference between JApplet and JFrame at one hand, and their AWT counterparts Applet

14 17.3 Extensions of AWT 13 Figuur 2: Components in Swing (and in AWT)

15 14 Object oriented design and Frame on the other hand, is that Swing containers cannot have components added to them directly using add. Instead, you need to call method getcontentpane. It yields a Container, to which you can add components. That container always has a BorderLayout, even in applets. Of course, you can change that to a FlowLayout if needed. Here is a very simple AWT applet creating a single button: class Hello extends Applet { public void init() { Button b = new Button("press here"); this.add(b); This is the corresponding version using Swing: class Hello extends JApplet { public void init() { JButton b = new JButton("press"); Container c = this.getcontentpane(); c.setlayout( new FlowLayout() ); c.add(b); A final difference between AWT and Swing is the behaviour of paint. Because of the light weigth nature of Swing, paint now also is responsible for drawing the components in the container. But if in a panel you have sub-components, but also a drawing in the background, there is a problem: when re-defining paint as usual, the buttons disappear! You have to redefine paintcomponent instead, which is responsible for drawing the component without sub-components. Unfortunately this does not work in the toplevel JApplet, which is not light weight. So avoid to both add subcomponents and drawing a picture in the toplevel applet. Instead, add canvases on which to draw. Well, not actually a canvas, because there is no class JCanvas. When you need a canvas in a Swing program, just use a JPanel. In section 17.4 an extensive example program is given, that makes use of the Swing toolkit. It also demonstrates how to use Action: an interface defined in Swing, that is an enhanced version of an ActionListener. It is beyond the scope of this text to discuss all 50 Swing components. In figure 2 some are enumerated, some more are used in the example program in section For even more classes consult the online documentation when needed. Graphics2D Whenever you want to make a drawing in Java, you need to use class Graphics. An object having this type has three roles: It is an abstraction of the medium to paint on. It can be a component, or a bitmap in memory, or a printer, etc. It has memory for some attributes: the current pen color, to be changed by setcolor the current font, to be changed by setfont a rectangle to limit the drawing to, to be changed by setclip the origin of the coordinate system, to be changed by translate the current drawing mode: XOR or normal the background color: not changeable, but used in clear It provides methods to draw things: lines, using drawline outline figures using drawrect, drawoval, and four more solid figures using fillrect, filloval, and four more text using drawstring images using drawimage These are rather limited capabilities. For example, there is not a current line width attribute, you cannot draw curves (other than arcs), and although you can fill rectangles, you cannot use non-solid fill patterns.

16 17.4 Application: a sketch program 15 These drawbacks are solved in a subclass of Graphics known as Graphics2D. (In the future we might even have a class Graphics3D). How can you obtain such a Graphics2D-object, in order to use the additional capabilities? The answer is that (starting form Java 1.2) a Graphics2D-object is simply passed to paint. However, the method header of paint was not modified in Java 1.2 for backward compatibility (old programs wouldn t compile anymore). But if you are sure that your programs will be used with an interpreter version 1.2 or later, you can simply cast the parameter of paint to Graphics2D: public void paint(graphics g) { Graphics2D g2 = (Graphics2D) g; // cast g2.setstroke( new BasicStroke(10) ); // set line width g2.drawline(0,0,100,100); // draw thick line What can be done with a Graphics2D object? Of course anything that can be done with Graphics, as it is an extension. Furthermore, a Graphics2D-object provides: additional memory for extra attributes: the background color that now can be changed the current line style, consisting of width, dot style, and endpoint shape the current fill style: solid, having a pattern (texture), or a gradient from one colour to another the current mechanism to combine new colors with existing ones the current roration and/or magnification some hints which might influence image quality new methods for drawing things: generic methods draw and fill to draw an arbitrary Shape-object. The Shape-object to be drawn can denote a simple rectangle, but also a complicated curve. The example above shows how to set the line width: create a BasicStroke-object, and pass it to setstroke. Apart form the constructor method of BasicStroke that is used here (which only needs a line width), there are variants for setting the line styles. See online documentation for details. The fill style can be specified by calling setpaint passing either a TexturePaint-object or a GradientPaint-object, or just a Color for solid filling. By calling setrenderinghint you can set additional options regarding image quality. Higher quality might increase drawing time, and not every Graphics-object can respond to every hint, but they ll try. Here is an example usage: g2.setrenderinghint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON ); After this hint, the Graphics-object will try to smoothen the edges of oblique lines, thus avoiding the characteristic zigzag effect often seen in computer graphics. Try and see it, and when you are dissatisfied, just set the hint... OFF! 17.4 Application: a sketch program Description of the program In this section we ll write a complete drawing program. In figure 4 a snapshot of the program is shown. Unlike the bitmap editor from an earlier chapter, this program shows tools to draw various shapes: pen, line, open en solid rectangle, and an eraser. Also, a tool for adding text is available. Apart form the tools, there are some additional controls near the bottom of the window: a button to clear the picture, one to rotate it (the implementation of which is left as an exercise to the reader), and a combobox to choose a color used for drawing. After selecting a rectangle tool, the user can drag a block on the canvas. The area selected is shown with a gray contour, and only after realeasing the mouse button the rectangle is drawn permanently. Tools can be selected either by the buttons near the left edge, or by selecting items from drop-down menu Tool. The functionality of th controls (Clear, Rotate) is also available from menu Edit. This redundant style of providing control to the user is often used in professional quality programs, and it is a challenge to the programmer to program this without violating the once and only once principle! Here, that is particularly important, as the program will probably have new versions with additional tools. It would be nice if with a single change of the program code, the new tool

17 16 Object oriented design would appear both in the toolbox and in the tool menu. The GUI is built using Swing. Both an application and an applet version are available; thanks to Swing, even the applet version can have a menu. Outline of the program For a change, we have not been economizing on the number of classes in this program. Consequently, it consist of not less than 22 classes. In figure?? their hierarchical relations are shown, and also their dependence on classes in Swing and AWT. It is important to study the diagram thoroughly before reading the details of the program, otherwise all of these classes will look the same to you... The large number of classes is typical for a rigorous object oriented design. The listings of the classes in isolation are not very surprising. Many listings are quite short, only containing a few methods each containing just a few statements. The magic is in the cooperation of the classes. Design of class structure Before we investigate the classes in detail, let s have a bird s eye view on their role in the program. It starts with an idea borrowed from the bitmap editor: there are separate classes for application, applet and the proper canvas, and there is a class that models what is visible on the canvas. SketchApplic is the entry point for the application. It contains method main that creates the window. The window contains only one component: the complete applet version of the program. (The corresponding class in the bitmap program had to create a menu, but that s not necessary here: thanks to Swing we can do this in the applet, which is part of the application.) SketchApplet is responsible for building the GUI: the canvas, a toolbox, a menu, and the control panel. This listing is the longest one of the program, mainly because building a GUI, as always, is a lengthy process. We have a member variable containing the canvas (as it is quite often needed), and a member variable for storing the currently chosen tool. Finally, there is a boolean indicating whether this is a stand-alone applet, or a part of an application: for these two cases there is a separate constructor method. The object listens to mouse motion and keyboard actions on the canvas: when something interesting happens, it notifies the current tool. Also, it listens to item changes in the color choice combobox: whenever something happens, it notifies the canvas. However, it does not listen to buttons and menu items: these listen to themselves! (see below). SketchCanv is the proper canvas showing the drawing. There is a member variable storing the model of the drawing, and one for storing the current pen color. The model can draw itself and resize itself, so the methods in SketchCanv merely pass requests to do so to the model. Sketch is the model of the drawing. The actual storage of the image is delegated to a BitMapobject, which we already programmed in an earlier chapter (write classes once and only once, and re-use them!). To resize a drawing, the bitmap is replaced by a new one having new dimensions, in which the old bitmap is copied. As you know, an ActionListener object can react upon user actions. Swing defines an extension to this interface: Action. Apart form a listener, it defines some additional properties, such as a name, an explanation, an abbreviation, and an icon which belong to this action. As an aid to implementing the Action interface, Swing defines an abstract class AbstractAction which implements Action, and which provides some convenience methods for setting common properties. An Action-object bundles all information that is important to an action: both for displaying it in a menu (using the name and/or the icon), and for handling the action when it is selected by the user. We ll use this mechanism in the program, defining three specialized classes AboutAction, ToolAction, and ControlAction, that collect all relevant information for the three types of action that occur in the sketch program. For the behaviour of an icon, Swing provides an interface: Icon. It specifies that an icon needs to be able to draw itself, and that it should know its size. Swing also defines an implementation: ImageIcon. We use it in the program for the pen and eraser icons. The other icons, however, are drawn in a different way. They show a mini instance of drawings that we need to be able to draw anyway on the canvas (line, outline or filled rectangle, text).

18 17.4 Application: a sketch program 17 Figuur 3: Classes in the Sketch program

19 18 Object oriented design page 21 page 21 page 22 page 28 page 23 We adhere to the once and only once priciple by re-using that in custom implementations of Icon: TextIcon for the text, and TwopointIcon for figures having a startpoint and an endpoint (line, rectangle). In a true object oriented style, the common thing of these two classes (viz., the dimensions of the icon) is placed in a nabstract class ToolIcon. Defining interfaces is not limited to standard libraries: we can define interfaces ourself, and subsequently implement them in classes. We ll use that here for defining the notion of a Tool. A tool is an object that can interpret mouse (and keyboard) actions as scribbles on a sketch-canvas. In interface Tool we therefore specify four methods that model this idea in the form of methods-with-parameters. Abstracte class StartpointTool elaborates on this for the case where a startpoint is needed, that has to be saved until the user has completed specifying the thing to be drawn. The class is abstract, because we have not yet said what will be drawn starting at the starting point. In the program, two kinds of tool extend the notion of a StartpointTool: TextTool, that shows a text at the startpoint, and TwopointTool for tools that apart form a startpoint also need a second point. The latter is abstract, because we have not yet said what will happen to the two points. LineTool and RectTool are concrete extensions of the abstract TwopointTool. FillRectTool is the same as RectTool as far as the positioning is concerned, but the final drawing is different. By defining a subclass of RectTool, we inherited the methods which are the same for outline and filled rectangles, thus adhering the once and only once principle. Even PenTool can inherit some methods, namely from class LineTool. After all, a pen drawing is just a sequence of (short) straight lines. Furthermore, an erasure by the eraser is essentially a broad, white line, and therefore we define EraserTool to be a subclass of PenTool. We ll now discuss the details of some of the classes. Refer to the listing of the classes while reading the description! Class SketchApplet The listing of class SketchApplet is distributed over four pages, starting with listing 2. In listing 2 we have method init. Here, the GUI is built: canvas, toolbar, controlpanel, and menu. First, the actions that are needed in the toolbar and controlpanel are gathered. For readability this is done in separate methods maketoolactions and makecontrolactions. Collections come in handy to store the actions (we could have used an array alternatively). The collections returned by the make-methods are passed to three methods, that create the proper toolbox, controlpanel and menu. Again, this is done in separate methods. Each of these returns a Component which is placed along the borders of the applet, or rather: the borders of the container obtained by getcontentpane, as that is the way it should be in Swing programs. The other non-trivial method in this listing is getimageicon. It calls a suitable constructor of Swing class ImageIcon, depending on the fact whether this is a stand alone applet or a part of an application. In listing 3 (still part of class SketchApplet) the methods that create the action-collections are placed. The caller of the methods (i.e. method init) only requires a collection, but we should decide for a concrete implementation of a collection (see the hierarchy in figure 1). As it is convenient that the elements appear in the same order as we describe them, we have to choose a list rather than a set. Which of the two list implementations to choose is arbitrary in this case; instead of LinkedList we could just as well have chosen ArrayList. The lists consist of separate Action-objects, or more precisely: ToolActions in maketoolaction and ControlActions in makecontrolactions. When carefully counting the parameters, you ll notice that there are various constructor methods for ToolAction: one for actions having an image as an icon, and one for actions having a custom drawn icon. These constructor methods are defined in listing 13. The details for building the GUI are in listing 4. The controlpanel is a JPanel, consisting of two parts: a row of buttons, stored in a JToolBar, and a JComboBox for choosing the pen color. Using an Iterator (zie section 17.2) the actions are added to the toolbar one by one. The nice thing of a JToolBar is that you can directly add Actions to it: creating the button and linking it to an ActionListener is done automatically. All required information can be found in the Action object. Also JMenu can digest Action objects, so building the menu is easy.

20 17.4 Application: a sketch program 19 For creating the toolbox we could have used another JToolBar. However, it would create a toolbar with text buttons only, whereas in a typical toolbar icons are commonly used. That is why the toolox is not a JToolBar object here, but simply a Box (this is the only Swing component not starting with a J). The price is that we have to create the buttons ourselves, and link them to actionlisteners. This gives you an idea of what JToolBar does behind the scenes. A combobox is given items by calling additem. That method can process any object knowing how to tostring, which is practically any object; particularly objects of class ColorName that we define for the purpose (see listing 9). page 26 Fourth and final part of SketchApplet is in listing 5. Here, sundry event-listening methods are page 24 defined. The relevant mouse events (but not the irrelevant ones) and keytyped are passed to the currently selected Tool, at the same time passing the identity of the canvas: after all, the tools must operate on the canvas. Interface Tool (see listing 17) was custom built to receive notifications page 30 like that. Method itemstatechanged processes changes to the color choosing combobox. Here, we extract the color that is chosen from the ColorName-object, and make it into the current pen color stored by the canvas. Class SketchCanv and its model Sketch As said, class SketchCanv (see listing 7) stores the current pen color in a private Color member. It page 25 can be changed by calling setpencolor. A second member variable stores a Sketch-object, which in turn (see listing 10) contains a BitMap-object. We already defined it in the previous chapter page 27 (see listing??); it was an extension of library class BufferedImage. page?? Consequently, in class SketchCanv we have access to various Graphics objects: the Graphics which is available in any Component, and can be obtained by method getgraphics inherited from Component. We ll use it to temporarily modify the canvas while the user is dragging a block. the Graphics attached to the bitmap, which is stored by the Sketch-object. We ll use it to store the permanent image. To provide access to both objects, we define an additional method getgraphicspermanent, which returns the Graphics object of the bitmap. Note that externally the current pen color is not available. The member is private, and there is no method getpencolor. Instead, the current pen color is pre-selected before returning a Graphics to external partners. A Sketch is able to draw itself. It does so (see listing 10) by simply drawing its bitmap. The only page 27 task Sketch handles additionally is resizing the bitmap whenever needed. The Icon-hierarchy According to the specification of interface Icon in Swing, an icon is an object that can denounce its width and height, and that can draw itself at a particular location on a particular Graphics. In Swing there is an implementation ImageIcon, which we use for the icons of pen and eraser. For our custom icons we begin with abstract class ToolIcon in listing 14. It implements two of three page 29 methods required: the denouncers of the dimension. Subclass TextIcon in listing 15 adds a third page 29 method, that draws a symbolic text of the right size. Another implementation of drawing is given in subclass TwopointIcon in listing 16. For the actual drawing, it uses a TwopointTool-object page 29 that was passed at its construction. The Action-hierarchy An Action is, according to the specification of this interface in Swing, an extended ActionListener. So at least it requires a method actionperformed. The extension specifies that an Action has some additional properties, such as name, explanation, and icon. All three of our implementations of Action therefore define a method actionperformed. Class AboutAction (see listing 11) reacts upon actions by showing an information dialogue (this is a page 27 neat demonstration of how to do that in Swing). The name "About" (that is shown in the menu) is passed to super, the constructor of superclass AbstractAction. Class ControlAction (see listing 12) reacts upon actions by clearing the canvas, or by any other page 28 operation that might be added in a future version of this program. The identity of the canvas is passed to the constructor method, and stored for later use. The remaining parameters of the constructor method are passed along to the superclass. Class ToolAction (see listing 13) reacts upon selecting particular tools (pen, line, eraser, etc). We page 28

21 20 Object oriented design page 22 page 30 page 30 page 30 page 31 page 31 page 32 page 32 page 32 page 32 simply notify the applet which tool to use from now on. The relevant tool should be passed to the constructor of the tool, and is stored for later use in actionperformed. Also, the identity of the applet is stored that way. Furthermore, the constructor takes name and explanation of the action as a parameter, which is just passed to the superclass. Finally, the fifth parameter of the constructor is an Icon. In listing 3 we pass an ImageIcon of either a pen image or an eraser image. But there is also a four-parameter version of the constructor. In this case, depending on the type of the fourth parameter, either a TextIcon or a TwopointIcon is created, which is passed to the five-parameter version of the constructor. The Tool-hierarchy The interface and the classes in this hierarchy are custom built for this program. They do not extend existing interfaces in Swing. In interface Tool (see listing 17) we specify what, in this program, is to be understood as a tool: an object that can operate on a SketchCanvas in response to pressing, dragging or releasing the mouse. The fact that a SketchCanvas is needed makes it specific for this program. Remember that the applet was designed that in the case of mouse events, one of these methods of the currently active tool is called. All tools are implemented as implementations of this interface. We start with an abstract class StartpointTool (see listing 18), that provides one of the four methods required. A startpoint tool reacts on mouse presses by storing the point for later use in a member variable that was declared for the purpose. Class TextTool in listing 19 is a concrete extension of it. It defines that when dragging or relasing the mouse nothing needs to be done, but that in the event of typing a symbol, it should be drawn at the position stored in the startingpoint. Next, the x-coordinate of the startpoint is incremented by an amount depending on the properties of the font. Some browsing through the online manual reveals that we need a FontRenderContext for determining the exact amount of pixels. Clss TwopointTool in listing 20 is another extension of StartpointTool. It reacts to dragging the mouse by drawing a gray outline. When the mouse is released, the figure is drawn permanently. Key presses are ignored by these kind of tools. Thus, all four methods required by interface Tool are implemented, but we introduced two more: drawoutline en drawfigure. We can give a default implementation for drawfigure, viz., doing the same as drawing an outline. However, we can t express how to draw an outline, as it is not yet determined whether we should draw a line, rectangle, or circle. Therefore method drawoutline is declared abstract, and thus needs to have no body. The price is that the class as a whole is abstract as well. Extensions to this abstract class are concrete subclasses LineTool in listing 21 and RectTool in listing 22. Each of these implement the remaining method drawoutline in their own way. The default implementation for drawing the final figure is fine for these tools. Class FillRectTool in listing 23 inherits drawing the outline from RectTool, but redefines the final figure, thus replacing the default behaviour. Here, the figure is drawn using fillrect. The implementation of PenTool in listing 24 is subtle. It redefines method mouseblock: whenever the mouse is dragged, we simulate that the mouse is released and pressed again. Those methods were already defined in LineTool, and draw a line to the current point, where subsequently a new line segment is started. Consequently, a line segment is drawn whenver the mouse is dragged just the thing we need for a pen. Class EraserTool in listing 25 finally is an extension to PenTool. While drawing the contour (and also when drawing the final figure, because for lines, and thus pens, and thus erasers, the final figure is the same as the contour) we first select a line width of 7 pixels, and pen color white. Then, the original method from the superclass is called (by means of super). So, an eraser is about the same as a pen, only drawing a wide white line instead of a thin colored line.

22 17.4 Application: a sketch program 21 import java.awt.*; import java.awt.event.*; import java.util.*; import java.net.url; 5 import javax.swing.*; public class SketchApplet extends JApplet implements MouseListener, MouseMotionListener, ItemListener, { 10 SketchCanv canvas; Tool currenttool; boolean ispartofapplication; KeyListener public SketchApplet() 15 { this(false); SketchApplet(boolean app) { this.ispartofapplication = app; 20 if (app) this.init(); public void init() { canvas = new SketchCanv(); 25 Collection tools = maketoolactions(); Collection controls = makecontrolactions(); Container c = this.getcontentpane(); c.setlayout(new BorderLayout()); 30 c.add(canvas, BorderLayout.CENTER); c.add(maketoolbox(tools), BorderLayout.WEST ); c.add(makemenubar(tools, controls), BorderLayout.NORTH ); c.add(makecontrolpanel( controls), BorderLayout.SOUTH ); 35 canvas.addmouselistener(this); canvas.addmousemotionlistener(this); canvas.addkeylistener(this); 40 public void setcurrenttool(tool tool) { currenttool = tool; private ImageIcon getimageicon(string filename) 45 { try { if (ispartofapplication) return new ImageIcon(filename); else return new ImageIcon(new URL(this.getCodeBase(), filename)); 50 catch (Exception e) { return null; Listing 2: Sketch/SketchApplet.java, part 1 of 4

23 22 Object oriented design Figuur 4: Snapshot of the Sketch editor 55 private Collection maketoolactions() { currenttool = new PenTool(); LinkedList result; result = new LinkedList(); 60 result.add( new ToolAction(this, "Pen", "Freehand drawing", currenttool, getimageicon("pen.gif"))); result.add( new ToolAction(this, "Line", "Line drawing", new LineTool())); result.add( new ToolAction(this, "Open rect", "Open rectangle", new RectTool())); result.add( new ToolAction(this, "Fill rect", "Filled rectangle", new FillRectTool())); 65 result.add( new ToolAction(this, "Text", "Text", new TextTool())); result.add( new ToolAction(this, "Eraser", "Eraser", new EraserTool(), getimageicon("eraser.gif"))); return result; 70 private Collection makecontrolactions() { LinkedList result; result = new LinkedList(); result.add( new ControlAction(canvas, "Clear", "Clear drawing" )); 75 result.add( new ControlAction(canvas, "Rotate", "Rotate drawing")); return result; Listing 3: Sketch/SketchApplet.java, part 2 of 4

24 17.4 Application: a sketch program 23 private Component makecontrolpanel(collection controls) 80 { JPanel controlpanel = new JPanel(); JToolBar toolbar = new JToolBar(JToolBar.HORIZONTAL); toolbar.setfloatable(false); for (Iterator iter=controls.iterator(); iter.hasnext(); ) 85 toolbar.add((action) iter.next()); controlpanel.add(toolbar); controlpanel.add(box.createhorizontalstrut(20)); controlpanel.add(new JLabel("Pencolor")); 90 JComboBox combo = new JComboBox(); combo.additem( new ColorName("black", Color.black) ); combo.additem( new ColorName("red", Color.red ) ); combo.additem( new ColorName("green", Color.green) ); combo.additem( new ColorName("blue", Color.blue ) ); 95 combo.additemlistener(this); controlpanel.add(combo); return controlpanel; private Component makemenubar(collection tools, Collection controls) { JMenuBar menubar = new JMenuBar(); JMenu menu; Iterator iter; menu = new JMenu("Tool"); for (iter=tools.iterator(); iter.hasnext(); ) menu.add((action) iter.next()); menubar.add(menu); menu = new JMenu("Edit"); for (iter=controls.iterator(); iter.hasnext(); ) menu.add((action) iter.next()); menubar.add(menu); menu = new JMenu("Help"); menu.add(new AboutAction()); menubar.add(menu); 120 return menubar; private Component maketoolbox(collection tools) { Box toolbox = new Box(BoxLayout.Y_AXIS); 125 for (Iterator iter=tools.iterator(); iter.hasnext(); ) { Action a = (Action) iter.next(); JButton button = new JButton((Icon) a.getvalue(action.default)); button.settooltiptext((string) a.getvalue(action.short_description)); button.addactionlistener(a); 130 toolbox.add(button); toolbox.add(box.createverticalglue()); return toolbox; Listing 4: Sketch/SketchApplet.java, part 3 of 4

25 24 Object oriented design public void mousepressed(mouseevent e) { this.currenttool.mousedown (e.getpoint(), canvas); 140 public void mousereleased(mouseevent e) { this.currenttool.mouseup (e.getpoint(), canvas); public void mousedragged(mouseevent e) 145 { this.currenttool.mouseblock (e.getpoint(), canvas); public void mouseclicked(mouseevent e) { canvas.requestfocus(); 150 public void itemstatechanged(itemevent event) { Object item = event.getitem(); if (item instanceof ColorName) 155 canvas.setpencolor( ((ColorName)item).getColorName() ); public void keytyped(keyevent e) { this.currenttool.symboltyped((char) e.getkeychar(), canvas); 160 public void keyreleased(keyevent e) { public void keypressed(keyevent e) { public void mouseentered(mouseevent e) { 165 public void mouseexited(mouseevent e) { public void mousemoved(mouseevent e) { Listing 5: Sketch/SketchApplet.java, part 4 of 4 import java.awt.event.*; public class WindowCloser extends WindowAdapter { public void windowclosing(windowevent e) 5 { System.exit(0); Listing 6: Sketch/WindowCloser.java

26 17.4 Application: a sketch program 25 import java.awt.*; import javax.swing.*; class SketchCanv extends JPanel 5 { private Sketch schets; private Color penkleur = Color.black; public SketchCanv() 10 { schets = new Sketch(); public void update(graphics g) { paint(g); public void paint(graphics g) { schets.draw(g); public void setbounds(int x, int y, int w, int h) { schets.resize(w, h); super.setbounds(x, y, w, h); repaint(); public void repaintnow() { this.paint(this.getgraphics()); public Graphics getgraphicspermanent() { Graphics g = schets.getgraphics(); g.setcolor(penkleur); return g; 35 public void setpencolor(color c) { penkleur = c; public void clear() { schets.clear(); this.repaint(); Listing 7: Sketch/SketchCanv.java

27 26 Object oriented design import java.awt.*; import javax.swing.jframe; public class SketchApplic extends JFrame 5 { SketchApplic() { this.setsize(800,600); this.settitle("sketch editor"); this.setbackground(color.lightgray); 10 this.addwindowlistener( new WindowCloser() ); this.getcontentpane().add( new SketchApplet(true), BorderLayout.CENTER); public static void main(string[] args) 15 { new SketchApplic().show(); Listing 8: Sketch/SketchApplic.java import java.awt.color; class ColorName { String name; 5 Color kleur; public ColorName(String name, Color kleur) { this.name = name; this.kleur = kleur; 10 public Color getcolorname() { return kleur; public String tostring() 15 { return name; Listing 9: Sketch/ColorName.java

28 17.4 Application: a sketch program 27 import java.awt.*; class Sketch { 5 private BitMap bitmap; Sketch() { bitmap = new BitMap(1,1); 10 public void draw(graphics g) { g.drawimage(bitmap, 0, 0, null); 15 public void resize(int w, int h) { if (w!=bitmap.getwidth() h!=bitmap.getheight()) { BitMap extra = new BitMap(w, h); extra.getgraphics().drawimage(bitmap, 0, 0, null); 20 bitmap = extra; public Graphics getgraphics() 25 { return bitmap.getgraphics(); public void clear() { bitmap.clear(); 30 Listing 10: Sketch/Sketch.java import java.awt.event.*; import javax.swing.*; public class AboutAction extends AbstractAction 5 { public AboutAction() { super("about"); 10 public void actionperformed(actionevent event) { JOptionPane.showMessageDialog( null, "SketchEditor version 1.0", "About", JOptionPane.INFORMATION_MESSAGE 15 ); Listing 11: Sketch/AboutAction.java

29 28 Object oriented design import java.awt.event.*; import javax.swing.*; public class ControlAction extends AbstractAction 5 { private SketchCanv canvas; public ControlAction(SketchCanv canvas, String name, String tip) { super(name); this.canvas = canvas; 10 putvalue(action.short_description, tip); public void actionperformed(actionevent event) { String name = (String) this.getvalue(action.name); 15 if (name.equals("clear")) canvas.clear(); Listing 12: Sketch/ControlAction.java import java.awt.event.*; import javax.swing.*; public class ToolAction extends AbstractAction 5 { protected Tool tool; protected SketchApplet applet; public ToolAction( SketchApplet applet, String name 10, String tip, Tool tool, Icon icon ) { super(name /*,icon */ ); // two parameters produces icons in menus this.applet = applet; this.tool = tool; 15 putvalue(action.default, icon); putvalue(action.short_description, tip); public ToolAction(SketchApplet applet, String name, String tip, TwopointTool tool) 20 { this(applet, name, tip, tool, new TwopointIcon(tool) ); public ToolAction(SketchApplet applet, String name, String tip, TextTool tool) { this(applet, name, tip, tool, new TextIcon() ); public void actionperformed(actionevent event) { applet.setcurrenttool(tool); Listing 13: Sketch/ToolAction.java

30 17.4 Application: a sketch program 29 import java.awt.dimension; import javax.swing.icon; public abstract class ToolIcon implements Icon 5 { private Dimension dim = new Dimension(36, 36); public int geticonwidth() { return dim.width; public int geticonheight() { return dim.height; Listing 14: Sketch/ToolIcon.java import java.awt.*; public class TextIcon extends ToolIcon { 5 public void painticon(component c, Graphics g, int x, int y) { int w = this.geticonwidth(), h = this.geticonheight(); g.setcolor(c.getbackground()); g.fillrect(x, y, w, h); g.setcolor(color.black); 10 g.setfont(new Font("Helvetica", Font.BOLD, h-5 )); g.drawstring("tx", x+2, y+h-2 ); Listing 15: Sketch/TextIcon.java import java.awt.*; public class TwopointIcon extends ToolIcon { private TwopointTool tool; 5 public TwopointIcon(TwopointTool t) { this.tool = t; 10 public void painticon(component c, Graphics g, int x, int y) { int w = this.geticonwidth(), h = this.geticonheight(); g.setcolor(c.getbackground()); g.fillrect(x, y, w, h); 15 g.setcolor(color.black); tool.setstartpoint( new Point(x+2, y+2 ) ); tool.drawfigure (g, new Point(x+w-3, y+h-3) ); Listing 16: Sketch/TwopointIcon.java

31 30 Object oriented design import java.awt.point; public interface Tool { 5 void mousedown (Point p, SketchCanv canvas); void mouseup (Point p, SketchCanv canvas); void mouseblock (Point p, SketchCanv canvas); void symboltyped (char c, SketchCanv canvas); Listing 17: Sketch/Tool.java import java.awt.*; public abstract class StartpointTool implements Tool { protected Point startpoint; 5 public void setstartpoint(point s) { startpoint = s; 10 public void mousedown(point p, SketchCanv canvas) { this.setstartpoint(p); Listing 18: Sketch/StartpointTool.java import java.awt.*; import java.awt.font.*; class TextTool extends StartpointTool 5 { private Font font = new Font("Helvetica", Font.BOLD, 24); public void symboltyped(char c, SketchCanv canvas) { String text = ""+c; 10 Graphics g = canvas.getgraphicspermanent(); g.setfont(font); g.drawstring(text, startpoint.x, startpoint.y ); FontRenderContext frc = ((Graphics2D)g).getFontRenderContext(); startpoint.x += font.getstringbounds(text, frc).getbounds().width; 15 canvas.repaint(); 20 public void mouseblock (Point p, SketchCanv canvas) { public void mouseup (Point p, SketchCanv canvas) { Listing 19: Sketch/TextTool.java

32 17.4 Application: a sketch program 31 import java.awt.*; public abstract class TwopointTool extends StartpointTool { 5 protected static Point minimumpoint(point p1, Point p2) { return new Point( Math.min(p1.x, p2.x), Math.min(p1.y, p2.y) ); protected static Dimension pointdistance(point p1, Point p2) 10 { return new Dimension( 1+Math.abs(p1.x - p2.x), 1+Math.abs(p1.y - p2.y) ); public void mouseblock (Point p, SketchCanv canvas) { canvas.repaintnow(); 15 Graphics g = canvas.getgraphics(); g.setcolor(color.gray); this.drawoutline(g, p); 20 public void mouseup (Point p, SketchCanv canvas) { Graphics g = canvas.getgraphicspermanent(); this.drawfigure(g, p); canvas.repaint(); 25 public void symboltyped (char c, SketchCanv canvas) { public void drawfigure(graphics g, Point p) 30 { this.drawoutline(g, p); public abstract void drawoutline(graphics g, Point p); Listing 20: Sketch/TwopointTool.java import java.awt.*; class LineTool extends TwopointTool { public void drawoutline(graphics g, Point p) 5 { g.drawline(startpoint.x, startpoint.y, p.x, p.y); Listing 21: Sketch/LineTool.java

33 32 Object oriented design import java.awt.*; class RectTool extends TwopointTool { public void drawoutline(graphics g, Point p) 5 { Point xy = minimumpoint(startpoint, p); Dimension wh = pointdistance(startpoint, p); g.drawrect(xy.x, xy.y, wh.width, wh.height); Listing 22: Sketch/RectTool.java import java.awt.*; class FillRectTool extends RectTool { public void drawfigure(graphics g, Point p) 5 { Point xy = minimumpoint(startpoint, p); Dimension wh = pointdistance(startpoint, p); g.fillrect(xy.x, xy.y, wh.width, wh.height); Listing 23: Sketch/FillRectTool.java import java.awt.point; public class PenTool extends LineTool { public void mouseblock(point p, SketchCanv canvas) 5 { mouseup(p, canvas); mousedown (p, canvas); Listing 24: Sketch/PenTool.java import java.awt.*; public class EraserTool extends PenTool { public void drawoutline(graphics g, Point p) 5 { ((Graphics2D) g).setstroke( new BasicStroke(7) ); g.setcolor(color.white); super.drawoutline(g, p); Listing 25: Sketch/EraserTool.java

34 17.5 File input/output File input/output Classes for file input/output There is a standard package containing over 40 classes related to doing input and output (or I/O for short) from and to files (not even counting the associated exception classes). This is package java.io. The classes are hierarchical structured; classes higher in the hierarchy are abstract classes. As always in object oriented design, the hierarchical ordering makes the concept graspable; without it, you would drown in the multitude of available classes. Unfortunately, the designers of java.io didn t exploit the full potential of a hierarchical ordering. That s why, in the description below, we ll add some hypothetical classes : these classes are not really part of package java.io, but they make the description clearer. The hierarchy is depicted in figure 5. As in earlier examples, classes ar shown as a yellow/lightgrey rectangle; abstract classes as a green/darkgrey parallelogram. Our hypothetical classes are shown as a backslanted parallelogram, with the name in italics. The arrows at the right hand side of the scheme do not belong to the hierarchy. They just show the type of the parameter of the constuctor method of the class they point to. At first sight the multitude of classes is rather overwhelming. But when we discuss the hierarchy step by step, you ll notice that there s method in it. We ll start the discussion at the top of the hierarchy. Here, class Object is shown, as Object is the superclass of any class in Java. Files: form or content? It is no surprise that in package java.io there is a class File, modeling a file. You might even wonder why we need 39 more classes... When constructing a File object, you pass the name of the file as a parameter. The creation of a File-object doesn t guarantee that the file indeed exists on the disk of the computer: a File-object models a possibly existing file. By calling method exists you can check whether the file exists in reality: File f; f = new File("hello.txt"); if (f.exists()) messagefield.settext("file exists"); Other methods, like isfile and isdirectory, which also have boolean result, check whether we have a proper file or with a directory. In the case of a directory, you might want to call listfiles, returning an array of File-objects describing the files in the directory. Java is designed to be platform independent. So we have to take care how the file name and the directory names are separated. Windows uses the character \, while Unix uses /. If you want to be unbiased to a particular platform, it is better to use the constant pathseparator, which is available in class File. Or use the File-constructor which takes two parameters: another File-object describing the directory, and a String containing the proper name. There are some more methods in File (see online help), but neither of these can read the contents of the file: they all process the file as a whole. To read the contents of a file, or to write new contents to a file, we need other classes, which are, like File, direct subclasses of Object. Stream-I/O versus Random-access-I/O There are two ways of accessing the contents of a file: as a continuous stream of information; that is: the information is read or written sequentially only with random access, where you can inspect or modify parts of the file at will. For the latter type, we have class RandomAccessFile. We won t elaborate on that here, but if you re interested you can consult online help for the available methods. For streams, there is a large number of classes. It would have been logical if these would have been subclasses of an abstract class Stream. This is not the case; there are four classes, each of which is a direct subclass of Object. But to give some structure to the picture, in figure 5 an abstract class Stream is drawn nevertheless. The backslanted parallelogram and italic name indicate that this is a hypothetical class, not really existing in the package. Byte-streams versus Character-streams Two types of streams can be distinguished:

35 34 Object oriented design Figuur 5: Classes for file input and output

36 17.5 File input/output 35 byte-streams, where each individual byte of the file can be processed by the program character-streams, where the content of a file is interpreted as characters, and possibly multiple bytes are combined into a single character. For these two types there are no abstract classes, but let s just pretend there were: Both types of streams are readable (examining the contents of an existing file) and writable (creating a new file). In the case of byte-streams use an InputStream or and OutputStream respectively, in the case of character-streams use Reader or Writer. You cannot interleave reading and writing to the same stream; use a random access file if you really need this. Until recently (in languages like C and C++) bytes and characters were considered to be the same. But as Java uses Unicode characters, having rather than 256 possible characters, this is not the case anymore. When you use character-streams, the necessary conversions are automatically performed. This way, you can read textfiles using the old ibm/dos character encoding, or the new ansi encoding, or the futuristic Unicode-encoding. Another conversion that is sometimes needed is the encoding of the newline symbol: whereas Windows uses two bytes (13 and 10), Apple uses only 13, and Unix uses only 10. By using character streams for reading textfiles, you can exchange textfiles transparantly among platforms. Byte-streams, by contrast, are more suitable for reading binary encoded files, where you really want to access each individual byte. Reading an writing Once you have an InputStream, you can call method read to read a single byte. You might expect the method to have byte as result type. This is not the case: it returns an int. The reason is, that we need an extra value to notice the end of the stream: read will yield the special value 1 in that situation. So now we can use tests like: int n; n = inpstr.read(); if (n==-1) messagefield.settext("nothing to read"); else messagefield.settext("value read is " + n ); Here, inpstr is the InputStream to read from. How to obtain such a stream will be discussed in the next subsection. Another way of reading is a call to method read, where an array of bytes is passed as a parameter. You can read many bytes in one go. The method result is the number of bytes read (the length of the array at maximum, or less if there were not that many bytes available). Writing to an OutputStream is done by calling method write, where you can either pass a single byte, or an array of bytes. Classes Reader and Writer also provide a method read and write respectively, but here the parameters are (arrays of) char rather than byte. In the case of Writer there is another version of write having a String as parameter; the string is nicely cut into characters, which are sent to the Writer. Construction of streams: subclasses of InputStream Once you created a stream (be it a byte stream in the form of an InputStream or an OutputStream, or be it a character-stream in the form of a Reader or a Writer), you can read and write things. But how can you obtain such a stream? It is not done by creating new objects of any of these four classes. The classes are abstract, and therefore cannot be instatiated. Instead, we ll have to make a choice for one of the available concrete subclasses. For InputStream the choice is as follows (and for the other three the subdivision is

37 36 Object oriented design similar). There are two ways of constructing an InputStream: directly, or an indirect, so-called filtered, inputstream: a FilterInputStream. To start with the direct constructions: again, there are two possibilities: a FileInputStream or a ByteArrayInputStream. A FileInputStream is used to read from a file. The File to be read from is passed as a parameter. Next, you can call method read; after all, it is a subclass if InputStream. For example: int n; File f; FileInputStream fis; f = new File("hello.txt"); fis = new FileInputStream(f); n = fis.read(); As a bonus, an alternative constructor of FileInputStream is available, which takes the name of a file instead of a File object. It saves you the trouble of first creating a File object. Another way of creating an InputStream is by constructing a ByteArrayInputStream. Here, too, you can use method read. This time, the data come from memory rather than from a real file. So, you can simulate the behaviour of a file in memory, without the rest of the program having to bother about it (the rest of the program can just rely on the fact that read is available, just as in the case of real files). Then we have some indirect ways of creating an InputStream. What makes them indirect, is that they need another InputStream, that has to be created first (for example a FileInputStream or a ByteArrayInputStream). It is passed to the constructor of the indirect stream, for example DataInputStream. All in all, it is quite some effort: File f; FileInputStream fis; DataInputStream dis; f = new File("hello.dat"); fis = new FileInputStream(f); dis = new DataInputStream(fis); but it is worth it: a DataInputStream provides some additional methods, allowing you for example to read binary encoded double values from a file: double d; d = dis.readdouble(); A BufferedInputStream is another indirect InputStream. Here, too, you first create another InputStream and pass it to the constructor. Having constructed a BufferedInputStream, you ll notice that it is faster than an ordinary FileInputStream, especially when dealing with slow network connections. A buffered stream fetches a large chunk of data in one go, buffers it, and does the retail selling. The rest of the program can just call read as usual, without having to bother with the buffering. Construction of streams: subclasses of OutputStream The subclass hierarchy under OutputStream is similar as the one under InputStream, and thus is as expected; see the large picture in figure 5. Again, there are two ways of creating a stream directly, and two indirectly. Subclass PrintStream of FilterOutputStream has no constructor,

38 17.5 File input/output 37 and thus cannot be instantiated; it is a historical mistake to be discussed in section Note that when constructing a ByteArrayOutputStream you don t have to pass a byte[]. The required array is automatically created, and grows when necessary. When, at some point, you want to use the array, you can fetch it by calling method tobytearray. Construction of streams: subclasses of Reader Character streams come in two types: Reader-classes (for input) and Writer-classes (for output). As with byte streams, you cannot instantiate the abstract classes, but you have to make a choice form the concrete subclasses. The hierarchical ordering is very much the same as with byte-streams. There are two direct ways of creating character-streams and two indirect ones (where you first need to construct another Reader). Again, you can choose to read from a real file, or from a string in memory. To read from a file, you first have to create an InputStream for that (which is a byte-stream). So even the direct way of creating a character-stream is not really direct: File f; FileInputStream fis; InputStreamReader isr; f = new File("hello.txt"); fis = new FileInputStream(f); isr = new InputStreamReader(fis); From the InputStreamReader thus constructed you can easily read characters. In practice, it is easier to read an entire line of text as one string. To be able to do so, we need another level of indirection: BufferedReader br; br = new BufferedReader(isr); A BufferedReader provides a method for reading an entire line of text: String s; s = br.readline(); It will yield exaclty one line of text from the file, where the newline character is already removed. When no more lines are available, it returns null (which is not the same as an empty line, which would be represented by an empty string). Construction of streams: subclasses of Writer The hierarchy under Writer is another variation on the same theme. Especially useful is PrintWriter. Objects of this type can write strings using method println, but also other primitive values, which are automatically converted to string. It takes some effort to create a PrintWriter-object, but the steps to be taken directly follow from the scheme: for construction, you need another Writer, which may be an OutputStreamWriter. For its construction you need an OutputStream, which may be a FileOutputStream. For its construction you need a File, and for its construction a String. You can do all steps in one large expression: PrintWriter pw; pw = new PrintWriter(new OutputStreamWriter(new FileOutputStream(new File("hello.txt")))); pw.println("this is printed to the file"); Convenience classes All in all, a common operation as reading or writing a file, is somewhat verbose. Therefore, packages java.io provides some additional classes, which do not really fit into the regular framwork, but which are quite useful in practice. Also, some of the regular classes have an alternative constructor. You can find these convenience classes in the scheme in figure 5: The constructor of FileInputStream needs a File-parameter, which in turn needs a Stringparameter (the file name). But you can also pass the string directly to the constructor of FileInputStream. The same holds for FileOutputStream. The constructor of InputStreamReader takes an InputStream parameter. Often, one uses a FileInputStream, that needs a File-parameter, that needs a String-parameter. A special subclass FileReader of InputStreamReader takes the File, or even the String, directly. The same holds for subclass FileWriter of OutputStreamWriter.

39 38 Object oriented design The constructor of PrintWriter takes a Writer parameter. Often, one uses an OutputStreamWriter, that needs an OutputStream. However, you can also pass the OutputStream directly to the constructor of PrintWriter Reading form a textfile can thus simply be done by: String s; BufferedReader br; br = new BufferedReader(new FileReader("in.txt")); s = br.readline(); And writing to a textfile is done by: PrintWriter pw; pw = new PrintWriter(new FileOutputStream("out.txt")); pw.println("some text"); page 39 Case study: text editor In listing 20 a fully functional text editor is shown. Most of the ideas have already been discussed above. Some minor details: There are two interaction components: a TextArea for the proper text, and a Label for displaying error messages. The menu items are not stored in variables. Therefore we cannot test the identity of e.getsource() in actionperformed. Instead (just as in the Calculator program in an earlier chapter) we retrieve the caption of the menu item by calling getlabel; the resulting string can be used to select the corresponding action. In response to menu choice Open method open is called. It asks the user for a file name. The proper reading is done in a separate method lees. Thus, the interaction with the user and with the file system is neatly separated. The separation immediately pays off. We can now call lees again from method main. Method main has an array of strings as parameter, that contains the strings the user supplied at the command line. Thus, we can read a file that was specified at the command line Non-window programs Console input/output Not every program needs a window to show its results. Although on PC s dos-programs are hardly used anymore, in the Unix culture it is rather common that programs generate text output to the console window they were started in by typing a command. These programs cannot use the mouse, and get all their user input from the keyboard. Class System Class System can be used in every Java program (even without importing it). There are two useful static variables, needed in console programs, available in this class: System.in and System.out. Their types are InputStream and PrintStream respectively. Variable System.in denotes the byte stream originating from the keyboard. All strings sent to System.out will appear as text on the console. A console-style Hello-program is surprisingly easy to write. No windows are needed, so no objects need to be created, and you don t need to define a subclass of Frame with a redefinition of method paint. Instead, directly from method main you can send text to the already existing object System.out: import java.io.*; class Hello { public static void main(string [] ps) { System.out.println("Hello!"); Object System.out is useful even in programs that do have windows: it can be used for showing debug information to the console while running. Even in applets it can be used; the output can be viewed by selecting menu item Java console from the browser.

40 17.6 Non-window programs 39 import java.awt.*; import java.awt.event.*; import java.io.*; 5 class Editor extends Frame implements ActionListener, WindowListener { TextArea tekst; Label status; FileDialog opendial, savedial; 10 private Editor() { tekst = new TextArea(20,60); status = new Label(); opendial = new FileDialog(this, "Open File...", FileDialog.LOAD); 15 savedial = new FileDialog(this, "Save File...", FileDialog.SAVE); this.setsize(400,350); this.settitle("simpele teksteditor"); this.addwindowlistener(this); 20 this.add(borderlayout.center, tekst); this.add(borderlayout.south, status); this.maakmenu(); 25 private void maakmenu() { MenuBar bar; Menu menu; MenuItem item; 30 bar = new MenuBar(); menu = new Menu("File"); item = new MenuItem("Open"); menu.add(item); item.addactionlistener(this); item = new MenuItem("Save"); 35 menu.add(item); item.addactionlistener(this); menu.addseparator(); item = new MenuItem("Quit"); menu.add(item); item.addactionlistener(this); bar.add(menu); 40 menu = new Menu("Edit"); item = new MenuItem("Upper"); menu.add(item); item.addactionlistener(this); item = new MenuItem("Lower"); 45 menu.add(item); item.addactionlistener(this); bar.add(menu); this.setmenubar(bar); Listing 20: Editor/Editor.java, part 1 of 3

41 40 Object oriented design 55 public void actionperformed(actionevent e) { MenuItem item; String keuze; item = (MenuItem) (e.getsource() ); keuze = item.getlabel(); if (keuze.equals("open")) 60 this.open(); else if (keuze.equals("save")) this.save(); else if (keuze.equals("quit")) System.exit(0); 65 else if (keuze.equals("upper")) this.vertaal(true); else if (keuze.equals("lower")) this.vertaal(false); 70 private void open() { String naam; opendial.show(); 75 naam = opendial.getfile(); if (naam!=null) this.lees(naam); 80 private void save() { String naam; savedial.show(); naam = savedial.getfile(); 85 if (naam!=null) this.schrijf(naam); private void vertaal(boolean upper) 90 { String inhoud; inhoud = tekst.gettext(); if (upper) inhoud = inhoud.touppercase(); else inhoud = inhoud.tolowercase(); tekst.settext(inhoud); 95 Listing 21: Editor/Editor.java, part 2 of 3

42 17.6 Non-window programs 41 private void lees(string naam) { String regel; BufferedReader invoer; 100 try { invoer = new BufferedReader( new FileReader(naam) ); tekst.settext(""); regel = invoer.readline(); while (regel!= null) 105 { tekst.append(regel + "\n" ); regel = invoer.readline(); invoer.close(); 110 catch (FileNotFoundException fnf) { status.settext("file " + naam + " bestaat niet"); catch (IOException io) { status.settext("leesfout in " + naam ); 115 status.settext(naam + " ingelezen."); private void schrijf(string naam) 120 { PrintWriter uitvoer; try { uitvoer = new PrintWriter( new FileWriter(naam), true); uitvoer.print( tekst.gettext() ); uitvoer.close(); 125 catch (IOException io) { status.settext("schrijffout in " + naam ); 130 public void windowclosing (WindowEvent e) {System.exit(0); public void windowclosed (WindowEvent e) { public void windowopened (WindowEvent e) { public void windowiconified (WindowEvent e) { 135 public void windowdeiconified(windowevent e) { public void windowactivated (WindowEvent e) { public void windowdeactivated(windowevent e) { public static void main(string [] params) 140 { Editor e; e = new Editor(); e.setvisible(true); 145 if (params.length>0) e.lees(params[0]); Listing 22: Editor/Editor.java, part 3 of 3

43 42 Object oriented design page 43 Example: grep-program A typical example of a console program is grep. It comes standard with Unix; the name abbreviates get regular expression pattern. We ll create a simplified version of this program in Java. When starting the program, a text must be specified at the command line (the so called pattern), as well as one or more file names. The program will show all lines from the file containing the pattern. The pattern and the file names are available in method main by means of the string-arrayparameter: the pattern is at position 0, and the file names at positions starting at 1. Because a similar action needs to be performed for all files, it is convenient to define a method for the purpose. It can be called for every file. In listing 23 this is method bewerk. It can (and must be) static, as there is no Frame-object involved. The remaining issue in method main is checking for the number of parameters. If not, a short message is shown to the user. Assignments have a result Up till now, we ve been using assignments as a statement. But assignments can also be used in place of an expression, i.e., they have a result value. The variable is assigned to as a side effect of calculating the value. The value of the assignment is of course the value that the variable just received. A simple example of such an assignment expression is: int x, y; x = (y=0); The assignment y=0 is used as an expression, that itself is used as a right hand side of an assignment statement to x. The assignment y=0 sets y to value 0. This also is the value of the assignment expression (y=0), so x is set to 0 as well. Of course, we could also have used two separate statements, as in: x=0; y=0; So what s the benefit of an assignment expression? Well, they are useful in a particular situation when reading files. In the editor program we had the following code to read all lines of a file: String line; line = input.readline(); while (line!=null) { text.append(line); line = input.readline(); Thus, there are two calls to method readline: first to read the first line, which needs to be done before the test line!=null is done. And next, at the end of the body of the while-statement, to read the next line. Using an assignment expression the two can be combined: we can assign the line variable as a side effect of testing it against null: while ( (line=input.readline())!= null) text.append(line); As there is only one statement in the body now, we can even discard the braces. In the example program, we also need a line number counter. This is done by using a for statement instead of a while statement: for (nr=1; (line=input.readline())!=null; nr++) text.append(nr + ":" + line); Reading from System.in Using System.in is slightly more complicated than System.out. Although you can use it to get single bytes from the keyboard, it is more useful to read strings in one go. Because strings consist of characters rather than bytes, we ll have to transform the InputStream which System.in is, to a Reader. It is done by passing System.in as parameter when constructing an InputStreamReader object. That object is subsequently used for creating a BufferedReader, from which we can read strings:

44 17.6 Non-window programs 43 import java.io.*; class Grep { 5 private static void bewerk(string patroon, String filenaam ) { BufferedReader br; InputStreamReader reader; String regel; try { if (filenaam.equals("")) reader = new InputStreamReader(System.in); else reader = new FileReader(filenaam); br = new BufferedReader(reader); for (int nr=1; (regel=br.readline())!= null; nr++) if (regel.indexof(patroon)!=-1) System.out.println( filenaam + " regel " + nr + ": " + regel ); 20 catch (Exception e) { System.out.println( filenaam + ": " + e ); 25 public static void main(string [] parameters) { switch (parameters.length) { 30 case 0: System.out.println("Usage: java Grep pattern [files]"); break; case 1: Grep.bewerk( parameters[0], "" ); break; default: for (int i=1; i<parameters.length; i++) 35 Grep.bewerk( parameters[0], parameters[i] ); Listing 23: Grep/Grep.java

45 44 Object oriented design InputStreamReader isr; BufferedReader br; String s; isr = new InputStreamReader(System.in); br = new BufferedReader(isr); s = br.readline(); In console programs like Grep it is customary to, when no file names are specified, read from System.in instead. That is why method bewerk contains an if-statement determining how the BufferedReader should be created: using an InputStreamReader as described above, or using an FileReader associated to a file. An error of history: PrintStream The object System.out is a byte-stream, more precisely an OutputStream, even more precisely a PrintStream. That class provides a method println, which can display a string. That s strange, because a string consists of characters, and converting it to bytes is done by a character-stream, more precisely a Writer, more precisely a PrintWriter. In older versions of Java (version 1.0) there was no difference between byte-streams and characterstreams. From version 1.2 on the constructor of PrintStream is deprecated, i.e. advised not to be used, as there are better alternatives (namely PrintWriter). For backward compatibility with older programs, the type of System.out is PrintStream rather than PrintWriter nevertheless. When using System.out just to debug your program, you ll hardly notice that it doesn t handle Unicode characters well. But for serious (international) use, you should wrap up PrintStream in a PrintWriter, as in: OutputStreamWriter osr; PrintWriter pw; osr = new OutputStreamWriter(System.out); pw = new PrintWriter(osr); pw.println(s); That is nicely symmetric to wrapping a System.in object in a BufferedReader, as in the preceding paragraph. Opgaven 17.1 Make Index Write a static method makeindex, specified as follows. The method takes an array of file names as a parameter. It should read these files, and write a new file named index.txt, which should contain a summary of the files. The summary shows, for each file, the following: The name of the file, as in filename: test.txt The number of lines, words and characters, as in: 12 lines 417 characters 74 words Newlines are not counted as characters. Words are separated by one or more spaces, periods, commas, semicolons of newlines. The longest word in the file, as in: longest word: supercalifragilisticexpialidocious At the end of the index, finally, the most difficult test is shown: most difficult: heavy.txt A text is more difficult than another text, when the average word length is larger. Files which cannot be read may be ignored, but this must me mentioned at the console: problem when reading bogus.txt

46 45 Chapter 18 Algorithms In the bitmap editor case study, emphasis was on building the GUI, and on class structure featuring frame, canvas and model. The actual data processing that it was all about (shifting, boldening etc. of the image) was rather simple after all. The sketch program was even more trivial in this respect: it merely draws just some lines and rectangles... What made this program complex was the strict adherence to the once and only once principle. In other programs, however, the data processing might be less trivial. In this chapter we study two cases: finding a route in a network, and recoginzing the language a text is written in, comparing it to example texts in known languages. Here, the algorithms, i.e. problem solving methods, are the central theme: we ll deliberately keep the GUI simple. Of course we ll use the classes described in earlier chapters, especially those for collections and files Case study: network search Case description The program described in this section is named Net. In enables the user to select two locations on a map (of roads, railroads, telecommunication links etc.), in reaction to which the program will search for the shortest (or fastest, or cheapest, or otherwise optimal) route between the two locations. The locations in the network, and the available links between them, are read from a file. It is shown graphically to the user. The user may click on two locations, upon which the route between them is shown in a contrasting color. Then, the user can click two new locations, etc. In figure 6 the running program is shown. The example network consists of the major railroad connections in the Netherlands. The snapshot shows the route found between Den Haag and Almelo, and the user has already clicked the starting point of a new query: Nijmegen. Modeling this problem is rather complicated. Both the subdivision in classes, and the definition of some of their methods, require carefull planning. Subdivision in classes This being an interactive program, we certainly need a subclass of Frame, which will also act as a MouseListener. For this, we ll write a method Net, where also method main can reside. This class solely handles user interaction. The modeling of the network proper is done in class Network. Similar to class Calc that had a member variable of type Proc (in which the state of the processor of the calculator was defined), class Net will have a member variable of type Network. Everything concerning frames, mouse actions etc. is placed in class Net; building the network from cities and roads, as well as the actual search process, is modeled in class Network. The network consists of cities and roads; therefore we define classes City and Road, which model these concepts. Result of a search is a route or path through the network. To model it, we ll define a class Path. Class Net: the GUI of the program Mouse clicks generated by the user are handled by the implementation of method mousepressed, graphical output is made by redefining paint. But what are the member variables we need? As mentioned above, we need a Network-object, storing the network at hand. Furthermore, we need objects that can display the network and the path on request:

47 46 Algorithms Figuur 6: Snapshot of the Net program

48 18.1 Case study: network search 47 a drawing of the network. This can be delegated to the Network object, that is available as a member variable, by calling a method draw of that class. a drawing of the path in a contrasting color. We ll need a Path-object, that is also able to draw itself. Worth mentioning is that method mousepressed reacts differently to the first and second click. The first click merely needs to be stored: appearanty, this is the start of the route to be found. Only after the second click, the search process can begin. So, we need a member variable that stores the start-city of the path. By inspecting whether this variable is already initialized, mousepressed can determine whether this is a first or a second click. A first design for class Net is thus as follows: class Net extends Frame { Network network; // model of the network Path path; // the path found City city1; // first city clicked Net() {... // initialisation paint(graphics){... // let network and path draw themselves mousepressed() {... // first time: keep city1, next time: find path main() {... // create a Net and setvisible it Class Network: modeling of a network A network consists of cities and roads between them. A staightforward implementation would consist of a collection of City-objects and a collection of Road-objects. However, we will store the roads as part of the city where they originate, so the roads need not explicitly be stored in the network. So, the network just consists of a collection of cities. We already identified one method in class Network: a method that is able to draw it to a given Graphics-object. Also, the network should be able to built itself from information found in a file. Finally, we need a method for the central question: find a path between two given cities. While building the network, it is convenient to have methods that add a single city, and a single road, respectively, to the network. And as the user clicks point on the screen, rather than cityobjects, we need a method that finds the city that is located at a particular point. The design of the Network is thus as follows: class Network { Collection cities; // member variable Network() {... // initialisation void makecity(...) {... void makeroad(...) {... City findcity(int,int) {... // is there a city at this point? Path findpath(city,city){... // find path between two cities void read(string) {... // build network described in file with given name void draw(graphics) {... // draw yourself Classes City and Road: parts of the network A city is characterized by a name and a location on the map. Also, we ve decided to store the outgoing roads with a city. Furthermore, it is convenient if a city can draw itself to a Graphicsobject, because then the network can delegate drawing of a city to the individual city-objects. And as a city stores the outgoing roads, we need a method to build a new road. So in class City we ll need at least the following: class City { String name; int x,y; Collection roads; city(...) {... void makeroad(...) {... void draw(graphics) {... If we want to find the cheapest path connecting two cities, we need to know the cost of using each

49 48 Algorithms Figuur 7: Two possible representations of a Path road. Also, the destination city of the road is essential knowledge. Thus, a Road is modeled by: class Road { City dest; int cost; Road(...) {... void draw(graphics) {... Class Path: a route through the network At first sight, a path may seem to be a sequence of roads, which might be stored in an array of arraylist. However, it appears to be more useful to represent a path as a list of cities it connects. Instead of an implementation from package collecion (e.g., ArrayList of LinkedList), we define an implementation of our own: (see figure 7): class Path { // Collection cities // replaced by new implementation: City here; Path int rest; cost; Path(...) {... boolean contains(city) {... void draw(graphics) {... Thus, a path is represented by the city it begins at, and another Path-object containing the rest of the path. That object stores the next city, and again a Path-object containing the remaining part of the path, etc. In the last link of the chain, we leave member variable rest uninitialized, i.e. null. Apart form a constructor and draw-method, we have a method that can check whether a given city is on the path The search algorithm Search method The actual searching of the path is tricky. The essence of the method is keeping a set of promising, though incomplete paths. We ll try to extend the set with more paths trying to reach the target. We ll continue extending the set until we find a path ending at the given destination. The set of paths can be initialized by a very short path: the path of length 0 that starts and ends at the initial city. Though this is not a particulary good path, it is certainly promising: it starts at the right location, after all. By extending it, we ll reach the target sooner or later. So, a first

50 18.2 The search algorithm 49 design of method findpath is: Path findpath(city from, City to) { paths.push(initialpath); // add a path from "from" to "from"; while (...) // while promising paths exist { path =...; // get a path from the set if (path.here==to) // does the path reach the target? return path; // found! for (...) // for all roads starting "here": paths.push(...); // add a path to the set return...; // sorry, nothing found Do not search circularly A caveat is that we should not investigate paths which re-visits the initial city. We would search circularly forever that way, without ever finding the destination. Therefore we should only add paths to the set of promising paths that are not circular. We can use method contains for checking whether a given path already contains the city that we are about to visit next. Search the best rather than the first The method designed above will stop searching as soon as it has found a path connecting the two cities. This path is not necessarily the best. To find the best path, we ll need to continue searching, hoping to find an even better path. Therefore, we combine the algorith above with the find the smallest algorithm that we used earlier to find the smallest value of an array. We get: Path findpath(city from, City to) { paths.push(initialpath); best = null; // not found anything yet while (...) { path =...; if (path.here==to) { if (...) // new solution better than best? best = path; // then it is the best! for (...) if (...) // not circular? paths.push(...); return best; // return the best ever, if it exists at all Optimization: abandon hopeless cases So, once we found a solution, we keep searching, hoping to find a better solution. But there is no point in exploring partial paths any further, if the partial path is already more expensive than the best-so-far solution. Therefore, we exclude hopeless paths from the search, which will increase the speed of the algorithm. Optimization: search most promising first Because of the optimization above, the search process is faster as soon as an initial solution is found. So it will help if the first solution is found early. A way of attaining that situation is investigating the most promising partial paths first. But what is the most promising candidate? Well, we know the coordinates of the current city as well as the target s, and if road prizing is logical, then travelling in the opposite direction is a bad strategy for minimizing costs... When travelling form Utrecht to Groningen, it is best to first try direction Amersfoort, or maybe Hilversum, but probably not Geldermalsen! This idea does not always help. When traveling from Hoorn to Leeuwarden the path doesn t include Enkhuizen, although at first sight that road is in the right direction. But is doesn t harm either to try the roads in a particular order in the previous version of the method, we search them in random order after all! (An attempt to increase the speed of an algorithm which works in most, though not all cases, but which doesn t harm either, is known as a heuristic.)

51 50 Algorithms Class Stack stacks objects Package java.util provides an additional implementation of List: class Stack. This class models a stack of objects, on top of which new elements can be added. Elements can be removed from a stack, but only at the top, so elements that are added last will be removed first ( last hired, first fired ; a bad idea to treat your personell, or your mailbox, like this). This class provides a few additional methods to those specified in List, including: boolean empty() determines whether the stack is empty void push(object x) adds an object at the top of the stack Object pop() removes the object at the top, and returns it page 54 page 55 page 56 page 51 page 52 page 53 page 53 Implementation of the program All in all, the network searching program consists of the following classes: Network, responsible for three tasks: building the network (see listing 28); the search algorithm (see listing 29); reading and drawing the network (see listing 30). NetApplet, implementing the GUI (see listing 24); City, modeling a city (see listing 25); Road, modeling a road between two adjacent cities (see listing 26); Path, modeling a path between two arbitrary cities (see listing 27). Net, an application which wraps the applet version

52 18.2 The search algorithm 51 import java.awt.*; import java.awt.event.*; import java.applet.applet; 5 public class NetApplet extends Applet implements MouseListener { Network network; Path path; City city1; 10 public void init() { this.addmouselistener(this); network = new Network(); if (ispartofapplication) 15 network.read("spoor.txt"); else network.readurl( this.getdocumentbase(), this.getparameter("network") ); public void paint(graphics g) 20 { network.draw(g); g.setcolor( Color.red ); if (path!=null) path.draw(g); g.setcolor( Color.blue ); if (city1!=null) city1.draw(g); 25 public void mousepressed (MouseEvent e) { City s = network.findcity(e.getx(), e.gety()); if (s!=null) 30 { if (city1==null) city1 = s; else { path = network.findpath(city1, s, true); city1 = null; 35 repaint(); 40 public void mouseentered (MouseEvent e) { public void mouseexited (MouseEvent e) { public void mousereleased(mouseevent e) { public void mouseclicked (MouseEvent e) { 45 boolean ispartofapplication; public NetApplet() { this(false); NetApplet(boolean app) { this.ispartofapplication = app; if (app) this.init(); Listing 24: Network/NetApplet.java

53 52 Algorithms import java.util.*; import java.awt.graphics; 5 { class City implements Comparator String name; Collection roads; int x, y; 10 public City(String s, int ax, int ay) { name = new String(s); roads = new LinkedList(); x = ax; y = ay; public void makeroad(city dest, int cost) { roads.add( new Road(dest, cost) ); public void draw(graphics g) { g.fillrect( x-5, y-5, 10, 10 ); g.drawstring(name, x+6, y ); // order two roads in *descending* order // w.r.t. the distance from their dest to the current City public int compare(object a, Object b) { return distance(((road)b).dest) - distance(((road)a).dest); 30 int distance(city a) { return distance(a, this); 35 static int distance(city a, City b) { return square(a.x-b.x) + square(a.y-b.y); 40 static int square(int x) { return x*x; Listing 25: Network/City.java

54 18.2 The search algorithm 53 import java.awt.graphics; class Road { 5 City dest; int cost; public Road(City s, int k) { dest = s; 10 cost = k; public void draw(graphics g, City s) { g.drawline( s.x, s.y, dest.x, dest.y ); 15 Listing 26: Network/Road.java import java.awt.graphics; class Path { 5 City here; Path rest; int cost; public Path( City s, Path r, int k) 10 { here = s; rest = r; cost = k; if (rest!=null) cost += rest.cost; 15 public boolean contains(city s) { if (here==s) return true; if (rest==null) return false; return rest.contains(s); 20 public void draw(graphics g) { here.draw(g); if (rest!=null) 25 { g.drawline( here.x, here.y, rest.here.x, rest.here.y ); rest.draw(g); Listing 27: Network/Path.java

55 54 Algorithms 5 import java.util.*; import java.io.*; import java.net.*; import java.awt.graphics; class Network { Collection cities; 10 public Network() { cities = new LinkedList(); public void makecity(string name, int x, int y) 15 { cities.add( new City(name, x, y) ); public void makeroad(string name1, String name2, int price) { City st1 = findcity(name1); 20 City st2 = findcity(name2); st1.makeroad(st2, price); st2.makeroad(st1, price); 25 public City findcity(string name) { for (Iterator iter=cities.iterator(); iter.hasnext(); ) { City st = (City)iter.next(); if (st.name.equals(name)) return st; 30 return null; public City findcity(int x, int y) 35 { for (Iterator iter=cities.iterator(); iter.hasnext(); ) { City st = (City)iter.next(); if ( Math.abs(x-st.x)<5 && Math.abs(y-st.y)<5 ) return st; 40 return null; Listing 28: Network/Network.java, part 1 of 3

56 18.2 The search algorithm 55 public Path findpath(city from, City to, boolean findsmart) { Stack paths = new Stack(); 45 Path best = null; paths.push( new Path(from,null,0) ); while(!paths.empty() ) 50 { Path path = (Path) paths.pop(); if (path.here==to) { if (best==null path.cost<best.cost) best = path; 55 Collection roads; if (findsmart) { // sort road w.r.t. distance to city "to" 60 roads = new TreeSet( to ); roads.addall(path.here.roads); else roads = path.here.roads; 65 for (Iterator iter=roads.iterator(); iter.hasnext(); ) { Road road = (Road) iter.next(); if (!path.contains(road.dest) && (best==null path.cost+road.cost<=best.cost) ) paths.push( new Path(road.dest, path, road.cost) ); 70 return best; Listing 29: Network/Network.java, part 2 of 3

57 56 Algorithms 75 public void read(string filename) { try { this.read(new BufferedReader(new FileReader(filename))); catch (Exception e) { 80 public void readurl(url base, String name) { try { BufferedReader br = new BufferedReader(new InputStreamReader(new URL(base, name) 85. openconnection(). getinputstream() )); this.read(br); catch (Exception e) {System.out.println(""+e); 90 private void read(bufferedreader lines) throws Exception { String line; while ( (line=lines.readline())!= null) 95 { StringTokenizer st = new StringTokenizer(line, " "); if (st.hasmoretokens()) { String command = st.nexttoken(); if (command.equals("city")) { String name = st.nexttoken(); 100 int x = Integer.valueOf(st.nextToken()).intValue(); int y = Integer.valueOf(st.nextToken()).intValue(); makecity( name, x, y ); else if (command.equals("road")) 105 { String from = st.nexttoken(); String to = st.nexttoken(); int cost = Integer.valueOf(st.nextToken()).intValue(); makeroad( from, to, cost ); 110 public void draw(graphics g) 115 { for (Iterator iter=cities.iterator(); iter.hasnext(); ) { City city = (City)iter.next(); city.draw(g); for (Iterator iter2=city.roads.iterator(); iter2.hasnext(); ) { Road w = (Road) iter2.next(); 120 w.draw(g, city); Listing 30: Network/Network.java, part 3 of 3

58 18.3 Case study: automatic language recognition Case study: automatic language recognition Case description This case study is named language as it can recognize the language of a given text. To be able to write such a program, we need to answer the question how language recognition is done. As an introduction, have a look at a verse from a poem named Jabberwocky by Lewis Carroll, and its translation in three languages: Twas brillig, and the slithy toves Did gyre and gimble in the wabe: All mimsy were the borogoves, And the mome raths outgrabe. Es brillig war. Die schlichten Toven Wirrten und wimmelten in Waben; Und aller-mümsigen Burggroven Die mohmen Räth ausgraben. Il brigue: les tôves libricilleux Se gyrent en vrillant dans la guave. Enmîmés sont les goubebosqueux Et le mômerade horsgrave. t Wier bradig en de slijp le torfs driltolden op de wijde weep. Misbrozig stonden borogorfs t verdwoolde grasvark schreep. The words in all translations are just as nonsensical as in the original. Yet it is immediately clear which language they are meant to be in. Appearantly, we can recognize that without understanding the text, but by merely investigating its formal aspects. An example of a formal aspect is the frequnecy of the various characters. Even without knowing Albanese of Finnish, you can recognize an Albanian text from the typical use of many q s and ë s, and a Finnish text from the many u s and other vowels. Our program will operate in a similar fashion: based on the character frequencies, the decision is made in which language the text (probably) is. Of course the program doesn t really know the language, in the same way that we know English or French. But what s the difference, as long as it can flawlessly recognize the languages? One might even argue that this is what knowing a language is all about, so that our program can be said to know the languages it recognizes one might even be tempted to attribute intelligence to it. Artificial intelligence, that is. Modeling One approach could be to built in the knowledge of various languages into the prgogram. The program would be rather lengthy, containing many if-statements distinguishing the properties of the languages. Furthermore, we d indentify the languages beforehand, and for each of these languages do a frequency analysis. But because the program should be able to do a frequency analysis for the unknown text anyway, we can use the same methods for doing a frequency analysis for the various languages. For that, we need a representative example text for each language. Based on that, the program can learn about the typical character frequencies in each language. In the program, therefore, no knowledge about particular languages is built-in; instead,the program learns from analyszing example texts. An advantage of this approach is that the user may decide which languages should be recognizable, provided an example text in those languages is available. The program needs tables that for each character of the alphabet gives its frequency in each language. We restrict ourselves to alphabetical characters we don t take punctuation marks and digits into consideration. Capitals and lower case are treated the same; it would distract us from the main characteristic: character frequency. For simplicity, we only use the western 26-character alphabet, but the program could easily be extended to other alphabets. Comparing grequency tables We need a criterion by which to decide whether frequency tables are closer to each other than to other tables. For this, we need a notion of difference of two tables: the bigger the difference, the less the resemblance. A table resembles most to the table to which it has smallest difference. There are various possibilities for a notion of difference. We have to take some arbitrary decisions. There is some room for later improvements by reconsidering or refining these decisions. The frequency of all characters is important. Therefore, we take the difference in frequency of all 26 characters, and totalize it. We might weigh some characters more heavyly in the

59 58 Algorithms Figuur 8: Snapshot of the language recognition program average, but as it is not clear which characters are that important, we just let all characters weigh the same. A longer text of course has higher character frequencies. As the length of the text should not have impact on the result, we determine the relative freqencies rather than the absolute ones. Both a deficit and an excess of characters should add to the total: we can t compensate a shortage of a s by a remainder of b s. Therefore we ll use the absolute value of the (relative) differences. Another possibility would be the square of the differences: that would emphasize large differences. Again, here is some experimentation possible. Summarizing, the difference between two tables is taken to be the sum of absolute values of differences of relative character frequencies, which is divided by 26 to end up with a number between 0 and 1. User interface The user interface provides a text area to type the text to be analyzed. Also the user should be able to provide some example texts, in the form of a name and an url on the www. Plenty of foreign sites are available from which we can grab example texts. Furthermore, the GUI presents a button, pressing which the user can start the recognition process. Finally, there is a Label showing the result. The five locations a BorderLayout supports precisely fit these five components. The languagenames and -urls are added to a Panel, that has a GridLayout. The complete interface is shown in figure 8. Class structure Clearly, a frequency table is an important object in this program. We happen to already have defined a class Checker in chapter 11, which is able to count individual character frequencies. That class is quite useful here. However, the class didn t provide a method to determine relative frequencies, neither a method to read input from the WWW. Therefore, we write a subclass RelChecker of Checker, in which the necessary additional methods are defined. In another class, named Language, we build the user interface. In its method actionperformed the comparison of the tables is controled.

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline

GUI Program Organization. Sequential vs. Event-driven Programming. Sequential Programming. Outline Sequential vs. Event-driven Programming Reacting to the user GUI Program Organization Let s digress briefly to examine the organization of our GUI programs We ll do this in stages, by examining three example

More information

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User

Control Flow: Overview CSE3461. An Example of Sequential Control. Control Flow: Revisited. Control Flow Paradigms: Reacting to the User CSE3461 Control Flow Paradigms: Reacting to the User Control Flow: Overview Definition of control flow: The sequence of execution of instructions in a program. Control flow is determined at run time by

More information

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing.

Example Programs. COSC 3461 User Interfaces. GUI Program Organization. Outline. DemoHelloWorld.java DemoHelloWorld2.java DemoSwing. COSC User Interfaces Module 3 Sequential vs. Event-driven Programming Example Programs DemoLargestConsole.java DemoLargestGUI.java Demo programs will be available on the course web page. GUI Program Organization

More information

Lecture 5: Java Graphics

Lecture 5: Java Graphics Lecture 5: Java Graphics CS 62 Spring 2019 William Devanny & Alexandra Papoutsaki 1 New Unit Overview Graphical User Interfaces (GUI) Components, e.g., JButton, JTextField, JSlider, JChooser, Containers,

More information

G51PRG: Introduction to Programming Second semester Applets and graphics

G51PRG: Introduction to Programming Second semester Applets and graphics G51PRG: Introduction to Programming Second semester Applets and graphics Natasha Alechina School of Computer Science & IT nza@cs.nott.ac.uk Previous two lectures AWT and Swing Creating components and putting

More information

PIC 20A GUI with swing

PIC 20A GUI with swing PIC 20A GUI with swing Ernest Ryu UCLA Mathematics Last edited: November 22, 2017 Hello swing Let s create a JFrame. import javax. swing.*; public class Test { public static void main ( String [] args

More information

The AWT Event Model 9

The AWT Event Model 9 The AWT Event Model 9 Course Map This module covers the event-based GUI user input mechanism. Getting Started The Java Programming Language Basics Identifiers, Keywords, and Types Expressions and Flow

More information

Graphic User Interfaces. - GUI concepts - Swing - AWT

Graphic User Interfaces. - GUI concepts - Swing - AWT Graphic User Interfaces - GUI concepts - Swing - AWT 1 What is GUI Graphic User Interfaces are used in programs to communicate more efficiently with computer users MacOS MS Windows X Windows etc 2 Considerations

More information

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson)

Graphics programming. COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Graphics programming COM6516 Object Oriented Programming and Design Adam Funk (originally Kirill Bogdanov & Mark Stevenson) Overview Aims To provide an overview of Swing and the AWT To show how to build

More information

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics

Outline. Topic 9: Swing. GUIs Up to now: line-by-line programs: computer displays text user types text AWT. A. Basics Topic 9: Swing Outline Swing = Java's GUI library Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 7: Expand moving shapes from Assignment 4 into game. "Programming

More information

Lecture 3: Java Graphics & Events

Lecture 3: Java Graphics & Events Lecture 3: Java Graphics & Events CS 62 Fall 2017 Kim Bruce & Alexandra Papoutsaki Text Input Scanner class Constructor: myscanner = new Scanner(System.in); can use file instead of System.in new Scanner(new

More information

Unit 7: Event driven programming

Unit 7: Event driven programming Faculty of Computer Science Programming Language 2 Object oriented design using JAVA Dr. Ayman Ezzat Email: ayman@fcih.net Web: www.fcih.net/ayman Unit 7: Event driven programming 1 1. Introduction 2.

More information

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011

GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI DYNAMICS Lecture July 26 CS2110 Summer 2011 GUI Statics and GUI Dynamics 2 Statics: what s drawn on the screen Components buttons, labels, lists, sliders, menus,... Containers: components that contain

More information

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events

11/7/12. Discussion of Roulette Assignment. Objectives. Compiler s Names of Classes. GUI Review. Window Events Objectives Event Handling Animation Discussion of Roulette Assignment How easy/difficult to refactor for extensibility? Was it easier to add to your refactored code? Ø What would your refactored classes

More information

Graphics. Lecture 18 COP 3252 Summer June 6, 2017

Graphics. Lecture 18 COP 3252 Summer June 6, 2017 Graphics Lecture 18 COP 3252 Summer 2017 June 6, 2017 Graphics classes In the original version of Java, graphics components were in the AWT library (Abstract Windows Toolkit) Was okay for developing simple

More information

Chapter 1 GUI Applications

Chapter 1 GUI Applications Chapter 1 GUI Applications 1. GUI Applications So far we've seen GUI programs only in the context of Applets. But we can have GUI applications too. A GUI application will not have any of the security limitations

More information

Packages: Putting Classes Together

Packages: Putting Classes Together Packages: Putting Classes Together 1 Introduction 2 The main feature of OOP is its ability to support the reuse of code: Extending the classes (via inheritance) Extending interfaces The features in basic

More information

Programming graphics

Programming graphics Programming graphics Need a window javax.swing.jframe Several essential steps to use (necessary plumbing ): Set the size width and height in pixels Set a title (optional), and a close operation Make it

More information

CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM

CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM CS 315 Software Design Homework 1 First Sip of Java Due: Sept. 10, 11:30 PM Objectives The objectives of this assignment are: to get your first experience with Java to become familiar with Eclipse Java

More information

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4.

Virtualians.ning.pk. 2 - Java program code is compiled into form called 1. Machine code 2. native Code 3. Byte Code (From Lectuer # 2) 4. 1 - What if the main method is declared as private? 1. The program does not compile 2. The program compiles but does not run 3. The program compiles and runs properly ( From Lectuer # 2) 4. The program

More information

Assignment 2. Application Development

Assignment 2. Application Development Application Development Assignment 2 Content Application Development Day 2 Lecture The lecture covers the key language elements of the Java programming language. You are introduced to numerical data and

More information

Using the API: Introductory Graphics Java Programming 1 Lesson 8

Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using the API: Introductory Graphics Java Programming 1 Lesson 8 Using Java Provided Classes In this lesson we'll focus on using the Graphics class and its capabilities. This will serve two purposes: first

More information

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing

Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Java Graphical User Interfaces AWT (Abstract Window Toolkit) & Swing Rui Moreira Some useful links: http://java.sun.com/docs/books/tutorial/uiswing/toc.html http://www.unix.org.ua/orelly/java-ent/jfc/

More information

Java Programming Lecture 6

Java Programming Lecture 6 Java Programming Lecture 6 Alice E. Fischer Feb 15, 2013 Java Programming - L6... 1/32 Dialog Boxes Class Derivation The First Swing Programs: Snow and Moving The Second Swing Program: Smile Swing Components

More information

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI

(listener)... MouseListener, ActionLister. (adapter)... MouseAdapter, ActionAdapter. java.awt AWT Abstract Window Toolkit GUI 51 6!! GUI(Graphical User Interface) java.awt javax.swing (component) GUI... (container) (listener)... MouseListener, ActionLister (adapter)... MouseAdapter, ActionAdapter 6.1 GUI(Graphics User Interface

More information

BASICS OF GRAPHICAL APPS

BASICS OF GRAPHICAL APPS CSC 2014 Java Bootcamp Lecture 7 GUI Design BASICS OF GRAPHICAL APPS 2 Graphical Applications So far we ve focused on command-line applications, which interact with the user using simple text prompts In

More information

Systems Programming Graphical User Interfaces

Systems Programming Graphical User Interfaces Systems Programming Graphical User Interfaces Julio Villena Román (LECTURER) CONTENTS ARE MOSTLY BASED ON THE WORK BY: José Jesús García Rueda Systems Programming GUIs based on Java

More information

Introduction to the JAVA UI classes Advanced HCI IAT351

Introduction to the JAVA UI classes Advanced HCI IAT351 Introduction to the JAVA UI classes Advanced HCI IAT351 Week 3 Lecture 1 17.09.2012 Lyn Bartram lyn@sfu.ca About JFC and Swing JFC Java TM Foundation Classes Encompass a group of features for constructing

More information

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1,

Java - Applets. C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, Java - Applets C&G criteria: 1.2.2, 1.2.3, 1.2.4, 1.3.4, 1.2.4, 1.3.4, 1.3.5, 2.2.5, 2.4.5, 5.1.2, 5.2.1, 5.3.2. Java is not confined to a DOS environment. It can run with buttons and boxes in a Windows

More information

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming

CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming CPS122 Lecture: Graphical User Interfaces and Event-Driven Programming Objectives: Last revised 1/15/10 1. To introduce the notion of a component and some basic Swing components (JLabel, JTextField, JTextArea,

More information

CPS221 Lecture: Threads

CPS221 Lecture: Threads Objectives CPS221 Lecture: Threads 1. To introduce threads in the context of processes 2. To introduce UML Activity Diagrams last revised 9/5/12 Materials: 1. Diagram showing state of memory for a process

More information

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM

CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM CS 201 Advanced Object-Oriented Programming Lab 10 - Recursion Due: April 21/22, 11:30 PM Introduction to the Assignment In this assignment, you will get practice with recursion. There are three parts

More information

Frameworks. CS151 Chris Pollett Oct. 26, 2005.

Frameworks. CS151 Chris Pollett Oct. 26, 2005. Frameworks CS151 Chris Pollett Oct. 26, 2005. Outline Collections Framework GUI Frameworks - AWT and Swing The Java Collection Framework Last day, we began discussing the Java collection Framework. We

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Swing from A to Z Some Simple Components. Preface

Swing from A to Z Some Simple Components. Preface By Richard G. Baldwin baldwin.richard@iname.com Java Programming, Lecture Notes # 1005 July 31, 2000 Swing from A to Z Some Simple Components Preface Introduction Sample Program Interesting Code Fragments

More information

Window Interfaces Using Swing Objects

Window Interfaces Using Swing Objects Chapter 12 Window Interfaces Using Swing Objects Event-Driven Programming and GUIs Swing Basics and a Simple Demo Program Layout Managers Buttons and Action Listeners Container Classes Text I/O for GUIs

More information

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more

Topic 9: Swing. Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Assignment 5: Will be an open-ended Swing project. "Programming Contest"

More information

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun!

Topic 9: Swing. Why are we studying Swing? GUIs Up to now: line-by-line programs: computer displays text user types text. Outline. 1. Useful & fun! Swing = Java's GUI library Topic 9: Swing Swing is a BIG library Goal: cover basics give you concepts & tools for learning more Why are we studying Swing? 1. Useful & fun! 2. Good application of OOP techniques

More information

AP CS Unit 12: Drawing and Mouse Events

AP CS Unit 12: Drawing and Mouse Events AP CS Unit 12: Drawing and Mouse Events A JPanel object can be used as a container for other objects. It can also be used as an object that we can draw on. The first example demonstrates how to do that.

More information

CSE 331 Software Design & Implementation

CSE 331 Software Design & Implementation CSE 331 Software Design & Implementation Hal Perkins Spring 2017 GUI Event-Driven Programming 1 The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous

More information

Class 16: The Swing Event Model

Class 16: The Swing Event Model Introduction to Computation and Problem Solving Class 16: The Swing Event Model Prof. Steven R. Lerman and Dr. V. Judson Harward 1 The Java Event Model Up until now, we have focused on GUI's to present

More information

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming

Framework. Set of cooperating classes/interfaces. Example: Swing package is framework for problem domain of GUI programming Frameworks 1 Framework Set of cooperating classes/interfaces Structure essential mechanisms of a problem domain Programmer can extend framework classes, creating new functionality Example: Swing package

More information

Event Driven Programming

Event Driven Programming Event Driven Programming 1. Objectives... 2 2. Definitions... 2 3. Event-Driven Style of Programming... 2 4. Event Polling Model... 3 5. Java's Event Delegation Model... 5 6. How to Implement an Event

More information

Animations involving numbers

Animations involving numbers 136 Chapter 8 Animations involving numbers 8.1 Model and view The examples of Chapter 6 all compute the next picture in the animation from the previous picture. This turns out to be a rather restrictive

More information

Advanced Java Programming (17625) Event Handling. 20 Marks

Advanced Java Programming (17625) Event Handling. 20 Marks Advanced Java Programming (17625) Event Handling 20 Marks Specific Objectives To write event driven programs using the delegation event model. To write programs using adapter classes & the inner classes.

More information

Lecture 19 GUI Events

Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events The plan User events and callbacks Event objects Event listeners Registering listeners to handle events Anonymous inner classes Proper interaction

More information

Which of the following syntax used to attach an input stream to console?

Which of the following syntax used to attach an input stream to console? Which of the following syntax used to attach an input stream to console? FileReader fr = new FileReader( input.txt ); FileReader fr = new FileReader(FileDescriptor.in); FileReader fr = new FileReader(FileDescriptor);

More information

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1

Block I Unit 2. Basic Constructs in Java. AOU Beirut Computer Science M301 Block I, unit 2 1 Block I Unit 2 Basic Constructs in Java M301 Block I, unit 2 1 Developing a Simple Java Program Objectives: Create a simple object using a constructor. Create and display a window frame. Paint a message

More information

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7

PROGRAMMING DESIGN USING JAVA (ITT 303) Unit 7 PROGRAMMING DESIGN USING JAVA (ITT 303) Graphical User Interface Unit 7 Learning Objectives At the end of this unit students should be able to: Build graphical user interfaces Create and manipulate buttons,

More information

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068

Welcome to CIS 068! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) CIS 068 Welcome to! 1. GUIs: JAVA Swing 2. (Streams and Files we ll not cover this in this semester, just a review) Overview JAVA and GUIs: SWING Container, Components, Layouts Using SWING Streams and Files Text

More information

UI Software Organization

UI Software Organization UI Software Organization The user interface From previous class: Generally want to think of the UI as only one component of the system Deals with the user Separate from the functional core (AKA, the app

More information

Come & Join Us at VUSTUDENTS.net

Come & Join Us at VUSTUDENTS.net Come & Join Us at VUSTUDENTS.net For Assignment Solution, GDB, Online Quizzes, Helping Study material, Past Solved Papers, Solved MCQs, Current Papers, E-Books & more. Go to http://www.vustudents.net and

More information

Prototyping a Swing Interface with the Netbeans IDE GUI Editor

Prototyping a Swing Interface with the Netbeans IDE GUI Editor Prototyping a Swing Interface with the Netbeans IDE GUI Editor Netbeans provides an environment for creating Java applications including a module for GUI design. Here we assume that we have some existing

More information

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 9: Writing Java Applets. Introduction INTRODUCTION TO COMPUTER PROGRAMMING Richard Pierse Class 9: Writing Java Applets Introduction Applets are Java programs that execute within HTML pages. There are three stages to creating a working Java

More information

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread

G51PGP Programming Paradigms. Lecture 008 Inner classes, anonymous classes, Swing worker thread G51PGP Programming Paradigms Lecture 008 Inner classes, anonymous classes, Swing worker thread 1 Reminder subtype polymorphism public class TestAnimals public static void main(string[] args) Animal[] animals

More information

Java - Applets. public class Buttons extends Applet implements ActionListener

Java - Applets. public class Buttons extends Applet implements ActionListener Java - Applets Java code here will not use swing but will support the 1.1 event model. Legacy code from the 1.0 event model will not be used. This code sets up a button to be pushed: import java.applet.*;

More information

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures

11-1. Collections. CSE 143 Java. Java 2 Collection Interfaces. Goals for Next Several Lectures Collections CSE 143 Java Collections Most programs need to store and access collections of data Collections are worth studying because... They are widely useful in programming They provide examples of

More information

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) )

COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) ) COMP-202 Unit 10: Basics of GUI Programming (Non examinable) (Caveat: Dan is not an expert in GUI programming, so don't take this for gospel :) ) Course Evaluations Please do these. -Fast to do -Used to

More information

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur Lecture - 43 Dynamic Binding (Polymorphism): Part III Welcome to Module

More information

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing

CSEN401 Computer Programming Lab. Topics: Graphical User Interface Window Interfaces using Swing CSEN401 Computer Programming Lab Topics: Graphical User Interface Window Interfaces using Swing Prof. Dr. Slim Abdennadher 22.3.2015 c S. Abdennadher 1 Swing c S. Abdennadher 2 AWT versus Swing Two basic

More information

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005.

I/O Framework and Case Study. CS151 Chris Pollett Nov. 2, 2005. I/O Framework and Case Study CS151 Chris Pollett Nov. 2, 2005. Outline Character Streams Random Access Files Design case study Planning Iterations Character Streams Java internally represents strings as

More information

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2,

Java Mouse Actions. C&G criteria: 5.2.1, 5.4.1, 5.4.2, Java Mouse Actions C&G criteria: 5.2.1, 5.4.1, 5.4.2, 5.6.2. The events so far have depended on creating Objects and detecting when they receive the event. The position of the mouse on the screen can also

More information

Java Collections Framework

Java Collections Framework Java Collections Framework Introduction In this article from my free Java 8 course, you will be given a high-level introduction of the Java Collections Framework (JCF). The term Collection has several

More information

Computer Science 210: Data Structures. Intro to Java Graphics

Computer Science 210: Data Structures. Intro to Java Graphics Computer Science 210: Data Structures Intro to Java Graphics Summary Today GUIs in Java using Swing in-class: a Scribbler program READING: browse Java online Docs, Swing tutorials GUIs in Java Java comes

More information

Graphical User Interface (GUI)

Graphical User Interface (GUI) Graphical User Interface (GUI) An example of Inheritance and Sub-Typing 1 Java GUI Portability Problem Java loves the idea that your code produces the same results on any machine The underlying hardware

More information

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development

CSCI 053. Week 5 Java is like Alice not based on Joel Adams you may want to take notes. Rhys Price Jones. Introduction to Software Development CSCI 053 Introduction to Software Development Rhys Price Jones Week 5 Java is like Alice not based on Joel Adams you may want to take notes Objectives Learn to use the Eclipse IDE Integrated Development

More information

Programming Languages and Techniques (CIS120e)

Programming Languages and Techniques (CIS120e) Programming Languages and Techniques (CIS120e) Lecture 29 Nov. 19, 2010 Swing I Event- driven programming Passive: ApplicaHon waits for an event to happen in the environment When an event occurs, the applicahon

More information

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday!

Lab & Assignment 1. Lecture 3: ArrayList & Standard Java Graphics. Random Number Generator. Read Lab & Assignment Before Lab Wednesday! Lab & Assignment 1 Lecture 3: ArrayList & Standard Java Graphics CS 62 Fall 2015 Kim Bruce & Michael Bannister Strip with 12 squares & 5 silver dollars placed randomly on the board. Move silver dollars

More information

CSE 331 Software Design and Implementation. Lecture 19 GUI Events

CSE 331 Software Design and Implementation. Lecture 19 GUI Events CSE 331 Software Design and Implementation Lecture 19 GUI Events Leah Perlmutter / Summer 2018 Announcements Announcements Quiz 7 due Thursday 8/9 Homework 8 due Thursday 8/9 HW8 has a regression testing

More information

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components

Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how to paint graphics on GUI components CS112-Section2 Hakan Guldas Burcin Ozcan Meltem Kaya Muge Celiktas Notes of 6-8 May Graphics Previously, we have seen GUI components, their relationships, containers, layout managers. Now we will see how

More information

In this lesson, you ll learn how to:

In this lesson, you ll learn how to: LESSON 5: ADVANCED DRAWING TECHNIQUES OBJECTIVES In this lesson, you ll learn how to: apply gradient fills modify graphics by smoothing, straightening, and optimizing understand the difference between

More information

Eclipsing Your IDE. Figure 1 The first Eclipse screen.

Eclipsing Your IDE. Figure 1 The first Eclipse screen. Eclipsing Your IDE James W. Cooper I have been hearing about the Eclipse project for some months, and decided I had to take some time to play around with it. Eclipse is a development project (www.eclipse.org)

More information

GUI in Java TalentHome Solutions

GUI in Java TalentHome Solutions GUI in Java TalentHome Solutions AWT Stands for Abstract Window Toolkit API to develop GUI in java Has some predefined components Platform Dependent Heavy weight To use AWT, import java.awt.* Calculator

More information

CHAPTER 2. Java Overview

CHAPTER 2. Java Overview Networks and Internet Programming (0907522) CHAPTER 2 Java Overview Instructor: Dr. Khalid A. Darabkh Objectives The objectives of this chapter are: To discuss the classes present in the java.awt package

More information

CS 116x Winter 2015 Craig S. Kaplan. Module 03 Graphical User Interfaces. Topics

CS 116x Winter 2015 Craig S. Kaplan. Module 03 Graphical User Interfaces. Topics CS 116x Winter 2015 Craig S. Kaplan Module 03 Graphical User Interfaces Topics The model-view-controller paradigm Direct manipulation User interface toolkits Building interfaces with ControlP5 Readings

More information

Swing from A to Z Using Focus in Swing, Part 2. Preface

Swing from A to Z Using Focus in Swing, Part 2. Preface Swing from A to Z Using Focus in Swing, Part 2 By Richard G. Baldwin Java Programming, Lecture Notes # 1042 November 27, 2000 Preface Introduction Sample Program Interesting Code Fragments Summary What's

More information

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright

GUI Basics. Object Orientated Programming in Java. Benjamin Kenwright GUI Basics Object Orientated Programming in Java Benjamin Kenwright Outline Essential Graphical User Interface (GUI) Concepts Libraries, Implementation, Mechanics,.. Abstract Windowing Toolkit (AWT) Java

More information

Using Flash Animation Basics

Using Flash Animation Basics Using Flash Contents Using Flash... 1 Animation Basics... 1 Exercise 1. Creating a Symbol... 2 Exercise 2. Working with Layers... 4 Exercise 3. Using the Timeline... 6 Exercise 4. Previewing an animation...

More information

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage)

+! Today. Lecture 3: ArrayList & Standard Java Graphics 1/26/14! n Reading. n Objectives. n Reminders. n Standard Java Graphics (on course webpage) +! Lecture 3: ArrayList & Standard Java Graphics +! Today n Reading n Standard Java Graphics (on course webpage) n Objectives n Review for this week s lab and homework assignment n Miscellanea (Random,

More information

Java. GUI building with the AWT

Java. GUI building with the AWT Java GUI building with the AWT AWT (Abstract Window Toolkit) Present in all Java implementations Described in most Java textbooks Adequate for many applications Uses the controls defined by your OS therefore

More information

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT

CSE 143. Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT CSE 143 Event-driven Programming and Graphical User Interfaces (GUIs) with Swing/AWT slides created by Marty Stepp based on materials by M. Ernst, S. Reges, D. Notkin, R. Mercer, Wikipedia http://www.cs.washington.edu/331/

More information

CS11 Java. Fall Lecture 3

CS11 Java. Fall Lecture 3 CS11 Java Fall 2014-2015 Lecture 3 Today s Topics! Class inheritance! Abstract classes! Polymorphism! Introduction to Swing API and event-handling! Nested and inner classes Class Inheritance! A third of

More information

Summary Chapter 25 GUI Components: Part 2

Summary Chapter 25 GUI Components: Part 2 1040 Chapter 25 GUI Components: Part 2 ponent on the line. TheJTextField is added to the content pane with a call to our utility method addcomponent (declared at lines 79 83). MethodaddComponent takes

More information

SD Module-1 Advanced JAVA

SD Module-1 Advanced JAVA Assignment No. 4 SD Module-1 Advanced JAVA R C (4) V T Total (10) Dated Sign Title: Transform the above system from command line system to GUI based application Problem Definition: Write a Java program

More information

CS Exam 1 Review Suggestions

CS Exam 1 Review Suggestions CS 235 - Fall 2015 - Exam 1 Review Suggestions p. 1 last modified: 2015-09-30 CS 235 - Exam 1 Review Suggestions You are responsible for material covered in class sessions, lab exercises, and homeworks;

More information

CONTAİNERS COLLECTİONS

CONTAİNERS COLLECTİONS CONTAİNERS Some programs create too many objects and deal with them. In such a program, it is not feasible to declare a separate variable to hold reference to each of these objects. The proper way of keeping

More information

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons

CompSci 125 Lecture 17. GUI: Graphics, Check Boxes, Radio Buttons CompSci 125 Lecture 17 GUI: Graphics, Check Boxes, Radio Buttons Announcements GUI Review Review: Inheritance Subclass is a Parent class Includes parent s features May Extend May Modify extends! Parent

More information

Java: Graphical User Interfaces (GUI)

Java: Graphical User Interfaces (GUI) Chair of Software Engineering Carlo A. Furia, Marco Piccioni, and Bertrand Meyer Java: Graphical User Interfaces (GUI) With material from Christoph Angerer The essence of the Java Graphics API Application

More information

Educational Fusion. Implementing a Production Quality User Interface With JFC

Educational Fusion. Implementing a Production Quality User Interface With JFC Educational Fusion Implementing a Production Quality User Interface With JFC Kevin Kennedy Prof. Seth Teller 6.199 May 1999 Abstract Educational Fusion is a online algorithmic teaching program implemented

More information

SD Module-1 Advanced JAVA. Assignment No. 4

SD Module-1 Advanced JAVA. Assignment No. 4 SD Module-1 Advanced JAVA Assignment No. 4 Title :- Transform the above system from command line system to GUI based application Problem Definition: Write a Java program with the help of GUI based Application

More information

More Swing. CS180 Recitation 12/(04,05)/08

More Swing. CS180 Recitation 12/(04,05)/08 More Swing CS180 Recitation 12/(04,05)/08 Announcements No lecture/labs next week Recitations and evening consulting hours will be held as usual. Debbie's study group on tuesday and office hours on thursday

More information

CS11 Java. Fall Lecture 4

CS11 Java. Fall Lecture 4 CS11 Java Fall 2006-2007 Lecture 4 Today s Topics Interfaces The Swing API Event Handlers Inner Classes Arrays Java Interfaces Classes can only have one parent class No multiple inheritance in Java! By

More information

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology: Inheritance 1 Inheritance One class inherits from another if it describes a specialized subset of objects Terminology: the class that inherits is called a child class or subclass the class that is inherited

More information

1 Getting started with Processing

1 Getting started with Processing cisc3665, fall 2011, lab I.1 / prof sklar. 1 Getting started with Processing Processing is a sketch programming tool designed for use by non-technical people (e.g., artists, designers, musicians). For

More information

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved.

Java How to Program, 9/e. Copyright by Pearson Education, Inc. All Rights Reserved. Java How to Program, 9/e Copyright 1992-2012 by Pearson Education, Inc. All Rights Reserved. Overview capabilities for drawing two-dimensional shapes, controlling colors and controlling fonts. One of

More information

Starting Out with Java: From Control Structures Through Objects Sixth Edition

Starting Out with Java: From Control Structures Through Objects Sixth Edition Starting Out with Java: From Control Structures Through Objects Sixth Edition Chapter 12 A First Look at GUI Applications Chapter Topics 12.1 Introduction 12.2 Creating Windows 12.3 Equipping GUI Classes

More information

Sample Examination Paper Programming and Software Development

Sample Examination Paper Programming and Software Development THE UNIVERSITY OF MELBOURNE DEPARTMENT OF COMPUTER SCIENCE AND SOFTWARE ENGINEERING Sample Examination Paper 2008 433-520 Programming and Software Development Exam Duration: 2 hours Total marks for this

More information

Sri Vidya College of Engineering & Technology

Sri Vidya College of Engineering & Technology UNIT-V TWO MARKS QUESTION & ANSWER 1. What is the difference between the Font and FontMetrics class? Font class is used to set or retrieve the screen fonts.the Font class maps the characters of the language

More information

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class.

All the Swing components start with J. The hierarchy diagram is shown below. JComponent is the base class. Q1. If you add a component to the CENTER of a border layout, which directions will the component stretch? A1. The component will stretch both horizontally and vertically. It will occupy the whole space

More information

Programmierpraktikum

Programmierpraktikum Programmierpraktikum Claudius Gros, SS2012 Institut für theoretische Physik Goethe-University Frankfurt a.m. 1 of 18 17/01/13 11:46 Java Applets 2 of 18 17/01/13 11:46 Java applets embedding Java applications

More information