Home >Documents >Chat Express

Chat Express

Date post:18-Nov-2014
View:116 times
Download:0 times
Share this document with a friend

Chat Express

1. 2. 3. 4. 5. 6.








10. 11. 12.



Chat Express


Chat Express


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. ChatExpress 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. ChatExpress 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: ChatExpress 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.


Chat Express

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 inbuilt manual available.


Chat Express


Chat Express

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.


Chat Express

Project Scope and Objectives: This can be treated as a product mainly used in chatting kind of communication products to exchange the information between the by storing the users info and his connection details, chatroom control

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.


Chat Express

The key to surviving--and thriving in--change is to change yourself. When we began in 1998, we focused on IT staffing. Since then, we have continually adapted our business to stay one step ahead of our clients' needs. Today we provide global contract and direct-hire recruiting services to the world's leading companies in Singapore, Malaysia, Australia, Newzealand, UK and Ireland in critical technology sectors such as Internet core technologies, software and hardware, intranets, extranets, e-commerce, and Mobile multimedia. OPERA TECHNOLOGIES scope of services includes the full range of IT Contract Services. We have representatives in Singapore, Malaysia, UK, Australia, Newzeland and Ireland to support the recruitment activities conducted in these countries. Our clients include Global 2000 corporations, government agencies, and healthcare institutions. Our core competency lies in building deep personal relationships. Keeping people happy, helping clients meet their business objectives, and facilitating our talent's growth--these are the hallmarks of Techmedia. Our philosophy is to bring together people and resources, broaden horizons for international businesses. Through our services, we help clients align operations with their business strategy, implement new technology to enable their strategy, and continuously optimize existing technology investments to meet their evolving business needs.


Chat Express

Consulting has become a necessity in our fast-paced technology- driven world. You might find it hard to keep up with the changes and complexity of today's huge requirements. A comprehensive collection of employment agencies, our domestic placement cell provides an essential point of reference for employment resources. We are in the profession of placing the right person, in the right place, at the right time and above all for the right price. Our long-term credibility, vitality and viability evince our unswerving commitment. We shall not compromise on quality even though speed will always be an important objective.

We shall respect and maintain confidentiality and ensure that the interests of our clients as well as the candidates are always safeguarded. We shall carefully select our own personnel and implement sound and progressive in-house human resource policies. We shall constantly endeavor to build long-term strategic business partnerships with our clients to whom we are thankful for providing us the opportunities to excel. For Employer : We collaborate with you to assist in building your people asset base by providing candidate with high intellect. For Candidate : We help you realize your career choices by providing you the right direction and offering top-notch career opportunities


Chat Express


Chat Express

The Chat Express System is developed with the aim of facilitating the effective communication channel and allows the user to send picture images, graphical chatting through canvas management, automatic logging of chatting transaction, segregating the users depending on their interests. Sending a message provides a private communication channel using the users can talk personally. A person, called admin, maintains this system. He can monitor each and every transaction entered by users of this system. He can also participate in the chatting using administrative client option for sending and receiving the messages. 1. Introduction 1.1 Purpose: The purpose of this document is to describe all external and internal requirements of the Chat Express. It also describes the interfaces for the system. It is a. 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.


Chat Express


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.



Scope: 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. 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


Chat Express

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.3 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.

1.4 1.5

Reference: Not Applicable.

The points that mentioned in system requirements specification areDevelopers Responsibilities overview:

1. An introductory nature describing mainly the 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 behaviour 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.


Chat Express

4. Contains external interface requirements, which includes the user, hardware and software interfaces. 5. Deals with performance requirements of the system. Contains the design constraints composing of software constraints and hardware constraints.

2. General Description Product functions overview: Chat Express is a Java Client/Server combination which can used to chat over the networks. Anyone can run Chat Express client/server, so you can hosts lot of guests on your computer or you can join in the someone elses session. The client can be used as simple JFC Swing window using which we can provide user friendly communication. This applications premier feature is white board drawing utility which we call as canvas. You can draw free hand, do circles, squares, lines, fonted text, or paste image files to the canvas. This is ideal when user wants to sketch concepts for one another. Users can interact publicly with everyone else on the server or they can chat/draw privately using chat express Whisper mode. Users can create and manage chat rooms, which can be either public private. The server will also store and answering machine-style messages for users who arent online and instant messages can also be sent. Additionally, users who arent watching their screens can be paged with sound. It can support any no of users and since it is written using java, it can be used in any java-enables environment. It works best with JDK1.4.1_01 but should be compatible with earlier


Chat Express

version also. The Chat Express in normally operated in GUI mode. 2.1 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. 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.



