MASARYKOVA UNIVERZITA FAKULTA INFORMATIKY

Visualization and GUI for CoUniverse

BACHELOR THESIS

Martin Tlachač

Brno, Spring 2008 Declaration

Hereby I declare, that this paper is my original authorial work, which I have worked out by my own. All sources, references and literature used or excerpted during elaboration of this work are properly cited and listed in complete reference to the due source.

Advisor: RNDr. Petr Holub, Ph.D.

11 Acknowledgement

I am very grateful to my advisor, RNDr. Petr Holub, Ph.D., also to RNDr. Miloš Liška for his occasional help and the whole Java team at the Masaryk University.

m Abstract

Goal of this thesis is implementation of graphical user interface (GUI) for component-based self-organizing collaborative framework CoUniverse. The GUI provides visual means for users to configure nodes within the CoUniverse network as well as visualization of the Co- Universe network for monitoring purposes. The GUI is implemented in Java as the whole CoUniverse uses this language. Toolkit is used to build the graphical interface.

IV Keywords

CoUniverse, Java, Graphical User Interface (GUI), Swing Toolkit Contents

1 Introduction 3 1.1 Thesis Structure 3 2 Tools 5 2.1 CVS 5 2.2 Swing Toolkit 5 2.3 IntelliJIdea 5 2.4 Netbeans 6 2.5 JXTA 6 2.6 SwingX-WS 6 2.7 OpenStreetMap project 6 3 CoUniverse 7 3.1 System architecture 7 3.2 Network organization 7 3.3 CoUniverse components 7 3.3.1 Communication nodes 7 3.3.2 Application group controllers 8 3.3.3 GUI Controller 8 3.4 Monitoring 8 3.5 Visualization 8 4 Design of CoUniverse GUI 9 4.1 GUI designers 9 4.2 Layout managers 10 4.3 Components 10 4.3.1 How painting works 10 4.3.2 Visual states of Swing components 11 4.3.3 My image button 12 4.3.4 My text button 13 4.4 Swing Worker 21 5 GUI for CoUniverse Configuration 23 5.1 Configuration 23 5.2 Start of GUI 25 5.3 Refactoring 25 5.4 Top-level container 25 5.5 Bottom panel 25

1 5.6 Titlepanel 25 5.7 Progress Visualization 25 5.8 My components 26 6 Visualization of CoUniverse Network 27 6.1 Design 27 6.2 JXMapViewer class 27 6.3 GUI Controller 29 6.4 Layout on map 30 6.5 Visualization components 31 6.5.1 Top-level container 31 6.5.2 Map browser 31 6.5.3 GoogleTileFactory class 31 6.5.4 NasaTileFactory class 32 6.5.5 OpenStreetsTileFactory class 32 6.5.6 Node information 32 6.5.7 Bottom panel 32 7 Conclusions 33 Bibliography 33 A CD 35

2 Chapter 1

Introduction

Nowadays, the requirements laid on GUI (Graphical User Interface) such as fast response time, a nice-looking design, an intuitive control, intelligent hints, an analysis of input, re­ strictions on the set of possible user actions based on the current state of the application etc.,—all sometimes referred to as user-friendliness—belong to commonly-expected stan­ dards. In many cases, the GUI is what ultimately sells the application. Even if a logic of ap­ plication has not a tiniest mistake, an unpleasant GUI can significantly degrade the whole application. GUI implementing all the requirements listed above can be very processor- time consuming especially when not using native host operating system's GUI controls as Java GUI framework called Swing does. On the other hand taking into consideration today's modern commonly-available hardware there is no need to worry about sufficient processing power. Therefore modern GUIs are developed to be breath-taking extent re­ gardless of their processor-time consumption. This thesis focuses on implementation of graphical user interface (GUI) for self- organizing collaborative framework CoUniverse. CoUniverse [1] is a framework for build­ ing advanced collaborative environments that can autonomously react to events happen­ ing in underlying networks even employing most advanced media transmission appli­ cations with extreme bandwidth requirements. The basic components of CoUniverse are nodes the network is comprised of. The CoUniverse schedules media streams onto links interconnecting applications while encapsulating and controlling individual media appli­ cations. GUI for the CoUniverse should allow users to configure the CoUniverse network, namely network nodes, and to visualize the behaviour of the network.

1.1 Thesis Structure

This thesis is divided into five main chapters. Chapter 2 summarizes tools, frameworks, IDEs (Integrated Development Environments) and technologies which were or could be utilized for implementing GUIs in Java and brief description to each of them. Preferably, GUI perspective on the technologies is given in description. Basic concepts and architecture of CoUniverse framework are described in Chapter 3. The following chapters 4 through 6 describe my own work on CoUniverse GUI. Chap­ ter 4 takes a look at design and implementation elements of CoUniverse GUI. It also sum­ marizes some parts of GUI development process I found worth describing, that are either

3 1. INTRODUCTION complicated or insufficiently documented in publicly accessible documents on Internet. Chapter 5 describes first part of the CoUniverse GUI I've implemented, that allows users configuring nodes within the CoUniverse network. Subsequent Chapter 6 is about visu­ alization part of the CoUniverse GUI of CoUniverse network and its states. When I im­ plemented visualization of CoUniverse, deep comprehension of CoUniverse architecture system down to actual source code was needed. Thus in introduction of this chapter, rele­ vant CoUniverse components are explained.

4 Chapter 2 Tools

For version control of project CVS (Concurrent Versions System) and for GUI implementa­ tion Swing Toolkit were used. I choose to use IntelliJ IDEA as Java IDE despite the fact I had never used it before. For visualization I found SwingX-WS project very useful so I built vi­ sualization on it, which saved me a lot of time. To implement the functionality SwingX-WS offers would be very difficult and time-consuming.

2.1 CVS

Concurrent Versions System1 (CVS) is a version control system that enables several users to work on the same project simultaneously. It is used to maintain current and historical versions of files such as source code, web pages, and documentation in common repository.

2.2 Swing Toolkit

Swing [2] is a GUI Toolkit for Java. Swing was developed to provide a more sophisticated set of GUI components than the earlier Abstract Window Toolkit. Swing provides a native that emulates the look and feel of several platforms, and also supports a pluggable look and feel that allows applications to have a look and feel unrelated to the underlying platform unlike AWT. Swing is extensible, component-oriented, customizable, configurable lightweight user interface.

