Documente Academic
Documente Profesional
Documente Cultură
1. 2. 3. 4. 5. 6.
NAME
ABSTRACT SYSTEM ANALYSIS ABOUT ORGANISATION SRS DOCUMENT DESIGN PRINCIPLES & EXPLANATION DESIGN DOCUMENT 6.1 SYSTEM DESIGN
PAGE NO
7.
8.
9.
Abstract:
Chatting is now-a-days very useful to express our ideas as well as receive others ideas on any topic. Chats reflect the recent trends of the society. Sometimes, it is possible to meet eminent people in chatting and have their advice. Corporate messenger is a graphical chatting application that makes chatting a pleasant experience. It has excellent features that make any user do what ever he wants while chatting. Corporate messenger has two types of users: 1. Admin and 2. Client Admin can do the following activities: 1. User Management: He makes some initial startup tasks while starting the chat server. He can create new users and allow or disconnect the users. Admin can also close the chat session, so that all the users will be disconnected. 2. Administrative Client: Admin can also involve in chatting as a client from his admin console using this option. 3. ShutDown: He can shut down the chat server. 4. Log Charts: He can create log charts which contain information of how chatting has taken place. Client can perform the following tasks: 1. Connect: He can connect him self to chat server by typing his username and password. 2. Chat: He can participate in chatting by entering into a chat room. 3. View this User Info: He can also his own profile and options. 4. Display activity of user: When chatting is done, whether the other user is sending text or images is also displayed on his console.
5. Room management: He can create his own chat rooms based on a subject and invite others to enter that room. He can also save the chat data separately. 6. Instant messages: It is possible to send instant messages and popups to other users who are in chatting. 7. Canvas management: Chat Space Instant Messanger is a graphical chatting application. It enables the clients to draw shapes and apply colors and save them. Client can also show or hide the canvas depending on his interest. 8. Copy & Paste: He can also perform operations like copying earlier text into chat text. It is also possible to copy pictures and save them in a file. 9. Chat Room control: He can manage the connection settings and control the chat room settings. 10. Play sound when paged. 11. Manual: In case any help needed, the client can go through the in-built manual available.
System Analysis
Existing System:
The existing communication system is not built as a software application. Everybody communicates with others physically or through the mails. To make this complex communication job simple and allows the users to participate in live communication and save unproductive time it is to be built as a software application. Each and every user or employee of an organization has to register, get into his inbox and check for his mail which doesnt provide live communication resemblance to the user. This facility does not categorize the users depending on their interests. This type of communication channel fails in providing effective user friendly communication between the users. If this channel grows up to some extent then it will be harder to place some restrictions on the users. As a result, ineffective communication wastes the user time.
Proposed System:
The first step of analysis process involves the identification of need. The success of a system depends largely on how accurately a problem is defined, thoroughly investigated and satisfying the customer needs by providing user friendly environment This system has been developed in order to overcome the difficulties encountered while using the mailing system for communication between the users. Providing user friendly communication channel, live communication facility, categorizing the users, logging the communication transaction, sending public & private messages, sending instant & offline messages, graphical communication are motivating factors for the development of this system.
Panel (invite, ban and allow) details and chatroom management details. It also helps the administrator to monitor the chatroom by generating different kinds of reports like users currently available in the chatroom, banned list of users and allows the users to view the offline messages individually. Lot of effort was put to make it user friendly. Optimum utilization of system is possible. All basic functionalities are provided. Reduces the user manual communication work. The wastage of time is reduced. It also helps in providing instant and offline communication. More flexible, it means we can continue to use the same system even the no of users up to maximum level.
Feasibility Steady
Feasibility steady is an important phase in the software development process. It enables the developer to have an assessment of the product being developed. It refers to the feasibility study of the product in terms of out comes of the product, operational use and technical support required for implementing it. Feasibility study should be performed on the basis of various criteria and parameters. The various feasibility studies are: Economic Feasibility Operational Feasibility Technical Feasibility
Economic Feasibility:
It refers to the benefits or outcomes we are deriving from the product as compared to the total cost we are spending for developing the product. If the benefits are more or less the same as the older system, then it is not feasible to develop the product. In this product if we have developed this application then the amount of time spent in preparing
the schedules, sending it different branches and monitor the work will be reduced which indirectly increases the production for the company.
Operational Feasibility:
It refers to the feasibility of the product to be operational. Some products may work very well at design and implementation but may fail in the real time environment. It includes the study of additional human resource required and their technical expertise. This application will also work in any environment with out any problems since we are implementing this project in java language.
Technical Feasibility:
It refers to whether the software that is available in the market fully supports the present application. It studies the pros and cons of using particular software for the development and its feasibility. It also studies the additional training needed to be given to the people to make the application work. For this project we need not recruit any additional staff to make use of this application. If we train our staff for one hour then it will be enough to work with application. Since this application uses the softwares which are already used by the company so that the company need not purchase new software to run this project.
1. Introduction The purpose of this document is to describe all external and internal requirements of the Corporate messenger. It also describes the interfaces for the system. It is
Purpose:
a.
b.
c.
d.
In user management module, when ever a new user wants to join in this chatting then the administrator will create this user and adds his information to the system. He has the right to delete the user at any point of time. Admin can disconnect a user or disconnect all users from this application. In chatroom management module also needs to interact with the system whenever creating/updating/entering a chatroom. This allows the user to be segregated as different groups depending on their interests. In chatting module, user needs system interaction at the time of chatting with others through public communication or private communication channel In messages module, the users send instant messages which will appeared as a popup at the targeted user system. if the targeted user is not available it also us to store the offline messages. Preferences & Editing Options module, system needs user interaction when the user wants any editing options like copy, paste etc. It also allows the administrator to change the preferences of this application. One major module called Canvas management module using which can participate in graphical chatting. Using the options available in this the user can also send the pictures and save the received pictures as files in our system.
e.
f.
1.1
This document describes the requirements of the system. It is meant for use by the developers, and will also be the basis for validating the final system. Any changes made to the requirements in the future will have to go through a formal change approval process. The developer is responsible for asking for clarifications. When necessary and will not make any alterations without the permission of client.
Scope:
This project work intends to facilitate the effective communication for the users. Up to now they followed the mailing system in their organization. When the community grown and came to know that the most of their resources wasting by put on sending the mails, receiving it and viewing it which doesnt live communication. By this user asked to enter all the details whatever he wants in the future and can get them in a proper format and required results whenever he wants easily just by few clicks only. This system is developed in such a way that any one can easily get the knowledge of how to use the system. 1.2 Definition: we can treat this as a product as well as application, means for a specific purpose or to automate a set of specific transaction. Here our system provides different types of effective user friendly communication channels. We consider only the requirement given by the client to develop. Reference: Not Applicable. Developers Responsibilities overview: The points that mentioned in system requirements specification are
1. An introductory nature describing mainly the
1.3 1.4
Purpose of the system requirements specifications document. Outlining the scope of the envisaged application.
2. Describes the iterations of the system with its environment without
going into the internals of the system. Also describes the constraints imposed on the system. Thus it is out side the envisaged application. The assumptions made are also listed. It is supported by the UML Diagrams
3. It also describes the internal behavior of the system in response to
the inputs and while generating the outputs. This document is also supported with detailed level UML diagrams, list of inputs, process explanation and list of output.
User characteristics:
In our project main user is an administrator. He must have the knowledge of how to configure the servers, setting the parameters, starting the servers, monitoring the application and taking the necessary actions. Another user is the normal who can join in the room and participating in the chatting.
2.2
General constraints:
The system should run on Pentium, under windowsNT/2000 professional or server or forward versions of Microsoft operating systems with minimum 256 MB RAM for better performance. Both the server and client will run on platform. 2.3
3. Function Requirements
Functional requirements specify which outputs should be produced from the given inputs. They describe the relationship between the input and output of the system, for each functional requirement a detailed description of all data inputs and their source and the range of valid inputs must be specified.
All the operations to be performed on the input data to obtain the output should be specified. 3.1
Inputs:
In our system we have different modules like User Management module, Chatroom management module, Chatting module, messages module, Canvas management module, preferences and editing options module.
3.2
Outputs:
1.
User Management Module: It allows the administrator to view the list of users or information corresponding to a user and banned list of users. It provides a facility to log the user chatting transaction in to log files.
2.
Chatroom management module: It generates the report which contains the list of chatrooms.
3.
4.2
4.3
5. Performance Requirements
All the requirements relating to the performance characteristics of the system must be clearly specified. There are two types of performance requirements static and dynamic. Static Requirements are those that do not impose constraint on the execution characteristics of the system. These include requirements like the number of terminals to be supported, and number simultaneous users to be supported, number of files, and their sizes that the system has to process. These are also called capacity of the system. Dynamic requirements specify constraints on execution behaviour of the system. These typically include response time and throughput constraints on the system. The processing speed, respective resource consumption throughput and efficiency measure performance. For achieving good performance few requirements like reducing code, less use of controls, minimum involvement of repeated data etc., are to be followed. Each real-time system, software what provides required function but does not conform to performance of software requirements is acceptable. These requirements are used to test run time performance of software with the context of an integrated system.
6. Design constraints
6.1
Software constraints :
Operating System Forms & Reports Other Softwares Windows2000 Server/ XP : JFC Swing & AWT : JDK1.4
:
6.2
Hardware Constraints:
Pentium Processor RAM Hard Disk CD/ROM Drive VDU Key Board
:
: : : : :
7. Acceptance Criteria
Before accepting the system, the developer must demonstrate that the system works on the details of the user information and chatroom. The developer will have to show through test cases that all conditions are satisfied.
When partitioning is high, then also arises a problem due to the cost of partitioning. In this situation to know the judgement about when to stop partitioning. In design, the most important quality criteria are simplicity and understandability. In this each the part is easily related to the application and that each piece can be modified separately. Proper partitioning will make the system to maintain by making the designer to understand problem partitioning also aids design verification. Abstraction is essential for problem partitioning and is used for existing components as well as components that are being designed, abstracting of existing component plays an important role in the maintenance phase in design process of the system. In the functional abstraction, the main modules to taking the details and computing for further actions. In data abstraction it provides some services. The system is a collection of modules means components. The highest-level component corresponds to the total system. For design this system, first following the top-down approach to divide the problem in modules. In top-down design methods often result in some form of stepwise refinement after divide the main modules, the bottom-up approach is allowed to designing the most basic or primitive components to higher-level components. The bottom-up method operations starting from very bottom. In this system, the system is main module, because it consists of discrete components such that each component supports a well-defined abstraction and if a change to the component has minimal impact on other components. The modules are highly coupled and coupling is reduced in the system. Because the relationships among elements in different modules is minimized.
Modules:
User Management module: This module contains add/delete the user in this
application for which we need to give user information as input. It also takes care of connect/disconnecting the users from the application for which you need to select the user and click on necessary action. It helps the administrator to manage the chatroom
control panel for inviting/banning or allowing the users. It also allows us to page the users and logging the user chatting transaction. Chat Room Management module: This module also used as the same like user management module. But in our system we treat this entity is different from user entity. It allows the users to create/update/view or joins in the room. Chatting Module: In this module we take the details like public or private messages and text you want to send finally send it to the appropriate destinations Messages Module: In this the user can send instant messages to a user, save offline messages for a user, read saved messages. Canvas Management Module: it provides a white board drawing facility using which the user can draw free hand, do circles, squares, lines, font text, or paste image files to the canvas.
Design Objectives
These are some of the currently implemented features:
This creates a good software user interface often finds its genesis in the user interfaces present in the physical world. Consider for a moment a simple button like one of the keys on the keyboard in front of you. With such a button there is a clean separation between the parts that compose the button's mechanism and the parts that compose its faade. The building block called a keyboard key is actually composed of two pieces. Once piece gives its button-like behavior. The other piece is responsible for its appearance. This construction turns out to be a powerful design feature. It encourages reuse rather than redesign. Because your keyboard's keys were designed that way, it's possible to reuse the button mechanism design, and replace the key tops to create a new key rather than designing each key from scratch substantial savings in design effort and time. Not surprisingly, similar benefits occur when this technique is applied to software development. One commonly used implementation of this technique in software is the design pattern called Model/View/Controller (MVC).
That's all well and good, but you're probably wondering how this relates to the Swing user interface components in the Java Foundation Classes (JFC). Well, I'll tell you. While the MVC design pattern is typically used for constructing entire user interfaces, the designers of the JFC used it as the basis for each individual Swing user interface component. Each user interface component (whether a table, button, or scrollbar) has a model, a view, and a controller. Furthermore, the model, view, and controller pieces can change, even while the component is in use. The result is a user interface toolkit of almost unmatched flexibility. Let me show you how it works.
Figure 1. MVC design pattern The model is the piece that represents the state and low-level behavior of the component. It manages the state and conducts all transformations on that state. The model has no specific knowledge of either its controllers or its views. The system itself maintains links
between model and views and notifies the views when the model changes state. The view is the piece that manages the visual display of the state represented by the model. A model can have more than one view, but that is typically not the case in the Swing set. The controller is the piece that manages user interaction with the model. It provides the mechanism by which changes are made to the state of the model. Using the keyboard key example, the model corresponds to the key's mechanism, and the view and controller correspond to the key's faade. The following figure illustrates how to break a JFC user interface component into a model, view, and controller. Note that the view and controller are combined into one piece, a common adaptation of the basic MVC pattern. They form the user interface for the component.
Design Document
1.System design
System design is the process of applying various techniques and principles for the purpose of definition a system in sufficient detail to permit its physical realization. Software design is the kernel of the software engineering process. Once the software requirements have been analyzed and specified, the design is the first activity. The flow of information during this process is as follows. Information domain details
Function specification
Desig n
Behavioral specification
Code
Program
Test
The Process
Software design is the process through which requirements are translated into a representation of software.
representation for software. In the present project report only preliminary design is given more emphasis.
Design Fundamentals
System design is the bridge between system & requirements analysis and system implementation. Some of the essential fundamental concepts involved in the design of as applications are Abstraction Modularity Verification Abstraction is used to construct solutions to problems without having to take account of the intricate details of the various component sub-programs. Abstraction allows system designer to make step-wise refinements by which attach stage of the design unnecessary details annunciate with representation or implementation may be hidden from the surrounding environment. Modularity is concerned with decomposing of main module into well-defined, manageable units with well-defined interfaces among the units. This enhances design clarity, which in turn eases implementation, debugging, testing, and documentation maintaining of the software product. Modularity viewed in this senses vital tool in the construction of large software projects.
Verification is fundamental concept in software design. A design is verification. It can be demonstrated that the design will result in an implementation, which satisfied the customers requirements. Some of the important factors of quality that are to be considered in the design of application are: The software should behave strictly according to the original specification of satisfying customers requirements and should function smoothly under normal and possible abnormal conditions. This product is highly reliable, can handle any number of mails to filter.
The design of the system must be such a way that any new additions to the information functional and behavioral domain may be done easily and should be adapted to new specifications. We provided this extensibility to this product. you can add any number of filters to your product in the future. System design is the process of developing specification for the candidate system that meets the criteria established during the phase of system analysis. Major step in the design is the preparation of input forms and design of output reports in a form acceptable to the user. These steps in turn lead to a successful implementation of the system.
A button in detail To better understand how the MVC pattern relates to Swing user interface components, let's delve deeper in the Swing set. Just as I did last month, I'll use the ubiquitous button component as a reference.We'll begin with the model. The model The behavior of the model in the button illustration above is captured by the ButtonModel interface. A button model instance encapsulates the internal state of a single button and defines how the button behaves. Its methods can be grouped into four categories - those that:
Query internal state Manipulate internal state Add and remove event listeners Fire events
Other user interface components have their own, component-specific models. They all, however, provide the same groups of methods.
Other user interface components have their own, component-specific view/controllers. They all, however, provide the same groups of methods. The scaffolding Programmers do not typically work with model and view/controller classes directly. In fact, to the casual observer, their presence is veiled. They hide behind an ordinary component class -- a subclass of java.awt.Component. The component class acts as the glue, or scaffolding, that holds the MVC triad together. Many of the methods present on thecomponent class (paint (), for example) are nothing more than wrappers that pass along the method invocation to either the model or the view/controller. Because the component classes are subclasses of class Component, a programmer can freely mix Swing components with regular AWT components. However, because the Swing set contains components that functionally mimic the regular AWT components, mixing the two is usually not necessary.
A concrete example
Now that we understand which Java classes correspond to which parts of the MVC pattern, we're ready to open the box and peek inside. What follows is a scaled-down tour
of a set of model classes designed and built according to the MVC principles outlined above. Because the JFC library is so complex, be right). Let's take a look at all the major players. I've narrowed the scope of my tour to include only one user interface component (if you guessed it to be the Button class, you'd
Input Design
Input design is the process of converting user-originated information to computerbased format. The goal of designing input data is to make data entry as easier and error free as possible. An input format should be easy to understand. In this application inputs are nothing but the information about different entities. Every entity has different fields i.e. user management has some properties like username, password and so on. By taking these inputs from the user, we do the process to decide whether to save the messages, send the content to the destination or placing any restrictions. The output design relays on input, which is used to the output. Hence input design needs some special attention.
Output Design
Output reflects image of the purpose. The output design involves designing forms layout, making lists, making well designed reports etc., and reports are main outputs of the proposed system. Here the outputs are: list of users, banned list of users, offline messages for a user and current active users.
Chat Server checkPasswd( ) findChatRoom () createNewUse r() isUserAllowed() readMessages() Chat user Dialog fillUserList() create User() deleteUsers()
Settings
Chat Server window updateStats()
setValues()
userinRoom() updateLists()
Chat clients
classDiagram(server)
Chat Client
Chat command
Open()
setCommand() getCommand()
Message Prepare()
Chat Applet
Chat Canvas
classDiagram(client)
ActivityDiagram
Chat room server window Lookups
Chat server
User mgt:
Admin client
Disconnect user
Disconnect all
Invite
Ban
Allow
Add client
Disconnect user()
Disconnect all()
SequenceDiagram
Chat client
connect
Chat rooms:
create
update
messaging
Drawing canvas
Connect() Select()
Add Edit
send
send
send
draw
User Management
Admin Client
Disconnect user
Disconnect all
Log chats
Connect
Chat rooms
messaging
Client
Use canvas
Public msg
Private msg
shared network access to data but the comparison dens there! The file server simply provides a remote disk drive that can be accessed by LAN applications on a file by file basis. The client server offers full relational database services such as SQL-Access, Record modifying, Insert, Delete with full relational integrity backup/ restore performance for high volume of transactions, etc. the client server middleware provides a flexible interface between client and server, who does what, when and to whom.
The browser specific components are designed by using the HTML standards, and the dynamism of the designed by concentrating on the constructs of the Java Server Pages.
ABOUT JAVA
Initially the language was called as oak but it was renamed as Java in 1995. The primary motivation of this language was the need for a platform-independent (i.e., architecture neutral) language that could be used to create software to be embedded in various consumer electronic devices. Java is a programmers language. Java is cohesive and consistent. Except for those constraints imposed by the Internet environment, Java gives the programmer, full control. Finally, Java is to Internet programming where C was to system programming.
addresses those concerns and by doing so, has opened the door to an exciting new form of program called the Applet.
FEATURES OF JAVA
Security
Every time you that you download a normal program, you are risking a viral infection. Prior to Java, most users did not download executable programs frequently, and those who did scanned them for viruses prior to execution. Most users still worried about the possibility of infecting their systems with a virus. In addition, another type of malicious program exists that must be guarded against. This type of program can gather private information, such as credit card numbers, bank account balances, and passwords. Java answers both these concerns by providing a application and your computer. When you use a Java-compatible Web browser, you can safely download Java applets without fear of virus infection or malicious intent. firewall between a network
Portability
For programs to be dynamically downloaded to all the various types of platforms connected to the Internet, some means of generating portable executable code is needed .As you will see, the same mechanism that helps ensure security also helps create portability. Indeed, Javas solution to these two problems is both elegant and efficient.
end of the compilation process to make sure that is all accurate and correct. So byte code verification is integral to the compiling and executing of Java code. Overall Description
J ava Source Java byte code av aV M J
Java
.Class
Picture showing the development process of JAVA Program Java programming uses to produce byte codes and executes them. The first box indicates that the Java source code is located in a. Java file that is processed with a Java compiler called javac. The Java compiler produces a file called a. class file, which contains the byte code. The .Class file is then loaded across the network or loaded locally on your machine into the execution environment is the Java virtual machine, which interprets and executes the byte code.
Java Architecture
Java architecture provides a portable, robust, high performing environment for development. Java provides portability by compiling the byte codes for the Java Virtual Machine, which is then interpreted on each platform by the run-time environment. Java is a dynamic system, able to load code when needed from a machine in the same room or across the planet.
Compilation of code
When you compile the code, the Java compiler creates machine code (called byte code) for a hypothetical machine called Java Virtual Machine (JVM). The JVM is supposed to execute the byte code. The JVM is created for overcoming the issue of portability. The code is written and compiled for one machine and interpreted on all machines. This machine is called Java Virtual Machine.
Source Code .. .. ..
C Compil er
Java Byte code (Platform indepen dent) Java Interpreter (Macintosh) Java Interpreter (Sparc)
Macintosh Compiler
SPARC
Com piler
During run-time the Java interpreter tricks the byte code file into thinking that it is running on a Java Virtual Machine. In reality this could be a Intel Pentium Windows 95 or Sun SPARC station running Solaris or Apple Macintosh running system and all could receive code from any computer through Internet and run the Applets. Simple Java was designed to be easy for the Professional programmer to learn and to use effectively. If you are an experienced C++ programmer, learning Java will be even easier. Because Java inherits the C/C++ syntax and many of the object oriented features of C++. Most of the confusing concepts from C++ are either left out of Java or implemented in a cleaner, more approachable manner. In Java there are a small number of clearly defined ways to accomplish a given task.
Object-Oriented
Java was not designed to be source-code compatible with any other language. This allowed the Java team the freedom to design with a blank slate. One outcome of this was
a clean usable, pragmatic approach to objects. The object model in Java is simple and easy to extend, while simple types, such as integers, are kept as high-performance nonobjects.
Robust
The multi-platform environment of the Web places extraordinary demands on a program, because the program must execute reliably in a variety of systems. The ability to create robust programs was given a high priority in the design of Java. Java is strictly typed language; it checks your code at compile time and run time.Java virtually eliminates the problems of memory management and deallocation, which is completely automatic. In a well-written Java program, all run time errors can and should be managed by your program.
JFC Overview
Sun Microsystems is leveraging the technology of Netscape Communications, IBM, and Lighthouse Design (now owned by Sun) to create a set of Graphical User Interface (GUI) classes that integrate with JDK 1.1.5+, are standard with the Java 2 platform and provide a more polished look and feel than the standard AWT component set. The collection of APIs coming out of this effort, called the Java Foundation Classes (JFC), allows developers to build full-featured enterprise-ready applications. JFC is composed of five APIs: AWT, Java 2D, Accessibility, Drag and Drop, and Swing. The AWT components refer to the AWT as it exists in JDK versions 1.1.2 and later. Java 2D is a graphics API based on technology licensed from IBM/Taligent. It is currently available with the Java 2 Platform (and not usable with JDK 1.1). The Accessibility API provides assistive technologies, like screen magnifiers, for use with the various pieces of JFC. Drag and Drop support is part of the next JavaBean generation, "Glasgow," and is also available with the Java 2 platform. Swing includes a component set that is targeted at forms-based applications. Loosely based on Netscape's acclaimed Internet Foundation Classes (IFC), the Swing components have had the most immediate impact on Java development. They provide a set of well-groomed widgets and a framework to specify how GUIs are visually presented, independent of platform. At the time this was written, the Swing release is at 1.1 (FCS). IFC, AWT, and Swing: Sorting it all out
Though the Swing widgets were based heavily on IFC, the two APIs bear little resemblance to one another from the perspective of a developer. The look and feel of
some Swing widgets and their rendering is primarily what descended from IFC, although you may notice some other commonalties. The AWT 1.1 widgets and event model are still present for the Swing widgets. However, the 1.0 event model does not work with Swing widgets. The Swing widgets simply extend AWT by adding a new set of components, the JComponents, and a group of related support classes. As with AWT, Swing components are all JavaBeans and participate in the JavaBeans event model. A subset of Swing widgets is analogous to the basic AWT widgets. In some cases, the Swing versions are simply lightweight components, rather than peer-based components. The lightweight component architecture was introduced in AWT 1.1. It allows components to exist without native operating system widgets. Instead, they participate in the Model/View/Controller (MVC) architecture, which will be described in Part II of this course. Swing also contains some new widgets such as trees, tabbed panes, and splitter panes that will greatly improve the look and functionality of GUIs. Swing Package Overview Swing can expand and simplify your development of cross-platform applications. The Swing collection consists of seventeen packages, each of which has its own distinct purpose. As you'll learn in this short course, these packages make it relatively easy for you to put together a variety of applications that have a high degree of sophistication and user friendliness.
javax.swing
The high level swing package primarily consists of components, adapters, default component models, and interfaces for all the delegates and models. javax.swing.border The border package declares the Border interface and classes, which define specific border rendering styles.
javax.swing.colorchooser
The color chooser package contains support classes for the color chooser component. javax.swing.event The event package is for the Swing-specific event types and listeners. In addition to the java.awt.event types, Swing components can generate their own event types. javax.swing.filechooser The file chooser package contains support classes for the file chooser component. javax.swing.plaf.* The pluggable look-and-feel (PLAF) packages contain the User Interface (UI) classes (delegates) which implement the different look-and-feel aspects for Swing components. There are also PLAF packages under the javax.swing.plaf hierarchy. javax.swing.table The table package contains the support interfaces and classes the Swing table component. javax.swing.text The text package contains the support classes for the Swing document framework.
javax.swing.text.html.* The text.html package contains the support classes for an HTML version 3.2 renderer and parser. javax.swing.text.rtf The text.rtf package contains the support classes for a basic Rich Text Format (RTF) renderer. javax.swing.tree The tree package contains the interfaces and classes which support the Swing tree component. javax.swing.undo The undo package provides the support classes for implementing undo/redo capabilities in a GUI.
javax.accessibility The JFC Accessibility package is included with the Swing classes. However, its usage is not discussed here. Widgets, Widgets, Widgets This section describes how to use the various Swing widgets. The Swing component hierarchy is shown in two parts for comparison with AWT. Part 1 of the component hierarchy is similar to that of AWT. However, there are over twice as many components in Swing as in AWT. Part 2 shows the expanded Swing component set. This group of components appeals most to developers, as it provides a much richer set of widgets to use.
COMPONENT HIERARCHY: PART 2--NEW AND EXPANDED COMPONENTS JPanel The first widget to discuss is JPanel. It is a lightweight Panel object offering built-in support for double buffering. When buffering is enabled, through the constructor, all the drawing operations of components within the panel will be drawn to an off-screen drawing area prior to being drawn to the screen. The JPanel class is used in most of the examples in this section. Icons The second component, Icon, isn't really a component at all. However, you can use it with almost all Swing components.
An Icon is used to describe fixed-size pictures, or glyphs. Typically, you embed icons in a JButton or other JComponent. Objects that can act as icons implement the Icon interface, shown below. It contains a paintIcon() method that specifies a drawing origin. You render the picture specified in the paintIcon () method in a rectangle whose size cannot exceed a rectangle with an origin at (x, y), a width of getIconWidth(), and a height of getIconHeight(). The Component parameter to paintIcon() is not usually used, unless you need to specify additional information, such as a font or color. public interface Icon { void paintIcon( Component c, Graphics g, int x, int y); int getIconWidth(); int getIconHeight(); }
The ImageIcon class is an implementation of Icon that creates an Icon from an Image. Icon tinyPicture = new ImageIcon ("TinyPicture.gif"); Alternatively, the ImageIcon constructor can take an Image or URL object or byte array as its parameter, with an optional String description parameter. One nice thing about ImageIcon is it checks a cache before retrieving the image file. Swing uses ImageIcon rather than Image for two reasons:
1.
An Image loads asynchronously, creating the need to monitor An Image is not serializable.
In addition to using ImageIcon, you can implement the interface yourself to create your own icons: public class RedOval implements Icon { public void paintIcon (Component c, Graphics g, int x, int y) { g.setColor(Color.red); g.drawOval (x, y, getIconWidth(), getIconHeight()); } public int getIconWidth() { return 10; } public int getIconHeight() { return 10; } }
JLabel A JLabel is a single line label similar to java.awt.Label. Additional functionality that a JLabel has is the ability to:
3. 4.
Add an Icon Set the vertical and horizontal position of text relative to the Set the relative position of contents within component
Icon 5.
public class LabelPanel extends JPanel { public LabelPanel() { // Create and add a JLabel
JLabel plainLabel = new JLabel("Plain Small Label"); add(plainLabel); // Create a 2nd JLabel JLabel fancyLabel = new JLabel("Fancy Big Label"); // Instantiate a Font object to use for the label Font fancyFont = new Font("Serif", Font.BOLD | Font.ITALIC, 32); // Associate the font with the label fancyLabel.setFont(fancyFont); // Create an Icon Icon tigerIcon = new ImageIcon("SmallTiger.gif"); // Place the Icon in the label fancyLabel.setIcon(tigerIcon); // Align the text to the right of the Icon fancyLabel.setHorizontalAlignment(JLabel.RIGHT); // Add to panel add(fancyLabel); } } JButton A JButton can be It instantiated behaves and an used AWT in a GUI just like a
java.awt.Button.
like
1.1
Button,
notifying
Also, the JButton has support for an embedded Icon, specified in the constructor, or via the setIcon() method. This creates an image button; here, with the label Tiger:
public class ButtonPanel extends JPanel { public ButtonPanel() { Icon tigerIcon = new ImageIcon("SmallTiger.gif"); JButton myButton = new JButton("Tiger", tigerIcon); add(myButton); } } Magercises
6. 7. 8.
Installing Swing and SwingSet Demonstration Creating Your First JFC Application Creating Buttons With Icons
AbstractButton While the AbstractButton isn't a class you use directly, several of the more common JComponent classes inherit much of their shared behavior from this object. For instance, the icon usage methods getIcon() and setIcon() come from AbstractButton. (The methods are also available elsewhere.) Some of the other common features are listed below:
setMnemonic() - Add a keyboard accelerator to a text label, use doClick() - Programmatically, select the button setDisabledIcon(), setDisabledSelectedIcon(), setPressedIcon(), setRolloverSelectedIcon(), setSelectedIcon() -
setRolloverIcon(), setIcon())
o
Change the displayed Icon, based on the button state (in addition to setVerticalAlignment(), setHorizontalAlignemnt() Anchors
text in different areas around icon. Both setXXXAlignment() and setYYYTextPosition() rely on the SwingConstants interface for the area placement settings. Note: The upcoming Swing 1.1.1 release includes the ability to specify label text in HTML by preceding the content with <html>. This will allow you to have multi-line button labels without having to customize the user interface. JCheckBox A JCheckBox is similar to an AWT Checkbox that is not in a
CheckboxGroup. Although Swing provides a default graphic to signify JCheckBox selection, you also can specify your own Icon objects for both the checked and unchecked state.
public class CheckboxPanel extends JPanel { Icon unchecked = new ToggleIcon (false); Icon checked = new ToggleIcon (true);
public CheckboxPanel() { // Set the layout for the JPanel setLayout(new GridLayout(2, 1)); // Create checkbox with its state // initialized to true JCheckBox cb1 = new JCheckBox("Choose Me", true); cb1.setIcon(unchecked); cb1.setSelectedIcon(checked); // Create checkbox with its state // initialized to false JCheckBox cb2 = new JCheckBox( "No Choose Me", false); cb2.setIcon(unchecked); cb2.setSelectedIcon(checked); add(cb1); add(cb2); } class ToggleIcon implements Icon { boolean state; public ToggleIcon (boolean s) { state = s; } public void paintIcon (Component c, Graphics g, int x, int y) { int width = getIconWidth(); int height = getIconHeight(); g.setColor (Color.black); if (state) g.fillRect (x, y, width, height); else
g.drawRect (x, y, width, height); } public int getIconWidth() { return 10; } public int getIconHeight() { return 10; } } } JRadioButton In AWT, radio buttons are checkboxes that belong to the same CheckboxGroup; which ensures that only one checkbox is selected at a time. Swing has a separate widget called a JRadioButton. Each JRadioButton is added to a ButtonGroup so the group behaves as a set of radio buttons. Like CheckboxGroup, ButtonGroup is a functional object that has no visual representation.
public class RadioButtonPanel extends JPanel { public RadioButtonPanel() { // Set the layout to a GridLayout setLayout(new GridLayout(4,1));
// Declare a radio button JRadioButton radioButton; // Instantiate a ButtonGroup for functional // association among radio buttons ButtonGroup rbg = new ButtonGroup(); // Create a label for the group JLabel label = new JLabel("Annual Salary: "); label.setFont(new Font( "SansSerif", Font.BOLD, 14)); add(label); // Add a new radio button to the pane radioButton = new JRadioButton("$45,000"); add (radioButton); // set key accelerator radioButton.setMnemonic (KeyEvent.VK_4); // Add the button to the ButtonGroup rbg.add (radioButton); // Set this radio button to be the default radioButton.setSelected(true); // Set up two more radio buttons radioButton = new JRadioButton("$60,000"); radioButton.setMnemonic (KeyEvent.VK_6); add (radioButton); rbg.add (radioButton);
Technically speaking, you can add JCheckBox or JToggleButton (described next) components to a CheckboxGroup. At most, one will be selected while in the group. JToggleButton The JToggleButton class is the parent to both JCheckBox and
JRadioButton. It doesn't have an AWT equivalent. The JToggleButton works like a Button that stays pressed in when toggled on. When a JToggleButton is toggled off, you cannot tell it from a regular Button or JButton class.
public class ToggleButtonPanel extends JPanel { public ToggleButtonPanel() { // Set the layout to a GridLayout setLayout(new GridLayout(4,1, 10, 10)); add (new JToggleButton ("Fe")); add (new JToggleButton ("Fi"));
JTextComponents JTextComponent is a generalized text class that contains all the features you would expect from a simple editor. Some of its methods include: copy() cut() paste() getSelectedText() setSelectionStart() setSelectionEnd() selectAll() replaceSelection() getText() setText() setEditable() setCaretPosition()
Although you won't instantiate a JTextComponent object directly, you will often use these methods, many of which are not available in AWT text widgets. JTextComponent objects in Swing can be placed in a panel in a fashion nearly identical to AWT text widgets.
There are three basic subclasses of JTextComponent: JTextField, JTextArea, and JEditorPane. JPasswordField and JTextPane are sub-subclasses that are also of interest. If you want your users to be able to see content that exceeds the screen display area, you must place the component inside of a JScrollPane to support scrolling to the extra content. JTextField & JTextArea Other than having to add a JTextArea to a JScrollPane for scrolling, JTextField and JTextArea behave very similarly to their AWT counterparts: java.awt.TextField and java.awt.TextArea:
// Instantiate a new TextField JTextField tf = new JTextField(); // Instantiate a new TextArea JTextArea ta = new JTextArea(); // Initialize the text of each tf.setText("TextField"); ta.setText("JTextArea\n Allows Multiple Lines"); add(tf); add(new JScrollPane(ta));
The
JTextField
also
supports
setting
of
text
justification
with
setHorizontalAlignment(). The three available settings are LEFT, CENTER, and RIGHT, where LEFT is the default. JTextPane JTextPane is a full-featured text editor that supports formatted text, word wrap, and image display. It uses a linked list of objects that implement the Style interface to specify formatting and supplies some convenience methods for formatting text. A more detailed discussion of JTextPane usage, and the javax.swing.text package, is included in Part II of this course.
JTextPane tp = new JTextPane(); MutableAttributeSet attr = new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, "Serif"); StyleConstants.setFontSize(attr, 18); StyleConstants.setBold(attr, true); tp.setCharacterAttributes(attr, false); add(new JScrollPane(tp));
public class TextPanel extends JPanel { public TextPanel() { // Set the layout to a BorderLayout setLayout(new BorderLayout()); // Create the three basic text components JTextField textField = new JTextField(); JTextArea textArea = new JTextArea(); JTextPane textPane = new JTextPane(); //Set the textpane's font properties MutableAttributeSet attr =
new SimpleAttributeSet(); StyleConstants.setFontFamily(attr, "Serif"); StyleConstants.setFontSize(attr, 18); StyleConstants.setBold(attr, true); textPane.setCharacterAttributes(attr, false); add(textField, BorderLayout.NORTH); add(new JScrollPane(textArea), BorderLayout.CENTER); add(new JScrollPane(textPane), BorderLayout.SOUTH); } } JPasswordField The JPasswordField is a JTextField that refuses to display its contents openly. By default, the mask character is the asterisk ('*'). However, you can change this with the setEchoChar() method. Unlike java.awt.TextField, an echo character of (char)0 does not unset the mask.
class PasswordPanel extends JPanel { PasswordPanel() { JPasswordField pass1 = new JPasswordField(20); JPasswordField pass2 = new JPasswordField(20); pass2.setEchoChar ('?'); add(pass1);
add(pass2); } } JEditorPane The JEditorPane class is a specialized JTextComponent for displaying and editing HTML 3.2 tags or some other format like RTF (rich text format), as determined by the input. It is not meant to provide a full-fledged browser, but a lightweight HTML viewer, usually for the purpose of displaying help text. You either construct the pane with a URL parameter (via a String or URL), or change pages with the setPage() method. For HTML content, links within the HTML page are traversable with the help of a HyperlinkListener.
public class Browser extends JPanel { Browser() { setLayout (new BorderLayout (5, 5)); final JEditorPane jt = new JEditorPane(); final JTextField input = new JTextField("http://java.sun.com"); // make read-only jt.setEditable(false); // follow links jt.addHyperlinkListener(new HyperlinkListener () {
public void hyperlinkUpdate( final HyperlinkEvent e) { if (e.getEventType() == HyperlinkEvent.EventType.ACTIVATED) { SwingUtilities.invokeLater(new Runnable() { public void run() { // Save original Document doc = jt.getDocument(); try { URL url = e.getURL(); jt.setPage(url); input.setText (url.toString()); } catch (IOException io) { JOptionPane.showMessageDialog ( Browser.this, "Can't follow link", "Invalid Input", JOptionPane.ERROR_MESSAGE); jt.setDocument (doc); } } }); } } }); JScrollPane pane = new JScrollPane(); pane.setBorder ( BorderFactory.createLoweredBevelBorder()); pane.getViewport().add(jt); add(pane, BorderLayout.CENTER);
input.addActionListener (new ActionListener() { public void actionPerformed (ActionEvent e) { try { jt.setPage (input.getText()); } catch (IOException ex) { JOptionPane.showMessageDialog ( Browser.this, "Invalid URL", "Invalid Input", JOptionPane.ERROR_MESSAGE); } } }); add (input, BorderLayout.SOUTH); } }
To activate the hyperlinks within the JEditorPane, event handling code is provided. Also, if you only want to display HTML, remember to setEditable(false) to make the editor read-only. JScrollBar JScrollBar offers a lightweight version of the java.awt.Scrollbar component.
public class ScrollbarPanel extends JPanel { public ScrollbarPanel() { setLayout(new BorderLayout()); JScrollBar scrollBar1 = new JScrollBar ( JScrollBar.VERTICAL, 0, 5, 0, 100); add(scrollBar1, BorderLayout.EAST); JScrollBar scrollBar2 = new JScrollBar ( JScrollBar.HORIZONTAL, 0, 5, 0, 100); add(scrollBar2, BorderLayout.SOUTH); } } JComboBox The JComboBox works like AWT's Choice component, but renames some methods and offers an editable option. For times when a fixed-list of choices isn't enough, you can offer a JComboBox with a list of default choices, but still permit the entry of another value. The nicest part about this control is that when the user presses the key for the first letter of an entry, it changes the highlighted selection. You can enhance this behavior by providing your own KeySelectionManager, a public inner class of JComboBox.
String choices[] = { "Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus","Neptune", "Pluto"}; public ComboPanel() { JComboBox combo1 = new JComboBox(); JComboBox combo2 = new JComboBox(); for (int i=0;i<choices.length;i++) { combo1.addItem (choices[i]); combo2.addItem (choices[i]); } combo2.setEditable(true); combo2.setSelectedItem("X"); combo2.setMaximumRowCount(4); add(combo1); add(combo2); } }
There is more to JComboBox than just a few new methods and editability. Details are included in Part II of this course, after the Model/View/Controller (MVC) Architecture has been explained. JList The JList component has both an easy (non-MVC) implementation and a more complicated view. For the MVC-view, you'll see an example in Part II of this course with JComboBox. For now, you'll see how to display a list of String objects, just like an AWT List component. Thankfully, it has gotten much easier. To add a String[] (or Vector) of elements to a JList, just tell the constructor or use the setListData() method.
There is one major difference between List and JList. JList doesn't directly support scrolling. You need to place the JList within a JScrollPane object, and let it deal with the scrolling.
public class ListPanel extends JPanel { String label [] = {"Cranberry", "Orange", "Banana", "Kiwi", "Blueberry", "Pomegranate", "Apple", "Pear", "Watermelon", "Raspberry", "Snozberry" }; public ListPanel() { setLayout (new BorderLayout()); JList list = new JList(label); JScrollPane pane = new JScrollPane(list); add(pane, BorderLayout.CENTER); } } Borders The javax.swing.border package consists of several objects to draw borders around components. They all implement the Border interface, which consists of three methods:
public
Insets
getBorderInsets(Component
c)
public
boolean
isBorderOpaque()
public void paintBorder (Component c, Graphics g, int x, int y, int width, int should only draw into the area requested with getBorderInsets(). height) Defines how to draw the border within the specified area. The routine
The border behavior is defined for JComponent, so all subclasses inherit the behavior. Swing provides nine borders, and you can create your own if none of them meets your needs:
o
AbstractBorder - An abstract class that implements the Border interface, BevelBorder - A 3D border that may be raised or lowered CompoundBorder - A border that can nest multiple borders EmptyBorder - A border where you specify the reserved space for an EtchedBorder - A border that appears as a groove, instead of raised or LineBorder - A border for single color borders, with arbitrary thickness MatteBorder - A border that permits tiling of an icon or color SoftBevelBorder - A 3D border with softened corners TitledBorder - A border that permits title strings in arbitrary locations
undrawn border
o
lowered
o o o o
You can create a border object directly from the appropriate class constructor or ask a BorderFactory to create the and border for you, with methods When like using createBevelBorder(type) createTitledBorder("TItle").
BorderFactory, multiple requests to create the same border return the same object.
public class BorderPanel extends JPanel { class MyBorder implements Border { Color color; public MyBorder (Color c) { color = c; } public void paintBorder (Component c, Graphics g, int x, int y, int width, int height) { Insets insets = getBorderInsets(c); g.setColor (color); g.fillRect (x, y, 2, height); g.fillRect (x, y, width, 2); g.setColor (color.darker()); g.fillRect (x+width-insets.right, y, 2, height); g.fillRect (x, y+height-insets.bottom, width, 2); } public boolean isBorderOpaque() { return false; } public Insets getBorderInsets(Component c) {
return new Insets (2, 2, 2, 2); } } public BorderPanel() { setLayout (new GridLayout (4, 3, 5, 5)); JButton b = new JButton("Empty"); b.setBorder (new EmptyBorder (1,1,1,1)); add(b); b = new JButton ("Etched"); b.setBorder (new EtchedBorder ()); add(b); b = new JButton ("ColorizedEtched"); b.setBorder (new EtchedBorder (Color.red, Color.green)); add(b); b = new JButton ("Titled/Line"); b.setBorder(new TitledBorder ( new TitledBorder( LineBorder.createGrayLineBorder(), "Hello"), "World", TitledBorder.RIGHT, TitledBorder.BOTTOM)); add(b); b = new JButton ("Bevel Up"); b.setBorder(new BevelBorder(BevelBorder.RAISED)); add(b); b = new JButton ("Bevel Down"); b.setBorder(new BevelBorder(BevelBorder.LOWERED));
add(b); b = new JButton ("Soft Bevel Up"); b.setBorder( new SoftBevelBorder(SoftBevelBorder.RAISED)); add(b); b = new JButton ("Soft Bevel Down"); b.setBorder( new SoftBevelBorder(SoftBevelBorder.LOWERED)); add(b); b = new JButton ("Matte"); b.setBorder( new MatteBorder(5, 10, 5, 10, Color.red)); add(b); b = new JButton ("Matte Icon"); Icon icon = new ImageIcon ("SmallTiger.gif"); b.setBorder(new MatteBorder(10, 10, 10, 10, icon)); add(b); b = new JButton ("ColorizedBezel"); b.setBorder(new BevelBorder(BevelBorder.RAISED, Color.red, Color.pink)); add(b); b = new JButton ("My/Compound"); b.setBorder(new CompoundBorder( new MyBorder(Color.red), new CompoundBorder (new MyBorder(Color.green), new MyBorder(Color.blue)))); add(b); } }
You can change the border of any JComponent object with the setBorder() method. Magercise
5.
Using Borders
Menus The menuing model used in Swing is nearly identical to that used in AWT. There are three key exceptions:
The menu classes (JMenuItem, JCheckBoxMenuItem, JMenu, and JMenuBar) are all subclasses of JComponent. They are not off in their own independent class hierarchy. As a result of this, you can place a JMenuBar within any Container, including Applet. [The JApplet class has a setJMenuBar() method to add a JMenuBar.] There is a new menu class, JRadioButtonMenuItem, to provide a set of mutually exclusive checkboxes on a menu, when placed within a ButtonGroup. Also, you can associate an Icon object with any JMenuItem.
public class MenuTester extends JFrame implements ActionListener { public void actionPerformed (ActionEvent e) { System.out.println (e.getActionCommand()); } public MenuTester() { super ("Menu Example"); JMenuBar jmb = new JMenuBar(); JMenu file = new JMenu ("File"); JMenuItem item; file.add (item = new JMenuItem ("New")); item.addActionListener (this); file.add (item = new JMenuItem ("Open")); item.addActionListener (this); file.addSeparator(); file.add (item = new JMenuItem ("Close")); item.addActionListener (this); jmb.add (file); JMenu edit = new JMenu ("Edit");
edit.add (item = new JMenuItem ("Copy")); item.addActionListener (this); Icon tigerIcon = new ImageIcon("SmallTiger.gif"); edit.add (item = new JMenuItem ("Woods", tigerIcon)); item.setHorizontalTextPosition (JMenuItem.LEFT); item.addActionListener (this); edit.add (item = new JMenuItem ("Woods", tigerIcon)); item.addActionListener (this); jmb.add (edit); JMenu choice = new JMenu ("Choices"); JCheckBoxMenuItem check = new JCheckBoxMenuItem ("Toggle"); check.addActionListener (this); choice.add (check); ButtonGroup rbg = new ButtonGroup(); JRadioButtonMenuItem rad = new JRadioButtonMenuItem ("Choice 1"); choice.add (rad); rbg.add (rad); rad.addActionListener (this); rad = new JRadioButtonMenuItem ("Choice 2"); choice.add (rad); rbg.add (rad); rad.addActionListener (this); rad = new JRadioButtonMenuItem ("Choice 3"); choice.add (rad); rbg.add (rad);
rad.addActionListener (this); jmb.add (choice); setJMenuBar (jmb); } } JSeparator The JSeparator object is the menu separator control. The image below shows the separator under the File menu from the example above.
Because Swing menu objects are truly components, you can use JSeparator outside of menus, too. However, normally you just add them to a JMenu with addSeparator(). JPopupMenu The JPopupMenu component allows you to associate context-sensitive menus with any JComponent. They work similarly to the AWT PopupMenu class, with an addSeparator() method to add a separator bar.
public class PopupPanel extends JPanel { JPopupMenu popup = new JPopupMenu (); public PopupPanel() { JMenuItem item; popup.add (item = new JMenuItem ("Cut")); popup.add (item = new JMenuItem ("Copy")); popup.add (item = new JMenuItem ("Paste")); popup.addSeparator(); popup.add (item = new JMenuItem ("Select All")); popup.setInvoker (this); addMouseListener (new MouseAdapter() { public void mousePressed (MouseEvent e) { if (e.isPopupTrigger()) { popup.show (e.getComponent(), e.getX(), e.getY()); } } public void mouseReleased (MouseEvent e) { if (e.isPopupTrigger()) { popup.show (e.getComponent(), e.getX(), e.getY()); } }
}); } } JFrame and Windows The Window class hierarchy is a little different when the Swing window classes are added.
As the diagram shows, they all subclass Window, not JComponent. This means they are not lightweight, have a peer, and cannot be transparent. The JFrame class is the replacement for AWT's Frame class. In addition to the ability to add a java.awt.MenuBar via setMenuBar(), you can add a JMenuBar to a JFrame via setJMenuBar(). The other difference of the JFrame class is shared with the JWindow and JDialog classes. No longer do you just add() components to each directly or setLayout() to change the LayoutManager. Now, you must get what's called a content pane, then add components to that or change its layout.
public static void main (String args[]) { JFrame f = new JFrame ("JFrame Example"); Container c = f.getContentPane(); c.setLayout (new FlowLayout()); for (int i = 0; i < 5; i++) { c.add (new JButton ("No")); c.add (new Button ("Batter")); } c.add (new JLabel ("Swing")); f.setSize (300, 200); f.show(); } }
The reason you have to get a content pane is because the inside of a window is now composed of a JRootPane, which no longer shields you from the inner workings of the Window, as AWT did. One other difference between JFrame and Frame is JFrame has a property that defines the default close operation. With Frame, nothing happens, by default, if you try to close the frame. On the other hand, JFrame will hide itself when you try to close it. The setDefaultCloseOperation() method lets you define three operations that can happen when the user tries to close a JFrame:
DO_NOTHING_ON_CLOSE: The AWT Frame behavior HIDE_ON_CLOSE: The default behavior. When user tries to close the window, the window will be hidden. You can then setVisible(true) to reshow it. DISPOSE_ON_CLOSE: When user tries to close window, it will be disposed.
Both HIDE_ON_CLOSE and DISPOSE_ON_CLOSE perform their operations last, in case an event listener needs to use the information from the closing event. JRootPane A JRootPane is a container that consists of two objects, a glass pane and a layered pane. The glass pane is initially invisible, so all you see is the layered pane. The layered pane also consists of two objects, an optional menu bar and a content pane. You work with the content pane just like you would the inside of a Window, Dialog, or Frame in AWT. The way the glass pane works is if you place a component in it, this component will always display in front of the content pane. This allows things like popup menus and tool tip text to work properly. The layering effect is done with the help of the new JLayeredPane component, explained next. Normally, the only difference in coding is changing all lines like: aFrame.setLayout (new FlowLayout()); aFrame.add(aComponent); to new lines accessing the content pane: aFrame.getContentPane().setLayout (new FlowLayout()); aFrame.getContentPane().add(aComponent); The rest of the panes are accessed with similar methods, though are rarely accessed directly. The layout management of all these panes is done through a custom layout manager. Container getContentPane(); setContentPane (Container); Component getGlassPane(); setGlassPane (Component); JLayeredPane getLayeredPane(); setLayeredPane (JLayeredPane); JMenuBar getMenuBar(); setMenuBar (JMenuBar);
JLayeredPane The JLayeredPane container keeps its children in layers to define an order to paint its components. When you add a component to the pane, you specify which layer you want it in: layeredPane.add (component, new Integer(5)); The default layer is the value JLayeredPane.DEFAULT_LAYER. You can add or subtract values from this value to have things appear above or below, layerwise. The LayoutManager of the pane determines what happens with the layers. Using FlowLayout or GridLayout as the layout only reorders the components as they are added; they will not be drawn on top of each other. For an example of actually drawing overlaid components, see the examples subdirectory that comes with the Swing release. Swing in Applets For applets to properly handle the Swing component set, your applets need to subclass JApplet instead of Applet. JApplet is a special subclass of Applet that adds support for JMenuBar and handles the painting support required by Swing child components (along with any other necessary tasks like accessibility support). Also, like JFrame, JApplet has a JContentPane to add components into, instead of directly to the applet. Another difference is the default LayoutManager: in JApplet it is BorderLayout, while in Applet it has always been FlowLayout.
public class AppTester extends JApplet { public void init () { Container c = getContentPane(); JButton jb = new JButton ("Default"); c.add (jb, BorderLayout.WEST); jb = new JButton ("LayoutManager"); c.add (jb, BorderLayout.CENTER); jb = new JButton ("is"); c.add (jb, BorderLayout.EAST); jb = new JButton ("BorderLayout: " + (c.getLayout() instanceof BorderLayout)); c.add (jb, BorderLayout.SOUTH); } }
The LayoutManager is actually a custom subclass of BorderLayout. This subclassing ensures that when a component with no constraints is added, the subclass maps the component to the CENTER area. Tooltips A tooltip is a context-sensitive text string that is displayed in a popup window when the mouse rests over a particular object on the screen. Swing provides the JToolTip
class to support this; however, you will rarely use it directly. To create a tooltip, you only need to call the setToolTipText() method of JComponent.
public class TooltipPanel extends JPanel { public TooltipPanel() { JButton myButton = new JButton("Hello"); myButton.setToolTipText ("World"); add(myButton); } }
JTabbedPane The JTabbedPane component offers a tabbed control for quick accessibility to multiple panels. If you ever tried to use CardLayout in JDK 1.0/1.1, you'll appreciate this: JTabbedPane adds the necessary support for changing from one card to the next. After creating the control, you add cards to it with the addTab() method. There are three forms for the addTab() method. One offers a quick way to associate a JToolTip to a tab, while the others only permit text, an Icon, or both. Any Component subclass can be the object added to each card.
o
addTab(String title, Component component) - Create new tab with title as addTab(String title, Icon icon, Component component) - Adds an options addTab(String title, Icon icon, Component component, String tip) - Adds
icon to be associated with the title for the tab. Either may be null.
o
public class TabbedPanel extends JPanel { String tabs[] = {"One", "Two", "Three", "Four"}; public JTabbedPane tabbedPane = new JTabbedPane(); public TabbedPanel() { setLayout (new BorderLayout()); for (int i=0;i<tabs.length;i++) tabbedPane.addTab (tabs[i], null, createPane (tabs[i])); tabbedPane.setSelectedIndex(0); add (tabbedPane, BorderLayout.CENTER); } JPanel createPane(String s) { JPanel p = new JPanel(); p.add(new JLabel(s)); return p; } } JSplitPane The JSplitPane control offers user-controlled resizing of two components within a container. You can place a JSplitPane within a JSplitPane for control of more then two components, and, you can control whether the splitting happens vertically or horizontally. The setContinuousLayout property causes each pane to be updated continuously as the splitter is dragged, when set to true.
You can move the divider programmatically by setting the dividerLocation property to a floating point value between 0.0 and 1.0 to indicate a percentage of the screen or to an integer value for an absolute position. The following screenshots demonstrate a JSplitPane between a JTree and a JList. (Note that the scrollbars in the pictures are there because the components are included in a JScrollPane; it is not a result of the JSplitPane.
The arrows on the splitter bar are obtained by setting the oneTouchExpandable property of the JSplitPane to true. Pressing them will fully push the splitter in the direction of the arrow, or return it to its previous position. Note that the splitter bar will not move past the minimumSize of either component if it can avoid it. In many cases it is desirable to call the following: comp.setMinimumSize(new Dimension(0,0)); on each component to allow full movement of the splitter bar. public class JSplitPanel extends JPanel { public JSplitPanel() {
setLayout(new BorderLayout()); JTree tree = new JTree(); String[] items = {"a", "two", "three", "four", "five", "six", "seven"}; JList list = new JList(items); JScrollPane left = new JScrollPane(tree); JScrollPane right = new JScrollPane(list); left.setMinimumSize(new Dimension(0,0)); right.setMinimumSize(new Dimension(0,0)); JSplitPane pane = new JSplitPane( JSplitPane.HORIZONTAL_SPLIT, left, right); pane.setDividerLocation(0.5); pane.setOneTouchExpandable(true); add(pane, BorderLayout.CENTER); } }
Swing Layouts There are four primary Swing layout managers, two are built into components (ScrollPaneLayout and ViewportLayout) and the remaining two (BoxLayout and OverlayLayout) are used like the ones from java.awt. The BoxLayout also happens to be built into the Box component. BoxLayout The BoxLayout layout manager allows you to arrange components along either an xaxis or y-axis. For instance, in a y-axis BoxLayout, components are arranged from top to bottom in the order in which they are added. Unlike GridLayout, BoxLayout allows components to occupy different amounts of space along the primary axis. A JTextField in a top-to-bottom BoxLayout can take much less space than a JTextArea.
Along the non-primary axis, BoxLayout attempts to make all components as tall as the tallest component (for left-to-right BoxLayouts) or as wide as the widest component (for top-to-bottom BoxLayouts). If a component cannot increase to this size, BoxLayout looks at its Y-alignment property or X-alignment property to determine how to place it within the available space. By default, JComponent objects inherit an alignment of 0.5 indicating that they will be centered. You can override the getAlignmentX() and getAlignmentY() methods of Container to specify a different default alignment. JButton for instance specifies left alignment. To create a BoxLayout, you must specify two parameters: setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); The first parameter specifies the container and the second the major axis of the BoxLayout. Components can then be added as they are in a GridLayout or FlowLayout: add(myComponent);
class BoxLayoutTest extends JPanel { BoxLayoutTest() { // Set the layout to a y-axis BoxLayout setLayout(new BoxLayout(this, BoxLayout.Y_AXIS)); // Create three components
TextField textField = new TextField(); TextArea textArea = new TextArea(4, 20); JButton button = new JButton( "Tiger", new ImageIcon("SmallTiger.gif")); // Add the three components to the BoxLayout add(new JLabel("TextField:")); add(textField); add(new JLabel("TextArea:")); add(textArea); add(new JLabel("Button:")); add(button); }} Box The Box class is a convenience container whose default layout manager is a BoxLayout. Rather than subclassing JPanel as above, the previous example could have subclassed the Box class. In addition to being a BoxLayout container, Box has some very useful static methods for arranging components in a BoxLayout. These methods create non-visual components that act as fillers and spacers. createVerticalStrut(int) createHorizontalStrut(int) createVerticalGlue() createHorizontalGlue() createGlue() createRigidArea(Dimension) Returns a fixed height component used for spacing Returns a fixed width component used for spacing Returns a component whose height expands to absorb excess space between components Returns a component whose width expands to absorb excess space between components Returns a component whose height will expand for a yaxis box and whose width will expand for an x-axis Box Returns a fixed height, fixed width component used for spacing
Now, rather than using labels to space components out as above, you could use struts and glue:
public class TestBox extends Box { TestBox() { super(BoxLayout.Y_AXIS); // Create the three basic text components TextField textField = new TextField(); TextArea textArea = new TextArea(4, 20); JButton button = new JButton("Tiger", new ImageIcon("SmallTiger.gif")); // Separate the three components // by struts for spacing add(createVerticalStrut(8)); add(textField); add(createVerticalGlue()); add(textArea); add(createVerticalGlue()); add(button); add(createVerticalStrut(8)); }
The struts will appear as top and bottom margins and the glue will expand to fill space when the Box is heightened. Magercise
7.
Using BoxLayout
ScrollPaneLayout The ScrollPaneLayout is the layout manager used by a JScrollPane. You do not need to create one, nor associate it to the JScrollPane. That is done for you automatically. The layout defines nine different areas for the JScrollPane:
o o o o
one JViewport - in the center for the content two JScrollBar objects - one each for horizontal and vertical scrolling two JViewport objects - one for a column headers, the other row four Component objects one for each of the corners
The JScrollPane constants to specify the corners are: LOWER_LEFT_CORNER, LOWER_RIGHT_CORNER, UPPER_RIGHT_CORNER. The center viewport portion of this layout is of primary interest for simple layouts. A JViewport is itself a container object that can hold components. This allows for some very flexible arrangements. JViewport contains its own layout manager, ViewportLayout. ViewportLayout ViewportLayout is the layout manager used by a JViewport. You should never need to use the layout directly, as it is automatically associated with a JViewport object, and positions the internal component for you based upon the JViewport properties. UPPER_LEFT_CORNER,
Testing is one of the most important phases in the software development activity. In software development life cycle (SDLC), the main aim of testing process is the quality; the developed software is tested against attaining the required functionality and performance. During the testing process the software is worked with some particular test cases and the output of the test cases are analyzed whether the software is working according to the expectations or not.
The success of the testing process in determining the errors is mostly depends upon the test case criteria, for testing any software we need to have a description of the expected behaviour of the system and method of determining whether the observed behaviour confirmed to the expected behaviour. Since the errors in the software can be injured at any stage. So, we have to carry out the testing process at different levels during the development. The basic levels of testing are Unit, Integration, System and Acceptance Testing. The Unit Testing is carried out on coding. Here different modules are tested against the specifications produced during design for the modules. In case of integration testing different tested modules are combined into sub systems and tested in case of the system testing the full software is tested and in the next level of testing the system is tested with user requirement document prepared during SRS. There are two basic approaches for testing. They are In Functional Testing test cases are decided solely on the basis of requirements of the program or module and the internals of the program or modules are not considered for selection of test cases. This is also called Black Box Testing
In Structural Testing test cases are generated on actual code of the program or module to be tested. This is called White Box Testing. A number of activities must be performed for testing software. Testing starts with test plan. Test plan identifies all testing related activities that need to be performed along with the schedule and guide lines for testing. The plan also specifies the levels of testing that need to be done, by identifying the different testing units. For each unit specified in the plan first the test cases and reports are produced. These reports are analyzed. Test plan is a general document for entire project, which defines the scope, approach to be taken and the personal responsible for different activities of testing. The inputs for forming test plane are
Project plan Requirements document System design Although there is one test plan for entire project test cases have to be specified separately for each test case. Test case specification gives for each item to be tested. All test cases and outputs expected for those test cases. The steps to be performed for executing the test cases are specified in separate document called test procedure specification. This document specify any specify requirements that exist for setting the test environment and describes the methods and formats for reporting the results of testing. Unit testing mainly focused first in the smallest and low level modules, proceeding one at a time. Bottom-up testing was performed on each module. As developing a driver program, that tests modules by developed or used. But for the purpose of testing, modules themselves were used as stubs, to print verification of the actions performed. After the lower level modules were tested, the modules that in the next higher level those make use of the lower modules were tested. Each module was tested against required functionally and test cases were developed to test the boundary values. Integration testing is a systematic technique for constructing the program structure, while at the same time conducting tests to uncover errors associated with interfacing. As the system consists of the number of modules the interfaces to be tested were between the edges of the two modules. The software tested under this was incremental bottom-up approach. Bottom-up approach integration strategy was implemented with the following steps. Low level modules were combined into clusters that perform specific software sub functions. The clusters were then tested.
System testing is a series of different tests whose primary purpose is to fully exercise the computer-based system. It also tests to find discrepancies between the system and its original objective, current specifications.
System Test Cases & System Test Report The system test cases mentioned below are expected to work and give the expected behavior if the explorer is configured to run jar files as mentioned in the project folder. The necessary library files and standard jar files are in the appropriate project directories and the path and class path environment variables are appropriately set.
Test C.N o.
INPUT
EXPECTED BEHAVIOUR
Login as admin with Admin Screen has to be correct login details displayed 1 2 Login as admin with Error message should be wrong login details displayed
-doAdd a user 3 It should add new user info at the backend. -do-
Delete a user
Login as user 5
User screen should be displayed with existing users info in the same room New Public user should be created
-do-
7 Create a new public room 8 Enter two users into second room
-do-
-do-
Message should be displayed for all the users in this room Message should be displayed for that user only. Room should created with a password Users who enters the correct password should be allowed Message should be displayed immediately in an alert box
-do-
10 11
-do-
-do-
12
-do-
13
P -do-
14
Message should be sent to the destination. Booted user should be logged out Message should be displayed for inviting
-doP -doP
15 16
-do-
Corporate messenger is an application developed according to client requirements. Lot of efforts was put to make it perfectly and efficiently. The developed system is tested with real data and the users are satisfied with the performance of the system and reports. This project is developed using JAVA, JFC-Swing and AWT. By using this application we can communicate with different people using different of channels across different departments in our organization. It saves our employees and company time and resources. By this lot of workload will be reduced to the each employee to communicate with other employee and get things early. This application is very useful for Administrating efficient user friendly communication system. It provides extendibility also. So you can add your modules to the system whenever there is a change in business logic or new business units are entered. This reduces the physical work, time as well as money saved. The time for sending the problems and getting the solutions is considerably reduced. All the features are implemented and developed as per the requirements.
An Integrated Approach to Software Engineering For UML diagrams : UML in 24 Hours Book
Introduction to System Analysis and Design : I.T.Hawryszkiewycz Some preferred websites : www.bruceeckel.com www.sun.com/j2se/JFC-Swing ww.sun.com/j2se