Assumptions and Dependencies: not applicable

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.1Inputs:

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.



Chat Express

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, fonted text, or paste image files to the canvas.




User Management Module: It allows the administrator to

view the list of users or information corresponding to a


Chat Express

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. Messages Module: It list of offline messages. also generates user wise

4. External Interface Requirements 4.1User Interface: This application provides JFC Swing based

GUI interface for the administrator to start the server at the particular port no and set the preferences and settings. The normal users can connection to server and start using the option through similar kind of interface. 4.2Software Interfaces: These interface requirements should

specify the interface with other. Software which the system will use or which will use the system, this includes the interface with the operating system and other applications. The message content and format of each interface should be given. Hardware Interfaces: Hardware interface is very important to the documentation. If the software is execute on existing hardware or on the pre-determined hardware, all the characteristics of the hardware, including memory restrictions, should be specified. In addition, the current use and load characteristics of the hardware should be given.


5. Performance Requirements


Chat Express

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


Software constraints : Operating System Forms & Reports Other Softwares : Windows2000 Server/

XP : JFC Swing & AWT : JDK1.4


Hardware Constraints : Pentium Processor RAM Hard Disk CD/ROM Drive : : : :

PentiumIV256 MB 20 GB 52X


Chat Express VDU Key Board : :

VGA 101 Standard

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.

CLIENT SERVEROVER VIEW:With the varied topic in existence in the fields of computers, Client Server is one, which has generated more heat than light, and also more hype than reality. This technology has acquired a certain critical mass attention with its dedication conferences and magazines. Major computer vendors such as IBM and DEC, have declared that Client Servers is their main future market. A survey of DBMS magazine reveled that 76% of its readers were actively looking at the client server solution. The growth in the client server development tools from $200 million in 1992 to more than $1.2 billion in 1996. Client server implementations are complex but the underlying concept is simple and powerful. A client is an application running with local resources but able to request the database and relate the services from separate remote server. The software mediating this client server interaction is often referred to as MIDDLEWARE. The typical client either a PC or a Work Station connected through a network to a more powerful PC, Workstation, Midrange or Main Frames server usually capable of handling request from more than one client. However, with some


Chat Express

configuration server may also act as client. A server may need to access other server in order to process the original client request. The key client server idea is that client as user is essentially insulated from the physical location and formats of the data needs for their application. With the proper middleware, a client input from or report can transparently access and manipulate both local database on the client machine and remote databases on one or more servers. An added bonus is the client server opens the door to multi-vendor database access indulging heterogeneous table joins.

What is a Client Server Two prominent systems in existence are client server and file server systems. It is essential to distinguish between client servers and file server systems. Both provide 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. Why Client Server Client server has evolved to solve a problem that has been around since the earliest days of computing: how best to distribute your computing, data generation and data storage resources in order to obtain efficient, cost effective departmental an enterprise wide data processing. During mainframe era choices were quite limited. A central machine housed both the CPU and20

Chat Express

DATA (cards, tapes, drums and later disks). Access to these resources was initially confined to batched runs that produced departmental reports at the appropriate intervals. A strong central information service department ruled the corporation. The role of the rest of the corporation limited to requesting new or more frequent reports and to provide hand written forms from which the central data banks were created and updated. The earliest client server solutions therefore could best be characterized as SLAVE-MASTER. Time-sharing changed the picture. Remote terminal could view and even change the central data, subject to access permissions. And, as the central data banks evolved in to sophisticated relational database with nonprogrammer query languages, online users could formulate adhoc queries and produce local reports with out adding to the MIS applications software backlog. However remote access was through dumb terminals, and the client server remained subordinate to the Slave\Master.


The entire user interface is planned to be developed in browser specific environment with a touch of Intranet-Based Architecture for achieving the Distributed Concept. 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.



Chat Express

The Communication architecture is designed by concentrating on the Standards of Servlets and Enterprise Java Beans. The database connectivity is established by using the Java Data Base Connectivity. The standards of three-tire architecture are given major concentration to keep the standards of higher cohesion and limited coupling for effectiveness of the operations.

FEATURES OF THE LANGUAGE USEDIn my project, I have chosen Java language for developing the code.


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.



Chat Express

Java has had a profound effect on the Internet. This is because; Java expands the Universe of objects that can move about freely in Cyberspace. In a network, two categories of objects are transmitted between the Server and the Personal computer. They are: Passive information and Dynamic active programs. The Dynamic, Selfexecuting programs cause serious problems in the areas of Security and probability. But, Java addresses those concerns and by doing so, has opened the door to an exciting new form of program called the Applet.JAVA CAN BE USED TO CREATE TWO TYPES OF PROGRAMS