2.3 IntelliJ Idea

IntelliJ IDEA2 is a commercial Java Integrated Development Environment by the company JetBrains. This sophisticated tool enormously increase your productivity.

1. http://www.nongnu.org/cvs/ 2. http://www.jetbrains.com/idea/

5 2. TOOLS

2.4 Netbeans

Netbeans3 is a free, open-source Integrated Development Environment for software de­ velopers. All the essential functionality is supported by both IntelliJ Idea and Netbeans but for IntelliJ Idea you have to pay. Deeper comparison of these two IDEs would spread over many pages and is rather impossible due to the rhythm both IDEs keep upgrading. I myself prefer using Netbeans to IntelliJ Idea because it is open-source and the Netbeans community is bigger than the IntelliJ Idea community.

2.5 JXTA

JXTA4 0uxtapose) technology is a set of open protocols that enable any connected device on the network, ranging from cell phones and wireless PDAs to PCs and servers, to com­ municate and collaborate in a P2P manner. JXTA peers create a virtual network where any peer can interact with other peers and resources directly, even when some of the peers and resources are behind firewalls and network address translations (NATs) or on different net­ work transports.

2.6 SwingX-WS

Swing Web Services components, SwingX-WS [3], is one of the core projects of SwingLabs, an Open Source laboratory for exploring new ways to make Swing applications easier to write, with improved performance and greater visual appeal. It is an umbrella project for various Open Source initiatives sponsored by and is part of the java.net community. Successful code and concepts may be migrated to future versions of the Java platform. Overview of all major project is here: http: //swinglabs . org/pro jects . j sp. SwingX-WS project provides many useful classes and utilities for writing web ori­ ented rich client applications in Java. SwingX-WS contains a rich mapviewer component I used in visualization. The SwingX-WS project introduces a set of JavaBeans and APIs for interacting with web technologies from within Swing applications.

2.7 OpenStreetMap project

OpenStreetMap is a free editable map of the whole world. You can learn about the system in more detail from [4].

3. http://www.netbeans.org/ 4. https://jxta.dev.java.net/

6 Chapter 3 CoUniverse

3.1 System architecture

The collaborative system is organized as one or more collaborative universes, where the ac­ tual collaboration takes place, and a multiverse, which servers for registration and lookup of clients and universes. The collaborative universes are intended to accommodate collab- orativer groups up to medium sizes and thus can implement very advanced functionality. On the contrary the multiverse provides very limited functionality, it has to scale with re­ gard to large number of participating nodes.

3.2 Network organization

From the networking perspective, each universe has a control plane and zero or more data planes. Both control and data planes form overlays over existing networking substrates. The maximum robustness and as fast failure recovery as possible is necessary—therefore it may be more aggressive especially in failure detection procedures. The control plane is used for control communication of all the components in universe, currently implemented as overlay peer-to-peer network using JXTA substrate. The data plane is used for actual data exchange between the components.

3.3 CoUniverse components

The Collaborative Universe comprises the following major components:

3.3.1 Communication nodes

The nodes are participating in the control plane and run a control plane peer. Collaborative applications runs on communications nodes. The applications may be started and stopped over and over again and (re)configured between it. The applications are grouped together into application groups. Each application group has its group controller, which takes care of collaborative applications (re)configuration. Each application group has its own data plane built on the networking substrates available.

7 3. COUNIVERSE

3.3.2 Application group controllers There is one application group controller per application group. It is mainly used for (re)configuration of the application group. The AGC may do the configuration in static or dynamic modes. For dynamic modes, it features stream to link scheduler, that builds up collaboration network configuration based on media producers, consumers and reflectors, based on various constraints such as link capacity, node capacity, node capabilities, etc.

3.3.3 GUI Controller Part of Chapter 6 is dedicated to GUI Controller which was developed by me.

3.4 Monitoring

Each communication node implements monitoring of itself together with monitoring of network connectivity to other communication nodes. For scalability reasons, it may be lim­ ited to monitoring inside application groups only. There is a basic support for monitoring already developed, but more sophisticated system suitable to be integrated in CoUniverse GUI visualization is being developed in Master thesis of Be. Simon Suchomel.

3.5 Visualization

It is used for comprehension of network organization as well as for incorporation of moni­ toring data. Chapter 6 of this thesis is about visualization of CoUniverse.

8 Chapter 4 Design of CoUniverse GUI

This chapter walks you through my GUI development. The chapter tries to look at GUI development from generalized perspective at the beginning and actual CoUniverse GUI solution is given in the end. This chapter addresses namely the visual part of GUI com­ ponents, while structure of individual components is given in subsequent chapters. Many of important and necessary technologies like Java Internationalization were opted out be­ cause of thesis content limitation.

4.1 GUI designers

All professional Java IDEs have usually GUI designers. Here are some pros the GUI de­ signer brings:

• using designer saves time

• you are provided with the form which gives you a picture what GUI looks like

• you don't have to understand how Layout Managers work to be able to implement simple GUI

• your cosmetic changes are immediately shown, you don't have to compile and run application as without using designer to see them

• you are provided with additional window(s) where you can see a list of attributes or controls of the currently selected GUI component and easily change them

There are also some cons:

• moving project to another IDE is usually slightly problematic because of GUI forms

• IDE won't let you change the code it has produced directly

• not using GUI builder the code is shorter and eaiser to understand for human-being

• you have to learn using GUI designer, it is very complex tool and mastering it takes much time

9 4. DESIGN OF COUNIVERSE GUI

The pros far outweigh the cons. Most efficient method is to combine using GUI builder and writing your own code by hand. Overwhelming part of code is generated by GUI de­ signer and just additional changes are by hand. But you certainly need to understand how Layout Managers work to be able to implement complicated GUIs. It enables you to have clear idea what happens in background and to have it under control when you use GUI designer (writing GUI without using GUI designers as you start with GUI development is recommended).

4.2 Layout managers

