SCHOOL OF ADVANCED TECHNOLOGY ICT - Applications & Programming Computer Engineering Technology – Computing Science JAP Java Application Programming LECTURES NOTES 1 This material is exclusive for CST8 221 – JAP Course at Algonquin College. 1 Originally developed by Prof. Svillen Ranev (Algonquin College, 2020) and Daniel Cormier (2021). Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 2 Welcome to a beautiful season in the Canadian Capital City... Source : https://www.forbes.com/sites/miriamporter/2019/09/29/outdoor - fall - activities - in - ottawa Lecture Notes – Summere/Spring , 2023 Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 3 Preface 1 About this Document Some initial notes: • This content does not intend to replace the resources from the book, that it is still required to study and has several examples that can be used in your apprenticeship. o Java How to Program, Early Objects , 11th Edition, by Deitel and Deitel, Published by Pearson Education Inc., 2018, ISBN - 13: 978 - 0 - 13 - 474335 - 6. • The included notes summarize concepts, and resources used to develop hybrid activities in the Java Application Programming ( JAP ) Course. • This course combines a set of concepts that will be integrated in the theoretical and practical components • The practical component (Labs) is integrant part of the course and an important element of the final grade. Compilers is not only a theoretical course, maybe the labs (and Assignments) are the most interesting part of it Important Advice: The progressive development This document will be updated weekly, including additional topics according to the development of the course. Articles covered in this version: Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 4 SECTION I – GUI Basics • Article 1 : GUI Introduction / Softwre Engineering • Article 2 : Java GUI (Basics) • Article 3 : Starting GUI Applications • Article 4 : Understanding Events • Article 5 : Working with Menus SECTION II – Advanced Java • Article 6 : Design Patterns and MVC • Article 7 : Java Threads • Article 8 : Networking • Article 9 : C/S Architecture and Protocols • Article 10 : Databases and JDBC See also some Appendix with basic code and information about topics In the end of each article, you will see a brief note / task about Software Engineering notes related to UML diagrams. The Hybrid materials (see the other file) contains the essential about UML diagrams and tip s to develop models. Finally, it is important to thank prof essors Svillen Ranev and Daniel Cormier for the original material developed and his work in continuously improve these lectures and motivate generations of programmers, in a scenario where Java Programming is fundamental / --------------------------------------------------------------------- \ | | | # / ------------------------------------ \ | | ## | A L G O N Q U I N C O L L E G E | | | ## # | JAVA APPLICATION PROGRAMMING | | | ### ## | S U M M E R - 2 0 2 3 | | | ### ## \ ------------------------------------ / | | ### ## | | ## ### ### | | ## ### ### | | ## ## ### ##### ## ## ##### | | ( ( ((((() ### ## ### ### ## | | (((( (((((((( () ### ###### ### ## ###### | | (( () ### ## ## ## ## ## ## | | ((((((((((((( ((() ### ###### ### ###### | | (( (( #### | | (((((((((((( | | ((( ( | | ((((((((((((((((((((((())) ( | | ((((((((((((((((((() | | | \ --------------------------------------------------------------------- / Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 5 Good luck with the course... JAP Professors, Algonquin College, Spring/Summer , 202 3 Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 6 Part I Article Notes Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 7 Article 1 GUI Introduction 1.1. GUI Fundamentals Graphical User Interface (GUI) is a Human - Machine Interface used for interaction between humans and computers. • The GUI consists of two basic parts: input devices and an application window for output. o The basic computer input devices are keyboard and mouse, but there are quite a number of other input devices as well, such as touchscreens you can find on tablets and mobiles. • The application window is an image (in other words, graphics) displayed on a computer screen. o Using the input devices, the user manipulates differ ent parts of the application window. o This interaction is made possible by the operating system which works seamlessly in the background. In many cases, the operating system provides the basic building - blocks that get used to build the application window. Figure 1.1: Schematic view of a pplications In order to create a GUI, programmers use some kind of application programming interface (API) provided by the language library they a re using. If they work directly with the underlying windowing system provided by the operating system, this kind of programming is called native window programming. Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 8 Figure 1.2: Several GUI components 1.2. Basic Principles of Good Interaction Design • Clear Mental Model : The user should understand the overall purpose of the software and how the individual components come together. How the software operates, on the level of user interaction, should make sense. • Reassuring Feedback : The user should know if they’ve done so mething successfully; the software should communicate on some level. For instance, when the user clicks on a button, the button should change its graphics to indicate it’s been clicked on. • Navigability : The user should know where they are in the system. They should have a clear idea what they can do there, where they can go next, and how they can get back. • Consistency : Every command with the same name should act the same way everywhere in the software. For instance, selecting “Copy” from the Edit menu s hould work exactly the same way as selecting “copy” from a right - click pop - up menu. • Intuitive Interaction : This sounds a lot like the clear mental model listed above, in a sense. A user should have a good sense of how the software behaves, without having to invest a great deal of thought. This is like the “clear mental model”, but on a smaller, more immediate level. The purpose of each button, each menu item, should be easy. • Behavior : Or in other words, performance. There are potentially many solution s to a given coding problem, but ones that don’t work well may leave the mouse moving sluggishly, or button clicks less responsive. Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 9 • Appropriateness : The UI, and its controls, should be relevant to the task at hand. A first - person shooter game requires a d ifferent set of interactions and controls than a spreadsheet, and imposing a clumsy pull - down menu in the middle of an online firefight is going to result in a substandard experience for the users. • And finally, Importance : There are a variety of ways a UI element can be presented to the user, and how it reacts to input. It might be just text, or have an icon, animations, or even sound. Features with important consequences should use many of those elements, such as the Recycle Bin. The Recycle Bin is grap hical, animated, has a text label and plays sounds, and deleting files permanently from one’s computer is much more important than whether a bit of text is bold. 1.3. Guidelines for Interface Design Process Here are some guidelines for the user interface (GUI ) design process outlined in the book “ The Essential Guide to User Interface Design 2ed ” by Wilbert O. Galitz, Wiley Computer Publishing. The 14 development steps typically followed in creating a graphical system's or Web site's screens and pages are: • Step 1: Know Your User or Client. To begin, an understanding of the most important system or Web site component, the user or client, must be obtained. Understanding people and what they do is a critical and often difficult and undervalued process. The firs t step in the design process involves identifying people's innate and learned characteristics, and understanding how they affect design. • Step 2: Understand the Business Function. A system or Web site must achieve the business objectives for which it is designed. To do so requires an understanding of the goals of the system and the functions and tasks performed. Determining basic business functions, describing user activities through task analysis, understanding the user's mental model, and developing a c onceptual model of the system accomplish this. The system's conceptual model must fit the user's view of the tasks to be performed. Step 2 also addresses the establishment of design standards or style guides, and the definition of training and documentatio n needs. • Step 3: Understand the Principles of Good Screen Design. A well - designed screen must reflect the needs and capabilities of its users, be developed within the physical constraints imposed by the hardware on which it is displayed, and effectively utilize the capabilities of its controlling software. Step 3 involves understanding the capabilities of, and limitations imposed by, people, hardware, and software in designing screens and Web pages. It presents an enormous number of general design princi ples for organizing and presenting information to people. • Step 4: Develop System Menus and Navigation Schemes. Graphical systems and Web sites are heavily menu - oriented. Menus are used to designate commands, properties that apply to an object, documents, and windows. To accomplish these goals, a variety of menu styles are available to choose from. Step 4 involves understanding how menus are used, and selecting the proper kinds for specific tasks. The principles of menu design are described, and Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 10 the purpose and proper usage of various menu types are detailed. In this step Web site navigation schemes are also discuss ed. • Step 5: Select the Proper Kinds of Windows. Graphical screen design will consist of a series of windows. Step 5 involves understanding how windows are used and selecting the proper kinds for the tasks. The elements of windows are described, and the p urpose and proper usage of various types of windows are detailed. • Step 6: Select the Proper Device - Based Controls. In addition to the keyboard, a system or Web site might offer the user a mouse, trackball, joystick, graphic tablet, touch screen, light p en, or some other similar device. Step 6 consists of identifying the characteristics and capabilities of these various control mechanisms and providing the proper ones for users and their tasks. • Step 7: Choose the Proper Screen - Based Controls. The desig ner is presented an array of screen - based controls to choose from. Selecting the right one for the user and the task is often difficult. But, as with device - based controls, making the right choice is critical to system success. A proper fit between user an d control will lead to fast, accurate performance. A poor fit will result in lower productivity, more errors, and often user dissatisfaction. Step 7 consists of identifying the characteris tics and capabilities of these various screen - based controls and gu idelines for providing the proper ones for users and their tasks. • Step 8: Write Clear Text and Messages. Creating text and messages in a form the user wants and understands is absolutely necessary for system acceptance and success. Rules for writing tex t and messages for systems and Web sites are presented. • Step 9: Provide Effective Feedback and Guidance and Assistance. Effective feedback and guidance and assistance are also necessary elements of good design. This step presents the guidelines for pres enting to the user feedback concerning the system and its processing status. It also describes the system response times necessary to meet user needs. Step 9 also describes the kinds of guidance and assistance that should be included in a system, and prese nts important design guidelines for the various kinds. • Step 10: Provide Effective Internationalization and Accessibility. People from different cultures, and people who speak different languages may use graphical systems and Web sites. Guidelines for ac commodating different cultures and languages in a design are presented. People with disabilities may also be users. Design considerations for these kinds of users are also described. • Step 11: Create Meaningful Graphics, Icons, and Images. Graphics, incl uding icons and images, are an integral part of design. Design guidelines for various types of graphics are presented. Icons are also described, including a discussion of what kinds of icons exist, what influences their usability, and how they should be de signed so they are meaningful and recognizable. • Step 12: Choose the Proper Colors. Color, if used properly, can emphasize the logical organization of a screen, facilitate the discrimination of screen components, accentuate differences, and make displays more interesting. If used improperly, color can be distracting and cause visual fatig ue, impairing a system's usability. Step 12 involves understanding color and how to use it effectively on textual and statistical graphics screens, and in Web sites. Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 11 • Step 13: Organize and Layout Windows and Pages. After determining all the components of a screen or page, the screen or page must be organized and its elements presented clearly and meaningfully. Proper presentation and organization will encourage the quick and accurate comprehension of information and the fastest possible execution of user tasks. Step 13 addresses the rules for laying out all screen elements and controls in the most effective manner possible. • Step 14: Test, Test, and Retest. A host of factors must be considered in design and numerous trade - offs will have been made. Indeed , the design of some parts of the system may be based on skimpy data and simply reflect the most educated guess possible. Also, the implications for some design decisions may not be fully appreciated until the results can be seen. Waiting until after a sys tem has been implemented to uncover any deficiencies and make any design changes can be aggravating, costly, and time - consuming. To minimize these kinds of problems, interfaces and screens must be continually tested and refined as development proceeds. Ste p 14 reviews the kinds of tests that can be performed, and discusses creating, evaluating, and modifying prototypes in an iterative manner. It also reviews final system testing and ongoing evaluations of working systems. This sounds very neat and organized , but in practice things almost never work out that way. In reality, steps will overlap to some extent or may run in parallel. Sometimes, especially with testing, one goes backwards along those steps. It may be tempting to skip steps, but from personal experience, poor designed results in a flawed foundation, and that winds up making for expensive and time - consuming fixes. As the proverb goes, measure twice, cut once. 1.4. Guidelines for Interface Design Process Here are some additional (and practical) gu idelines for creating interesting GUI applications : • Balance : equal weight of screen elements, left and right, top and bottom. • Symmetry : replicate elements left and right of the screen centerline. • Regularity : similar element sizes, shapes, colors, and spacing. • Predictability : be consistent and follow conventional orders or arrangements. • Sequentially : arrange elements to guide the eye through the screen. • Economy : use as few styles, display techniqu es, and colors as possible. • Unity : use similar sizes, shapes, or colors for related information. • Proportion : data or text with aesthetically pleasing proportions. • Simplicity : optimize the number of elements on a screen, within limits of clarity • Groupings : provide functional groupings of associated elements. Eyeball fixation studies also indicate that during the initial scanning of a display in a clockwise direction, people are influenced by the symmetrical balance and weight of the titles , graphics, and text Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 12 of the display. People naturally seeks order and meaning, and they intuitively impose some sort of structure when confronted with uncertainty. The more cluttered or unclear the screen, the more effort required, to figure the software out, and if a user has to work hard at it, they may be daunted or simply prefer clearer alternatives. In other words, if it’s too much work to use your program, they’ll use somebody else’s instead of yours. 1.5. And 10 Commandments... Basically, there are some “suggestions” to create user engagement... Figure 1.3: User Design Commandments Source: https://www.designmantic.com/blog/infographics/the - 10 - commandments - of - ui - design/ 1. Create a story (think about images, avatars, interaction, etc.) 2. Streamline navigation (by friendly interface and clear steps) 3. Make it responsive (how to organize the interfac e) 4. Ensure accessibility (ex: text for images, alternative flows, etc) 5. Form follows function (think about visual elements and actions) 6. Use pleasant color themes (how to attract the user and maintain consistency) Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 13 7. Define font families (simpler is better) 8. Boos t optimized images (minimize size and define styles) 9. Master minimalism (“less is more”) 10. Eliminate errors (start thinking about “standards” and exceptions). 1.6. Software Engineering – Lesson 1 In the end of some chapters , you will see some ideas about SE (Software Engineering) topics, related to professional development (and the relationships with the activities to be done). Let’s start reviwing one idea: Project and Planning Let’s start with the classical picture: Figure 1.4: SE in a tree story ( https://dev.to/jewbixcube/11 - software - engineering - good - practices - hpo ) REQUIREMENTS : In our course, we need to develop a game, so, start c larifying: • What about is this game? • Are there alternative tools (ex: free on - line version)? • What are the functionalities to be implemented? Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 14 • What the interface is supposed to have? You will receive an initial specification about minimal functionalities. But think about how you could develop giving your “personal touch” (ex: colors, interesting ideas, etc). Step 1: REQUIREMENT : About the leadership: • How you understood the project? • Ca n you anticipate the progressive development be done? • If you work in teams, how you are dividing the activities? Step 2 : MANAGEMENT : About the planning : • What are the initial activities to be developed? • If you work in teams, how you are dividing the activi ties? Step 3: DESIGN : Be sure that the analysis is functional : • How this project can implement functionalities? • What are the modes / strategies to be used? Step 4: PROGRAMMING (your principal role): • The implementation compiles? Does it run? Does it finish? • How to develop an “user - friendly” application? Step 5: TESTS ( also your role): • How you can demo that your code is functional? What is the process? • Is there any “happy - day”? How you define the “User - Cases” for your game? • Do you have functional scripts for running? Step 6: BUSINESS : If your application was about to be transformed into a product: • Are the specifications real with the project developed? • How you could improve / evolve it? Step 7: DOCUMENTATION (in Agile, the “code is the document itself”): • Is y our code well written? • Do you have condition to document it correctly? Step 8: INSTALATION (in small projects, scripts can be used): • How to be sure that your code runs “anywhere”? • How to resolve dependences? Step 9: BILLING (in your case, you need to think about “pass”): • Are you computing the time / effort during the development? • Is your solution fair with the final expectation? Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 15 Step 10: SUPPORT (imagine the evolution of your project): • Are you demoing the main functionalities? • Is your code able to evolve and maintain the coherence? Step 11: MARKETING ( think about how you are “demoing” the code) : • Are you demoing the main functionalities? Step 12: EXPECTATIONS : Final result: • Does your solution follow the specification? • Are you ok with the feedback re ceived? ACTIVITY : Try to answer questions from steps 1 to 3 (until before starting programming) . Also REVIEW UML models. Review Questions ( no submission required ) 1. Explain with your words the process of developing a GUI application. 2. Which part of the process you consider most important and why? 3. What is the most important aspect of a GUI application under your opinion? Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 16 Article 2 Basics about Java GUI 2.1. Java Swing 2.1.1. General View Since the beginning, the idea about using a language that can have powerful functionalities, including rich interface, made Java an interesting choice in comparison with different options. However, the complexity here is not only what implement but how to do it, considering that Java is based on JVM ( Virtual Machines ) that should support the proposal. Even though, our focus will be on the most used solutions in the industry, v arious GUI (Graphical User Interface) frameworks were developed and are still available today for creating graphical interfaces in Java Figure 2.0 : Some GUI frameworks for Java (see: https://csveda.com/best - java - gui - frameworks/ ) AWT • Used for several years, t he Abstract Window Toolkit (AWT) was the initial proposal for Java graphical interfaces (still present in Swing), but since it is using operational systems resources (native components), it lacks some features and has performance problems Swing ( SwingX ) • Swing is the most known option for developing new GUI - based Java app lications , with rich UI components (especially in comparison with AWT, its predecessor) SwingX is based on Swing and intends to be still richer, using advanced components and features JavaFX • JavaFX was one of the latest toolkits of Java/Oracle to develop rich applications as well as Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 17 web applications, since it uses some facilities with the use of CSS (Cascate Style Sheets), creating modern applications that are also supported for Mobile apps. S WT ( Standard Widget Toolkit ) • Not having direct relationship with the previous solutions, the Standard Widget Toolkit ( SWT ) is a particular framework developed by IBM for Eclipse IDE and intends to include additional features by using native support for wid gets by JNI (Java Native Interface) This feature (native GUI) can be both an advantage and disadvantage, since requires DLLs. • Example: import org.eclipse.swt.SWT; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Label; public class HelloWorld { public static void main(String[] args) { Display display = new Display(); Shell shell = new Shell(display); Label label = new Label(shell, SWT.CENTER); label.setTe xt( "Hello, World!" ); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } display.dispose(); } } Apache Pivot • Being an open - source framework, aims to develop rich internet applications that can also be applied to desktop applications. It claims to have a cross - platform and support for several JVM environments (including Groovy, or Scala) • Example: import org.apache.pivot.wtk.Application; import org.apache.pivot.wtk.DesktopApplicationContext; import org.apache.pivot.wtk.Display; import org.apache.pivot.wtk.Label; import org.apache.pivot.wtk.Window; public class HelloWorld implements Application { privat e Window window = null ; @Override public void startup (Display display, Map<String, String> properties) throws Exception { window = new Window(); Label label = new Label( "Hello, World!" ); window.setContent(label); window.setTitle( "Hello, World!" ); window.setMaximized( true ); Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 18 window.open(display); } @Override public boolean shutdown ( boolean optional) { if (window != null ) { window.close(); } return false ; } @Override public void suspend () { } @Override public void resume () { } public static void main(String[] args) { DesktopApplicationContext.main(HelloWorld.class, args); } } 2.1.2. Detailing Java Solutions When Java was introduced for the first time, it contained a class library called Abstract Windowing Toolkit (AWT) which provided the programmer with the basic components for GUI programming. • The basic AWT library deals with user interface elements by delegating their creation and behavior to the native windowing system (Windows, Solaris, Linux, Mac, and so on). • Each component in AWT has a "native" peer responsible for handling the user actions. • For that reason, are called " heavyweight compo nents ." The peer - based approach is very effective but has two major problems • First, it depends on the platform, which means that the GUI will look and behave differently on each platform • A nd second, if the platform changes or adds some components new peer s must be provided in the library. The solution to this problem is to create a GUI library , which is not heavily dependent on the underlying platform. Sun created such library for Java 1.2 under the code name Swing • Swing is now part of so - called Java Fou ndation Classes (JFC). The Java Foundation Classes (JFC) are a comprehensive set of GUI components and services which dramatically simplify the development and deployment of commercial - quality desktop and Internet/Intranet applications No need to bundle. Java Foundation classes are core to the Java 2 Platform • The Swing components such as buttons, menus and so on are painted onto blank windows. Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 19 • For that reason, they are called “ lightweight components .” • The only functionality required from the underlying windowing system is to put up a window and to paint on the window. Swing is not a complete replacement for the AWT – it is built on the top of AWT architecture and contains some heavyweight components. I t uses the foundation of AWT for event handling. Of course, Swing based user interface will be always somewhat slower to appear on the user’s screen than the peer - based component used by AWT, but this is not a major concern for application running on a mod ern computer On the other hand, the advantages of Swing are numerous: • Swing provides a very far - reaching set of user interface elements; • Swing has a very few dependencies on the underlying platform, which means that it is less prone platform specific bugs ; • Swing provides consistent user experience across platforms and allows for adjustment to the native platform “ Look and Feel .” Figure 2. 1: Inheritance Hierarchy (arrows indicate inheritance) for AWT and Swing 2.1.3. Components and Containers To build a GUI the programmer needs to perform a few simple tasks: 1. Choose a primary container (window). 2. Choose GUI components and containers which will be part of the interface. Arrange the components inside the containers. 3. Arrange the components an d the containers inside the primary container. 4. Handle the events generated by the user actions such as mouse click or a keystroke. A primary container or a top - level window (that is, a window that is not contained inside another window) is called fram e in Java. • The AWT library has a class, called Frame for this primary container. Algonquin College – JAP: CST8221 – Lecture Notes / Hybrid Materials – Spring/Summer , 2022 20 • The Swing version of this class is called JFrame and it extends the Frame class. • The JFrame is one of the few Swing components which is not painted. • Thus, all its decorations are drawn by the user’s windowing system. This is how a simple frame looks like. Figure 2. 2 : Blank window frame Internally the frame has a very complex structure. It contains a root pane which has four parts. Figure 2. 3 : Layers in Swing • Root pane : The root pane is created automatically when you instantiate JInternalFrame or one of the top - level Swing containers, such as JFrame , JApplet , JDialog , JWindow , and JInternalFrame • Glass pane : Hidden by default . If you make the glass pane visible, then it's like a sheet of glass over all the other parts of the root pane.