Applications and Applets: An application is a program that runs on our Computer under the operating system of that computer. It is more or less like one creating using C or C++. Javas ability to create Applets makes it important. An Applet is an application designed to be transmitted over the Internet and executed by a Java compatible web browser. An applet is actually a tiny Java program, dynamically downloaded across the network, just like an image. But the difference is, it is an intelligent program, not just a media file. It can react to the user input and dynamically change.FEATURES OF JAVASecurity 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 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 application and your



Chat Express

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. The Byte code The key that allows the Java to solve the security and portability problems is that the output of Java compiler is Byte code. Byte code is a highly optimized set of instructions designed to be executed by the Java run-time system, which is called the Java Virtual Machine (JVM). That is, in its standard form, the JVM is an interpreter for byte code. Translating a Java program into byte code helps makes it much easier to run a program in a wide variety of environments. The reason is, once the run-time package exists for a given system, any Java program can run on it. Although Java was designed for interpretation, there is technically nothing about Java that prevents on-the-fly compilation of byte code into native code. Sun has just completed its Just In Time (JIT) compiler for byte code. When the JIT compiler is a part of JVM, it compiles byte code into executable code in real time, on a piece-by-piece, demand basis. It is not possible to compile an entire Java program into executable code all at once, because Java performs various runtime checks that can be done only at run time. The JIT compiles code, as it is needed, during execution. Java, Virtual Machine (JVM) Beyond the language, there is the Java virtual machine. The Java virtual machine is an important element of the Java technology. The virtual machine can be embedded within a web browser or an operating system. Once a piece of Java code is loaded onto a machine, it is verified. As part of the loading process, a class loader is invoked and does byte code verification makes sure that the code thats has been generated by the compiler will not corrupt the machine that


its loaded on. Byte code verification takes place at the 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

Chat Express



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.


Compiling and interpreting Java Source Code

Chat Express


Source Code .. .. ..

C Compil er

Java Interpreter (PC)

Java Byte code (Platform indepen dent) Java Interpreter (Macintosh) Java Interpreter (Sparc)

Macintosh Compiler


Com piler

During run-time the Java interpreter tricks the bytecode file into thinking that it is running on a Java Virtual Machine. In reality this could be a Intel Pentium Windows 95 or SunSARC 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 highperformance non-objects. 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.

Chat Express


Chat Express

JFC OverviewSun 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.

Chat Express

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 colorchooser 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 filechooser 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.29

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.

Chat Express


Chat Express



Chat Express






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. You32

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(); }

Chat Express

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: An Image loads asynchronously, creating the need to monitor the loading process (with MediaTracker). 2. An Image is not serializable.1.

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() {


Chat Express

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: Add an Icon Set the vertical and horizontal position of text relative to the Icon 5. Set the relative position of contents within component3. 4.

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); } }


Chat Express

JButton A JButton can be instantiated and used in a GUI just like a java.awt.Button. It behaves like an AWT 1.1 Button, notifying ActionListener list elements when pushed.

public class ButtonPanel extends JPanel { public ButtonPanel () { JButton myButton = new JButton("Tiger"); add(myButton); } }

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. Installing Swing and SwingSet Demonstration 7. Creating Your First JFC Application 8. Creating Buttons With Icons AbstractButton35

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 the VK_* constants from KeyEvent to specify the key o doClick() - Programmatically, select the button o setDisabledIcon(), setDisabledSelectedIcon(), setPressedIcon(), setRolloverIcon(), setRolloverSelectedIcon(), setSelectedIcon() - Change the displayed Icon, based on the button state (in addition to setIcon()) o setVerticalAlignment(), setHorizontalAlignemnt() - Anchors icon/text in different areas of button o setVerticalTextPosition(), setHorizontalTextPosition() Positions 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 . This will allow you to have multi-line button labels without having to customize the user interface. JCheckBoxo

Chat Express

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() {


Chat Express

// 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.

Chat Express

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);


Chat Express

// 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); radioButton = new JRadioButton("$75,000"); radioButton.setMnemonic (KeyEvent.VK_7); 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() {


Chat Express

// Set the layout to a GridLayout setLayout(new GridLayout(4,1, 10, 10)); add (new JToggleButton ("Fe")); add (new JToggleButton ("Fi")); add (new JToggleButton ("Fo")); add (new JToggleButton ("Fum")); } }

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 subsubclasses 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

Chat Express

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));


Chat Express

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.

Chat Express

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.


Chat Express

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() {


Chat Express

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 (


Chat Express

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.

public class ComboPanel extends JPanel { 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

Popular Tags:

Click here to load reader

Reader Image
Embed Size (px)