There are several Layout Managers in Swing Toolkit. The most important two are Grid- BagLayout and GroupLayout. The GroupLayout was originally done as an open source project and was so successful that later became a part of Java SE 6. It is also default Lay­ out Manager of Mantis, Netbeans GUI builder. Before GroupLayout came the Gridbaglay- out was used for developing complicated and complex GUIs rather than any other Lay­ out Manager. The GridBaglayout is flexible and very powerful Layout Manager as well as GroupLayout. Due to wide variety of layout controls it is not easy to master these two Lay­ out Managers completely. In present the GroupLayout is preferred to GridBagLayout. The main reasons are following: GroupLayout is default Layout Manager for Mantise, runtime changes to your GUI are supported, resizing behaviour can be set per component. You can use some other layout managers for simple GUI panel if you are sure it won't change in the future otherwise you will have to rewrite whole code in order to change Layout man­ ager if unsupported functionality is needed. Therefore it is better to use powerful Layout Manager just at the beginning even if it offers much more than you need.

4.3 Components

Swing Toolkit supports various L&Fs (Look and Feel) but sometimes you need components to have specific design. Either you need very specific shape of component to fit among other components or you want unique look for your application probably because of com­ mercial reasons. As mentioned before Swing doesn't use host system native's component which gives you an option to make unique design for all of your components.

4.3.1 How painting works Every GUI component1 must be part of a containment hierarchy. A containment hierarchy is a tree of components that has a top-level container as its root. Each program that uses Swing components has at least one top-level container. This top-level container is the root of containment hierarchy—the hierarchy that contains all of the Swing components that appear inside the top-level container.

1. Swing classes which have visual representation (they have setVisible method)

10 4. DESIGN OF COUNIVERSE GUI

Every GUI component extends Container class (AWT class). JContainer class en­ capsulates functionality which enables the component to add other GUI components in it or remove them. Instances of JContainer class can be added into instance of JContainer class recursively, which results in the tree. Each GUI component can be con­ tained only once. If a component is already in a container and you try to add it to another container, the component will be removed from the first container and then added to the second container. Swing allows three GUI components to be top-level components, namely JFrame, JDi- alog and JApplet. GUI components of one application form tree resp. trees starting with top-level container resp. containers for each tree. All GUI components except top-level con­ tainers also extend JComponent class which implements paint method where look of the component is defined. This method is invoked by Swing for each GUI component to draw itself. It is important to remember that paint method is invoked in separated thread. So when you call the constructor of GUI component nothing happens what would make the component visible. You need to add instance of component into container which is directly or indirectly contained in top-level container. By doing so the component is registered for painting process. Painting starts with top-level containers whose paint methods are passed by Graphics class instances. Graphics class contains many methods you can use for actual painting (paintLine (Point pi, Point p2) draws line from Point pi to point p2, for example). Top-level container paints itself then pass Graphics class instance to all GUI components which have been added by add method into it and those components do the same thus in the end each component in the tree is reached (paints itself). This pro­ cess is done again and again everytime after something what could change the look of application happened. Not always everything is repainted there are many optimizations but they are too complex to be explained in detail. GUI components such as JButton, JLabel and so on, override the paint method from JComponent class and JComponent class overrides it from JContainer class (AWT class). The result look also depends on L&F which influences painting in paint method.

4.3.2 Visual states of Swing components Swing components can be in various visual states such as2:

• enabled state (all Swing GUI components) default state which indicates that the component can be selected or triggered by an input device, such as a mouse pointer,

• focused state (just components whose isFocusable method returns true) Many components3 - even those primarily operated with the mouse, such as buttons

2. Not all possible states are listed above, just those most commonly recognized. 3. http://Java.sun.com/docs/books/tutorial/uiswing/misc/focus.html

11 4. DESIGN OF COUNIVERSE GUI

- can be operated with the keyboard. For a key press to affect a component, the com­ ponent must have the keyboard focus. From the user's point of view, the component with the keyboard focus is generally prominent—with a dotted or black border, for example. The window containing the component is also more prominent than other windows on screen. These visual cues let the user know to which component any typing will relate. Only one component at a time in the window system can have the keyboard focus,

• selected state 0RadioButton) indicates that the component has been selected,

• rollover state 0Button) indicates that the mouse is over the component,

• pressed state 0Button) indicates that the component is pressed,

• disabled state 0Button) indicates that the button cannot be selected or triggered by an input device, such as a mouse pointer,

• selected-rollover state 0RadioButton) indicates that the component is in selected and rollover state at once,

• disabled-selected state 0CheckBox) indicates that the component is in disable and selected state at once.

4.3.3 My image button

This section shows one way how you can make a GUI component look like you wish. It is much easier than the way described in following chapter but it also doesn't offers you as many possibilities. You need to have an image for every state you want to distinguish and just set the image for that state. It can be done very easy as the following code shows: 1 public class ImageButton extends JButton { 2 3 public ImageButton() { 4 this.setlext(null); 5 this.setlcon(new Imagelcon("default.png")); 6 this.setPressedlcon(new Imagelcon("pressed.png")); 7 this.setRolloverlcon(new Imagelcon("rollover.png")); 8 this.setSelectedlcon(new Imagelcon("selected.png")); 9 this.setDisabledlcon(new Imagelcon("disabled.png")); 10 11 JButton was chosen to demonstrate how you can set icons for some states. No further explanation is given because the names of methods and images are pretty straightforward and for detailed description of states see Visual states of Swing components section 4.3.2.

12 4. DESIGN OF COUNIVERSE GUI

4.3.4 My text button This section demonstrates how to override paint method. By doing so you can create very specific and unique design for GUI components. In the end two complete components im­ plemented by me are shown which are almost identical to those I used in CoUniverse GUI.

Firstly, we create skeleton of a button: 1 public class MyButtonl extends JButton { 2 3 public MyButtonl (String text) { 4 this.setlext(text); 5 this.setBorderPainted(false); 6 this.setContentAreaFilied(false); 7 this.setFocusPainted(false); 8 } 9 10 SOverride 11 public void paint (Graphics g) { 12 Graphics2D g2 = (Graphics2D) g; 13 14 //content painting 15 g2 . setColor (new Color (255, 255, 255)); 16 g2.fillRoundRect(1, 1, getsize().width - 3, getsize().height - 3, 10, 10); 17 18 //border painting 19 g2 . setColor (new Color (0, 0, 0 ) ) ; 20 g2.draw(new RoundRectangle2D . Double (1, 1, getsize() .width - 3, 21 getsize () .height - 3, 10, 10)); 22 //text painting 23 g2 . setColor (new Color (0, 0, 0 ) ) ; 24 g2 .drawstring (this .getlext () , 20, 15); 25 26 g2 . dispose () ; 27 } 28 } The body of the constructor is explained bellow. As you can see in the overridden paint method we just "manipulate Graphics". Buttonl class example code only paints custom content, border and text. To understand methods of MyButtonl class exam­ ple code on lines 16 and 20 see http: //Java. sun. com/docs/books/tutorial/2d/ index .html. Paint4 method actually delegates the work of painting to three protected meth­ ods: paintComponent, paintBorder and paintChildren. They're called in the order listed to ensure that children appear on top of component itself. Generally speaking, the component and its children should not paint in the insets area allocated to the border. Sub­ classes can just override this method, as always. A subclass that just wants to specialize the UI (L&F) delegate's paint method should just override paintComponent. Appli­ cations should not invoke paint method directly, but should instead use the repaint method to schedule the component for redrawing. If Buttonl code example contained any

4. http://Java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#paint(Java. awt.Graphics)

13 4. DESIGN OF COUNIVERSE GUI

Q@Q

í My Button 1 ]

Figure 4.1: My Buttonl.

child components we would have to invoke paint Children method. In the constructor of MyButtonl example code on the lines 3 we set border not to be drawn. Actually, we do not have to because paintBorder method is not invoked from within the body of paint method. Notice that on the first line in paint method (line 12 in MyButtonl example code) a Graphics object is cast into Graphics2D object. This Graphics2D5 class extends the Graphics class to provide more sophisticated control over geometry, coordinate transformations, color management, and text layout. This is the fundamental class for ren­ dering 2-dimensional shapes, text and images on the Java platform. Sometimes we want to customize the component just a little then it is recommended that the body of the paintComponent method comprises custom changes followed by invocation of the ancestor's paint method. Then the paintComponent method could look like this: i public class MyButton2 extends JButton { 2 3 public MyButton2() { 4 this.setlext("My Button 2"); 5 this.setFocusPainted(false); 6 7 8 SOverride 9 public void paintComponent(Graphics g) 10 Graphics2D g2 = (Graphics2D) g; 11 super.paint(g); 12 if (this.isFocusOwner()) { 13 int[] xPoints = {2, 2, 10};

5. http://Java.sun.com/javase/6/docs/api/java/awt/Graphics2D.html

14 4. DESIGN OF COUNIVERSE GUI

14 int[] yPoints = {2, 10, 2}; 15 g2.fillPolygon(new Polygon(xPoints, yPoints, 3) 16 17 g2.dispose( 18 19

0(3©

My Button 2 jButton2

Figure 4.2: On the left button our focus is painted (MyButton2). On the right button called jButton2 you can see default JButton focus painted.

Important: we do not override paint method anymore paintComponent method is overridden instead. This is how it should be. The previous examples were to give idea of how it all works. Notice that in MyButton2 example code we do not forbid default content and border to be painted as in MyButtonl example code on lines 5 and 6 because we want the default con­ tent and border to be painted for MyButton. It also very important to invoke s upe r. pa i nt method before custom painting because otherwise custom painting would be invisible. It would be overlaid by default content painting, now it is vice-versa not to be hidden. New problem occurs the moment we want custom text to be drawn over button. For ex­ ample imagine we want to draw text overlaid by the same, little shifted text to get shadow effect. Than default text drawing is now unwanted. Be aware there is no method which can prevent text from being painted (no method like setTextPainte exists). One choice is to set the text to empty String (setText ("")) or to null (setText (null)) then clearly no text is painted. But we do need JButton to calculate its preferredSize and it does it according to its text and font. Of course, we can calculate preferredSizeby ourselves, but it is not so easy because besides actual text and font the

15 4. DESIGN OF COUNIVERSE GUI

text size also depends on FontRendererContext instance. The FontRenderContext6 class is a container for the information needed to correctly measure text. The measure­ ment of text can vary because of rules that map outlines to pixels, and rendering hints provided by an application. Typically, instances of FontRenderContext class are ob­ tained froma Graphics2D object. A FontRenderContext instance which is directly con­ structed will most likely not represent any actual graphics device, and may lead to unex­ pected or incorrect results. Graphics2D is a parameter of paintComponent method. Procedure of laying out component has these steps in following order: Layout Manager of container where components have been added asks for preferredSizes of compo­ nents, Layout Manager calculate positions and sizes of added components, set locations of component within the scope of frame eventually adjust their sizes, invoke paint method from which paintComponent method is invoked. In the last step paintComponent method is invoked and is passed Graphics2D object from which FontRenderContext instance can be obtained. But it is to late for us to calculate pref err edS i ze in the last step. We have to know it before container asks for it otherwise container shrinks the component to minimum because of default pref erredSize of component. Second choice is to set the text of button but make sure it is not painted. We make sure the text is not painted even if it is set by overriding paintComponent and being careful not to invoke ancestor's paintComponent or ancestor's paint method. In this case the preferredSize is calculated by button for us and we can paint the text in any way we want on the button. Logically, we set the text of button to the text we want to paint to get preferredSize ofthat text. Besides preferredSize calculation we even avoided calculation of the button text position. In MyButtonl example code we set it by hard what will soon or later result in the button text misplacing. It is quite common for all buttons inside application to have the same size. When hard-setting size of buttons you will have restrict length of the button text but on the other hand all problems coming with pref erredSi ze calculating will be avoided. Labels have hardly-ever hard-set sizes. Here is the first example where the size of button is hard-set: 1 public class MyButton3 extends JButton { 2 3 public MyButton3() { 4 this.setlext(null); 5 this.setContentAreaFilied(false); 6 this.setFocusPainted(false); 7 this.setBorderPainted(false); 8 this.setFont(new Font("SansSerif", Font.PLAIN, 13)

9 } 10 11 SOverride 12 public Dimension getPreferredSize() { 13 return new Dimension (132, 32); 14 } 15 16 SOverride

6. http://Java.sun.com/j2se/l.4.2/docs/api/java/awt/font/FontRenderContext.html

16 4. DESIGN OF COUNIVERSE GUI

17 public void paintComponent(Graphics g) { 18 Graphics2D g2 = (Graphics2D) g; 19 TextLayout textLayout = new TextLayout("My Button 3", getFont(), 20 g2.getFontRenderContext() ) ; 21 Rectangle2D boundsOfText = textLayout.getBounds(); 22 23 if(boundsOfText.getwidth() => this.getsize()){ 24 //length of button text is too long, not whole will be visible 25 26 27 g2.setColor(Color.WHITE); 28 g2.fillRoundRect(1, 1, (int)getPreferredSize().getwidth() - 3, 29 (int) getPreferredSize().getHeight()-3, 10, 10); 30 31 g2.setColor(Color.BLACK); 32 g2.drawRoundRect(1, 1, (int)getPreferredSize().getwidth()-3, 33 (int)getPreferredSize().getHeight()-3, 10, 10); 34 35 double startPositionOfText = (getPreferredSize().getwidth() 36 - boundsOfText.getwidth()) /2; 37 g2.drawstring("My Button 3", (int) startPositionOfText + 2, 20); 38 39 g2.dispose(); 40 41

Figure 4.3: My Button3.

Method getPrefferedSize is overridden as well. This means the button has hard- set size. On the lines 16 and 17 of MyButton3 example code is shown how bounds of text can be found out. We need width of the text to be able to centre it. It has to be done in paintComponent method because FontRenderContext is needed and can be only ob­ tained from Graphics2D. Here is code of Mylabel with changeable width based on text: 1 public MyLabel extends JLabel{

17 4. DESIGN OF COUNIVERSE GUI

2 public MyLabel() { 3 this.setiext("Loooooooong text"); 4 this.setFont(new Font ( "Lucida Bright", Font.ITALIC, 18)); 5 Dimension d = this.getPreferredSize(); 6 d.setSize(d.getwidth() + 50, d. getHeight ()) ; 7 this.setPreferredSize(d); 8 } 9 10 SOverride 11 public void paintComponent (Graphics g) { 12 Graphics2D g2 = (Graphics2D) g; 13 g2.setRenderingHint(RenderingHints.KEY_ANIIALIASING, 14 RenderingHints.VALUE_ANIIALIAS_ON); 15 16 //content painting 17 GradientPaint background = new GradientPaint(0, 0, new Color(255, 255, 255), 18 0, getSize () .height / 2, new Color (0, 0, 0), true); 19 g2 . setPaint (background) ; 20 g2 . fillRoundRect (1, 1, getSize () .width - 3, getSize () .height - 3, 40, 40); 21 22 //border painting 23 g2 . setColor (new Color (255, 255, 255)); 24 g2 . setstroke (new BasicStroke (2 . Of, BasicStroke . CAP_BUH, 25 BasicStroke.CAP_BUII, 10. Of)); 26 g2.draw(new RoundRectangle2D . Double (1, 1, getsize() .width - 3, 27 getSize () .height - 3, 40, 40)); 28 29 //text painting 30 TextLayout tl = new TextLayout(this.getlext(), this.getFont(), 31 g2 . getFontRenderContext () ) ; 32 int startPositionOfText = getSize().width - (int) tl.getBounds().getwidth(); 33 startPositionOflext = startPositionOfText / 2; 34 35 g2 . setColor (new Color (0, 0, 0 ) ) ; 36 g2.drawstring(this.getlext(), startPositionOflext + 2, getHeight() / 2 + 7); 37 38 g2.setColor(new Color(255, 255, 255)); 39 g2.drawstring(this.getlext(), startPositionOflext, getHeight() / 2+5); 40 41 g2 . dispose () ; 42 } 43 }

Now we have to change the button look based on the state the button is in. Button has its model since Swing is based on (modified) MVC architecture7. The model can be asked for states of the button. So in next example we change the look of button when a mouse is over the button. All we need to do is to substitute line 26 of MyButton3 example code with following piece of code:

1 if(getModel().IsRollover()){ 2 g2.setColor(Color.CYAN); 3 } else { 4 g2.setColor(Color.WHITE); 5 }

7. Model-view-controller pattern: http : //en .wikipedia.org/wiki/Model-view-controller

18 4. DESIGN OF COUNIVERSE GUI

Figure 4.4: MyLabel (almost identical to label I used for CoUniverse GUI).

The previous examples cover almost everything what is needed to know about over­ riding paintComponent method. Good knowledge of Java 2D and we are free to create whatever look we desire. Here is example which can stand for full-featured button: i public class MyButton extends JButton { 2 3 public MyButton(String text) { 4 this.setlext(text.toUpperCase()); 5 this.setFont(new Font("SansSerif", Font.ITALIC, 12) 6 setContentAreaFilled(false); 7 setBorderPainted(false); 8 setFocusPainted(false); 9 10 11 SOverride 12 protected void paintComponent(Graphics g) { 13 Graphics2D g2 = (Graphics2D) g; 14 g2.setRenderingHint(RenderingHints.KEY_ANIIALIASING, 15 RenderingHints.VALUE_ANIIALIAS_ON); 16 17 //background painting 18 GradientPaint background = new GradientPaint(0, 0, new Color (255, 255, 255) 19 0, getPreferredSize().height / 2, new Color(0, 0, 0), true) 20 if(getModel().isRollover()){ 21 background = new GradientPaint(0, 0, new Color(255, 255, 255), 22 getPreferredSize().width , getPreferredSize().height , 23 new Color(0, 0, 0), true); 24 25 if(getModel().isPressed()){ 26 background = new GradientPaint(0, 0, new Color(255, 255, 255), 0, 27 getPreferredSize().height /2, new Color(210, 210, 210), true) 28 29 g2.setPaint(background); 30 g2.fillRoundRect(1, 1, getPreferredSize().width - 3 , 31 getPreferredSize().height - 3, 10, 10) 32

19 4. DESIGN OF COUNIVERSE GUI

Q@©

My Button 4 My Button 4

Figure 4.5: My Button4.

33 //Border painting 34 g2.setColor(new Color(255, 255, 255)); 35 g2.setstroke(new BasicStroke(2.Of, BasicStroke . CAP_BUH, 36 BasicStroke.CAP_BUII, 10.Of)); 37 g2.draw(new RoundRectangle2D.Double(1, 1, getPreferredSize( .width - 3, 38 getPreferredSize().height - 3, 10, 10));

40 //focus painting 41 if (this.isFocusOwner()) { 42 int[] xPoints = {2, 2, 14}; 43 int[] yPoints = {2, 14, 2}; 44 g2.fillPolygon(new Polygon(xPoints, yPoints, 3) 45 46 47 //text painting 48 g2.setFont(getFont()); 49 TextLayout tl = new TextLayout(getText(), getFont() g2.getFontRenderContext()); 50 int startPositionOfText = getPreferredSize().width (int) tl.getBounds().getwidth( 51 startPositionOfText = startPositionOfText / 2; 52 53 g2.setColor(new Color(255, 255, 255)); 54 g2.drawstring(getText(), StartPositionOfText -2, getHeighti / 2 + 5) 55 56 g2.dispose(); 57 58 59 SOverride 60 public Dimension getPreferredSize! 61 return new Dimension(132, 32); 62 63

20 4. DESIGN OF COUNIVERSE GUI

Figure 4.6: States of MyButton (almost identical to button I used for CoUniverse GUI).

Last method you should be aware of is contains method from Component class (AWT class). This method takes two parameters, x/y coordinates, and returns boolean value. It gives the UI delegate an opportunity to define the precise shape of this compo­ nent for the sake of mouse processing by deciding whether the x/y coordinates belongs to content of the component. Logically, in most cases you just ask a shape object you use for content painting whether it contains the x/y coordinates and return result. Fact that many classes in Java 2D have contains method makes it even easier.

4.4 Swing Worker

SwingWor ker 8 is an abstract class to perform lengthy GUI-interacting tasks in a dedicated thread. When writing a multi-threaded application using Swing, there are two constraints to keep in mind: time-consuming tasks should not be run on the Event Dispatch Thread (otherwise the application becomes unresponsive). Swing components should be accessed on the Event Dispatch Thread only.

8. http://Java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html

21 4. DESIGN OF COUNIVERSE GUI

A user-friendly program provides some indication to the user that the task is occur­ ring, how long the task might take, and how much work has already been done. For such an indication ProgressBar or a ProgressMonitor is used with combination of SwingWorker. There are two types of tasks: tasks whose progress cannot be measured and tasks whose progress can be measured. A typical example of measurable task is copy­ ing data task. Program is capable of calculating amount of already transferred data so can display percentage of all data which has already been transferred. CoUniverse GUI has to wait for the node to join Application Peer Group and then for Application Group Con­ troller to send network topology data. This is example of task whose progress cannot be measured because the internet is involved and behaviour of internet is unpredictable. For these types of task indeterminate ProgressBar is used.

22 Chapter 5 GUI for CoUniverse Configuration

In this chapter describes the part of CoUniverse GUI I designed and implemented for con­ figuration of CoUniverse nodes. Main window of this part is shown on Figure 5.1. All components have Round Rectangle shapes and are placed on white background. Top, bottom and left component are permanent and just right (or centre) component changes. In the first phase the main job of GUI is to walk a user through several settings. The right component shows which settings has been done, actual one and which are still waiting for the user. By clicking next resp. back button user can go to next setting resp. previous setting. The biggest advantage of this besides better orientation for user in appli­ cation is that you can get enough information for some swing worker task to run before all settings are completely finished. So many tasks are being processed while user fulfils an­ other setting. But it really complicates application because of back button. User may want to go back to setting he has already done and change something then some swing worker tasks might have to be restarted. The easiest solution is to dispose back button after swing worker task has been run but it is not user-friendly solution. In addition, in case user clicks back button he is not supposed to write everything again thus previous settings have to be hold in memory.

5.1 Configuration

First four modules of CoUniverse GUI enables user to completely configure instance of NetworkNode class. The last module displays CoUniverse Visualization described in next Chapter 6. The first module of whole configuration called Initial Settings (actually selected module on Figure 5.1) enables user to choose configuration file together with some basic settings needed to join Universe Peer Group. The second module, Node settings, contains information about local node such as node name, geographical position of node and so on. Design structure of Interfaces settings is list to which user can add new interfaces or delete or edit existing interfaces from it. The last module of settings, Applications, allows user to set applications which will be running on the local node. The desing structure for Applications settings is the same like structure for Interfaces settings.

23 Collaboration Universe =|njxj era 3 (D Collaboration Universe

n o P"1 era 3 tu ri- CÍ' 3 t/i n m O 3 i—i •n n O o n 3 o t/l O < M c/i M n o n c > H hr- O 5. GUI FOR COUNIVERSE CONFIGURATION

5.2 Start of GUI

GuiMain class contains main method which starts CoUniverse application with GUI (it is possible to start CoUniverse without GUI). This class also sets L&F of application. Some calculation to make possible displaying of the CoUniverse GUI over several screens were started here but not finished. GuiMain class was meant to contain all static settings which can be performed in advanced.

5.3 Refactoring

GuiUniversePeer class is new refactorized version of UniversePeer class to suit GUI flow control of application. It is class from within the logic of application can be controlled. This class is very complicated and should be tested in the future.

5.4 Top-level container

BaseFrame class is top-level container of application which extends JFrame. I created ContentPanePanel class which serves as content pane for BaseFrame. That enabled me to move a lot of code which is usually placed into top-level container of application to its content pane. By doing this I was able to separate "GUI logic" from all the other code (GUI usually need a lot of code and I didn't use GUI designer). This class works as listener for most of events. This class also comprises various tasks by which GuiUniversePeer class is operated from GUI. These tasks are inner classes extending SwingWorker class thus can be run by execute method.

5.5 Bottom panel

Bottom panel component on Figure 5.1 is implemented by MyButtonPanel class. It con­ tains main buttons of application whose events are caught in BaseFrame class.

5.6 Title panel

Title panel on Figure 5.1 is implemented by MyTitlePanel class. The component only shows the name of the application. The text of title panel enlarges together with whole frame of CoUniverse GUI when a user enlarges that frame.

5.7 Progress Visualization

The left component on Figure 5.1 is implemented by MyPr ogre s sPanel class. It indicates what is the current setting of application the user sets.

25 5. GUI FOR COUNIVERSE CONFIGURATION

5.8 My components

Other classes whose name consists of "My" plus Swing GUI component name where the capital'}' is opted out at the beginning are just standard Swing GUI component in which paintComponent method is overridden analogically as in My text button section to fit the look of the CoUniverse GUI (for example MyCheckBox class extends JCheckBox class). The functionality of these components is mostly unchanged or very similar to standard Swing GUI components they extend.

26 Chapter 6 Visualization of CoUniverse Network

The goal of visualization was to create frame in which you can browse world map. On the map participants of CoUniverse are shown as well as connections between them. Visu­ alization also offers information about participants. Output of monitoring is integrated. I didn't completely finished visualization of connections and monitoring output integration as the monitoring framework for CoUniverse is still unfinished—thus I've only utilized those interfaces, that are currently available.

6.1 Design

Main screen of the visualization is shown in Figure 6.1. As you can see the title panel is still the same. Left Panel is no more needed that's way it was opted out. Bottom panel is the same just contains different buttons. The middle is fulfilled by world map. In the left-bottom corner of map is zoomer consisting of slider and small plus and minus but­ tons. In the top left corner is opaque panel showing information about actually selected CoUniverse participant.

6.2 JXMapViewer class

JXMapViewer class[5] was the first class in SwingX-WS project. It implements world map browser. The JXMapViewer class is based on dividing the entire world map up into equal sized tiles which you reference with an x/y coordinates. A tile based map is essentially a pyramid of square bitmaps. At the top level you have a single bitmap with a certain size, for example 256 x 256 pixels. In the level below there are four tiles, also 256 x 256 each. On the third level there are four tiles for each tile in the second level, for a total of sixteen. When you continue on down the number of tiles grows by a factor of four. As you can imagine this creates a lot of tiles. The total zoom levels is the number of levels in your tile pyramid. The minimum and maximum zoom levels are the limits placed on the user navigating within the levels. First maps which were used for JXMapViewer class were from Google's map server and it uses such a tile based map. SwingX-WS developers found that concept very user-friendly That's the reason why they based JXMapViewer class on it. More precisely, tile is rectangular piece of map referenced by x/y coordinates and zoom level. Some other possible world map provider servers, for example NASA Maps, use different system for

27 6. VISUALIZATION OF COUNIVERSE NETWORK

Figure 6.1: Visualization part of CoUniverse GUI.

28 6. VISUALIZATION OF COUNIVERSE NETWORK map referencing but SwingX-WS project can convert those systems to tile-based system, which enables you to use them all through common interface. The JXMapViewer class uses a TileFactory implementation to retrieve the actual tiles. The Def aultTileFactory class implements the basic tile loading and geometric transformation behaviour required for your typical tile based map server like Google Maps and Yahoo Maps. You just need to provide information about the server to the Def aultTileFactory class and it will take care of the rest. You do this using an instance of TileProviderlnfo class where you have to set, for example url of tile provider server, max/min zoom level, tile size and so on.

6.3 GUI Controller

GUI controller collects monitoring data from all nodes, processes it and distributes it back to nodes which has registered for it. Node can register just for some of monitoring data (for example if it has slow internet connection). Map visualizer assembles information showed on map from followings: graph and monitoring data where monitoring data consists of global network monitoring and local network monitoring data. From graph participants and their communication connections are painted. Job of global monitoring is to notify visualization when new participial joins or when any of existing leaves the CoUniverse network. Local monitoring keeps an eye on participants themselves, for example it provides info about applications running on a network node to visualization. This type of monitoring required one node to communicate with another so that each node receives data from all nodes participating in CoUniverse network except itself. Complexity of such a monitoring is number of participants to the power of two. In order to decrease this complexity of network nodes monitoring data ex­ changing new components called GuiController class was created. Now all nodes send the data just to GUI Controller. GuiController class process received monitoring data and distributes them back to nodes. Flowing of all monitoring data through one "throat" brings many advantages. Later, statistics calculation can be implemented, for example. Another advantage is that GuiController class enables participants to register just for some monitoring data or they can reject receiving any monitoring data (they proba­ bly have low bandwidth and they want to use it rather for applications than monitoring). GuiController class is very similar to Application Group Controller. GUI Controller uses input and output pipes to communicate with CoUniverse network nodes as well as any other participants of CoUniverse network. Pipes [6] are the default way in JXTA by which peers can communicate with each-other. Participant become a peer by publishing JXTA advertisement, an XML structured docu­ ment, which names, describes and publishes a JXTA resource such as a peer, a peer-group, a JXTA pipe etc. A pipe is a virtual, unreliable and uni-directional communication chan­ nel implemented on top of existing networking protocols (such as TCP/IP or Bluetooth). A pipe can be bound to any two or more peers dynamically, during run-time. JXTA pipes are said to be virtual because they can be re-used and be bound to different peers after they

29 6. VISUALIZATION OF COUNIVERSE NETWORK

have been created. Additionally, since they are uni-directional, a pipe is an output pipe to the peer that is sending a message and the same pipe is an input one to the peer that is receiving the message. Pipes can be divided in point-to-point pipes and propagate pipes. The difference of these two kinds of pipes is that a point-to-point one connects exactly two peers at a time, while a propagate one connects an output endpoint to more that one input endpoints, and can therefore broadcast a message. Pipes are constructed using MyJXTAConnector class. MyJXTAConnector class, Co- Universe project class, is based on JXTA framework and extends it. It was developed with purpose to make some operations upon JXTA framework easier and faster. Sending mes­ sages via pipes works in very similar way to event listeners system in Swing Toolkit. You just have to create your own messages (events) the rest is the same. Messages are identified by a UUID (an 128-bit identifier). They are required by the protocol to travel only through JXTA pipes. Messages are designed as datagrams and as such they contain an envelope and stacks of protocol headers along with their bodies. Their envelopes must also contain headers, the source endpoint and the destination endpoint. Nodes have to register for set of messages types they want to receive. Messages are then send by invoking methods on pipes. JXTA takes care of messages transmission itself.

6.4 Layout on map

JXMapViewer class offers you very easy way how to implement your own drawing on the map. After map painting it invokes WaypointRenderer . paintWaypoint method for each Waypoint and pass Graphics2D instance to it by which you can easily do your custom additional painting. Waypoint is a class which represents map location in SwingX- WS project. All you have to do is to implement the WaypointRenderer [ 7 ] interface. These example demonstrates how you can draw red cross on the map for each Waypoint: 1 painter.setRenderer(new WaypointRenderer() { 2 public boolean paintWaypoint(Graphics2D g, JXMapViewer map, Waypoint wp) { 3 g.setColor(Color.RED); 4 g.drawLine(-5,-5,+5,+5); 5 g.drawLine(-5,+5,+5,-5); 6 return true; 7 } 8 }) ; The WaypointPainter class does all necessary coordinate calculations and pre- translates the Graphics2D object before calling your paintWaypoint method. This means the centre of the Waypoint will be at 0,0, so creating a ten-pixel X is easily ac­ complished by drawing from -5 to +5. References to the map and current Waypoint are provided in case your code needs to conditionally draw certain Waypoints differently. The return Boolean is not currently used so you can just return true. To show further information about nodes on the map click it was required to find out which node where clicked by user on the map if any. I straggled with implementation of this quite a long. There are two possibilities I discovered how you can implement it. First,

30 6. VISUALIZATION OF COUNIVERSE NETWORK you can use no Layout Manager and implement your own Waypoint class which extends JLabel. Then you just add listener for click on JLabel. Second, you can implement contains method in Waypoint class and register JXMapVisualizer class as MouseListener events. Contains method of each Way- point is invoked and passed by point containing coordinates of user's click on the map. If place on the map representing Waypoint contains point coordinates contains method re­ turns true otherwise false. Obviously, precise position of Waypoint on the map normalized to map frame has to be added to Waypoint and regularly renewed each time map repaints. That can be easily obtained from JXMapViewer instance. Further information about last time clicked CoUniverse node is shown on the top-left opaque panel you can see on figure 6.1.

6.5 Visualization components

Visualization consists of main components listed in following subsections.

6.5.1 Top-level container

Top-level container was implemented by MyMapVisualizerPanel class. Every GUI component of CoUniverse visualization was placed on this panel. I had to change MyButtonPanel class. The middle part of CoUniverse GUI in visualization state is new. Only part which stayed totally unchanged was TitlePanelclass anything else was differ­ ent for visualization state of CoUniverse GUI. To make moving to visualization state easier I decided to create thisMyMapVisualizationPanel class. All visualization components are put together on it so that the ContentPanePanel class which served as content pane for top-level container before can be easily replaced with this class. It means that even in­ stance ofMyTitlePanel class was replaced with new one not to complicate GUI.

6.5.2 Map browser

Map browsing was implemented by MyMapVisualizator class. This main class of vi­ sualization which extends JXMapVisualizer class was already described in this Sec­ tion 6.2. Zoom slider, custom painting of Waypoints and MyNodeWaypointlnf oPanel were added to JXMapVisualizer class.

6.5.3 GoogleTileFactory class

This class extends DefaultTileFactory class from SwingX-WS project. It enables MyMapVisuali zer class to download maps from Google Maps Server.

31 6. VISUALIZATION OF COUNIVERSE NETWORK

6.5.4 NasaTileFactory class This class extends DefaultTileFactory class from SwingX-WS project. It enables MyMapVisuali zer class to download maps from Nasa Maps Server.

6.5.5 OpenStreetsTileFactory class

This class extends DefaultTileFactory class from SwingX-WS project. It enables MyMapVisuali zer class to download maps from OpenStreetMap Server.

6.5.6 Node information Further information to currently-selected node is provided by opaque panel which is im­ plemented by MyNodeWaypointInf oPanel class.

6.5.7 Bottom panel Bottom panel is implemented by BottomPane 1 class. Buttons of this panel enables user to switch between Google Maps, Nasa and OpenStreet Maps provider, get to home position on the map and change size of the map.

32 Chapter 7

Conclusions

The main objective of this thesis was to design and implement a GUI for CoUniverse, a complex and sophisticated collaborative environment. Necessary prerequisite for this was thorough understanding of CoUniverse framework. The GUI has been designed suc­ cessfully. The central part and node configuration has been fully implemented. In terms of network visualization, I've only utilized the interfaces that are currently available and thus only map-based view of CoUniverse network with visualization if implemented plan is available. The real-time monitoring data are not incorporated as necessary interfaces were not available before submitting this thesis. I have largely expanded my knowledge of Swing Toolkit, Threads, JXTA and many other Java frameworks. Working with IntelliJ IDEA, a Java IDE new to me, has been a source of rich experience for me. I really enjoined working with SwingX-WS framework despite the fact there is still a few problems in its implementation that need to be overcome.

33 Bibliography

[1] Petr Holub, Miloš Liška, and Luděk Matýska. CoUniverse: Self-organizing collabora­ tive environment. In GLIF2007 Workshop, Prague, Czech Republic, 2007.

[2] James Elliott, Robert Eckstein, Marc Loy, and David Wood. Java Swing, Second Edition. 2003.

[3] Richard Bair. Web swinging. Java Today, December 2006. http://today.java. net/pub/a/today/20 06/10/11/web-swinging.html.

[4] OpenStreetMap project, http://www.openstreetmap.org/.

[5] Joshua Marinacci. Getting started with the Aerith Mapping Component, July 2006. http://weblogs.Java.net/blog/joshy/archive/20 06/0 7/getting_ started.html.

[6] JXTA-specific entities and terminology, http: //www. des . gla. ac .uk/~iraklis/ fyp_report/node22.html.

[7] Joshua Marinacci. Building Maps into Your Swing Application with the JXMapViewer, October 2007. http: / /today. j ava . net /pub/a/today / 2 0 0 7/10/ 30/building-maps-into-swing-app-with-jxmapviewer.html.

34 Appendix A CD

The attached CD contains the following items:

• PDF version of the thesis,

• LATEX source files plus all images required to compile the thesis,

• and source files of CoUniverse GUI implementation.

The PDF version of the thesis is located directly in the root directory of the CD. Source files and images used to compile the thesis are located in the thesis directory. Source files of CoUniverse GUI implementation is available in the CoUniverse directory. All classes located in package GUI plus GuiController. class in GuiController package of Co- Universe project were implemented by me.

35