integrated database environment with a single consistent interface

115
Abstract Integrated Database Environment with a Single Consistent Interface is a GUI SQL client written in 100% Java. Integrated Database Environment with a Single Consistent Interface can communicate with any database that has a JDBC driver. It should run anywhere Java runs. I use it on Linux and Windows XP Professional with Oracle's 100% Java JDBC driver. Integrated Database Environment with a Single Consistent Interface acts like a universal database client which can connect to any database and perform any required operations on that database. Integrated Database Environment with a Single Consistent Interface is versatile in such a way it can -connect to any database -execute any query and show the results in the same window. -create mutiple connections to mutiple databases. -The executed set of commands can be saved in a SQL file and can be later retrieved and run. This is useful to perform repeated tasks. -Open mutiple SQL files in mutiple windows Integrated Database Environment with a Single Consistent Interface runs each query in a separate thread so the GUI remains alive while a query is running. Integrated Database Environment with a Single Consistent Interface has got a simple tabbed pane where provision for connecting to any database is available. Its File- >Configure feature helps to specify the database name to which a connection is needed. Once connected to the database using Query option, we can execute any statement on the database. File option has sub options like: New, Open, Save, Close, Configure options. These are all highly useful to perform various tasks on files and configuring the databases. Feature Rich Universal DataBase Engine

Upload: vijaykumar-bonagiri

Post on 27-Nov-2014

120 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Integrated Database Environment With a Single Consistent Interface

Abstract

Integrated Database Environment with a Single Consistent Interface is a GUI SQL client written in 100% Java. Integrated Database Environment with a Single Consistent Interface can communicate with any database that has a JDBC driver. It should run anywhere Java runs. I use it on Linux and Windows XP Professional with Oracle's 100% Java JDBC driver. Integrated Database Environment with a Single Consistent Interface acts like a universal database client which can connect to any database and perform any required operations on that database.

Integrated Database Environment with a Single Consistent Interface is versatile in such a way it can-connect to any database-execute any query and show the results in the same window.-create mutiple connections to mutiple databases.-The executed set of commands can be saved in a SQL file and can be later retrieved and run. This is useful to perform repeated tasks.-Open mutiple SQL files in mutiple windows

Integrated Database Environment with a Single Consistent Interface runs each query in a separate thread so the GUI remains alive while a query is running. Integrated Database Environment with a Single Consistent Interface has got a simple tabbed pane where provision for connecting to any database is available. Its File->Configure feature helps to specify the database name to which a connection is needed. Once connected to the database using Query option, we can execute any statement on the database.

File option has sub options like: New, Open, Save, Close, Configure options. These are all highly useful to perform various tasks on files and configuring the databases.

Edit option has cut, copy, paste options.

Query option has commit, rollback and execute options. After a set of commands are executed, we can save the changes permanently to a database using commit. To cancel the affect of earlier changes, by using rollback. There is cancel option to cancel a query and type a new one.

Save document option is very helpful to save a set of given commands as a file. This file can be later on retrieved and executed. When this file is executed, all those commands will be one by one executed. This is useful for the people who want to repeatedly perform certain tasks. Once the task related commands are stored in a file like this, he/she can execute them whenever they want.

Integrated Database Environment with a Single Consistent Interface also allows us to export the data to .csv file by using specified delimiters. Further we can use that .csv file to import that same data to any database.

Feature Rich Universal DataBase Engine

Page 2: Integrated Database Environment With a Single Consistent Interface

Integrated Database Environment with a Single Consistent Interface

Integrated Database Environment with a Single Consistent Interface is the

project that goes around the development of GUI Universal Database Client. It is the

project that is intended to make the connection to different databases from single

interface in an easy, fair, faster and reliable.

This software to be designed which deals with different databases and execute

different kinds of SQL statements from a single Tool. Users can create the

connections for each and every database and store it in the Tool. Later on the user can

select connection name to connect to a particular database and start executing SQL

statements. User can also execute select statements and see the results in the Tool

only. All the statements which are executed can be stored in .SQL file and at a later of

point of time the user can use that .SQL file to execute the same statements. Users can

Commit or rollback the SQL statements.

Objectives:

The objectives of the system are as follows:

1. To connect to different kinds of databases from single GUI Tool with

Flexible and user-friendly screens. We can all the SQL statements

from tool and see the results in the tool.

2. The user can commit or rollback the statement by just clicking the

button

3. We can undo, redo, cut, copy and paste the contents in text area of the

tool

4. We can switch to any database by just switching the connections

5. The results has to be displayed and those results can also be exported

to .CSV files

6. We can set the Timeout values for the connections.

7. To create the schemas from this tool

Feature Rich Universal DataBase Engine

Page 3: Integrated Database Environment With a Single Consistent Interface

Problem Definition

The present system has different tools or consoles for each and differently.

The user feels uneasy to switch over to a different database by learning the how to use

console for that database. If the user executes no of statements and after if he feels to

store all these statements to port the same statements in different machine, it is not

possible. For doing this each user has to store each and every statement by copying

and pasting it in a file. User has to manually copy the results from the console and

paste it in a file to store results of the query.

If the user wants to commit or rollback the statements then he has to manually

type the commands in their consoles. If the user wants to undo or redo the tasks

belongs to textual information then it is also not possible in most of the consoles.

This entire system needs to be performed from a single GUI tool which is

common to all the databases for better performance and makes it user-friendly.

Organization Profile

Feature Rich Universal DataBase Engine

Page 4: Integrated Database Environment With a Single Consistent Interface

Sierra Atlantic

Founded in 1993, Sierra Atlantic is headquartered in Silicon Valley with

offices in Chicago, New York, London, Singapore, Indonesia, and India. Sierra

Atlantic has over 300 customers such as Amkor, BP, Ciena, GE, HP, Kmart, PPG,

Sherwin-Williams and The Trane Company. Sierra Atlantic has many partners world

wide. Its partners include Agile, BEA, Oracle, PeopleSoft, Siebel, TIBCO,

webMethods, and WorldChain. Sierra Atlantic has been awarded Oracle's E-Business

Suite Implementer of the Year, Oracle E-Business Suite Reseller of the Year, IDC's

Solution Integrators of the 21st Century, VARBusiness' e25, and Silicon India's si100.

Sierra Atlantic is one of the first e-Business integrators to recognize and execute a

repeatable and reliable approach to business extensibility that really work

Sierra Atlantic has an established suite of key solutions for the manufacturing

industry.

Sierra Atlantic , helps customers optimize their investments in enterprise business

applications - ERP, CRM, and SCM – from leading vendors such as Agile, Oracle,

PeopleSoft, SAP and Siebel.

They offer complete lifecycle application management solutions, with excellence

in business application implementation, integration, upgrade, and support, providing

superior value with their global delivery model. They specialize in providing services

to discrete manufacturing, process manufacturing and financial services industries.

Sierra Atlantic leverages it’s offshore Global Development Center in India to

deliver services with superior quality and economics.

Sierra Atlantic Application Networks® - business process integration solutions

help simplify the enterprise application integration challenge to transform an

organization into a more agile, customer-focused business.

Feature Rich Universal DataBase Engine

Page 5: Integrated Database Environment With a Single Consistent Interface

Sierra Atlantic currently offers the following Application Networks

integrating business processes among Agile, Oracle, PeopleSoft and SAP:

Customer Relationship Management Network (CRMnet)

ECO Lens

Enterprise Services Automation Network (ESAnet)

Human Capital Management Network (HCMnet)

Portal Network (PORTALnet)

Strategic Relationship Management Network (SRMnet)

Supply Chain Management Network (SCMnet)

Sierra Atlantic offers immense value to its process industry customers

spanning food and beverage, paints and chemicals and pharmaceutical industry

sectors, more than any typical implementation or integration partner.

The services offered to the process industry are:

Enterprise-wide eBusiness technology vision, strategy and planning

ERP application integration with a focus on eBusiness solutions

Internet application design, development, and implementation

Oracle Process Manufacturing - implementation, customization and

integration

Oracle Financials - implementation, customization and integration.

Data Warehousing, Business Intelligence - design and implementation

CRM, Enterprise Information Portals - implementation, customization and

integration.

B2B Infrastructure - deployment

Feature Rich Universal DataBase Engine

Page 6: Integrated Database Environment With a Single Consistent Interface

SYSTEM ANALYSIS

Existing system

The present system is a console-based system for each and every database

separately and the user has to learn how to use that console to connect to a particular

database and how to work on console to execute SQL statements. In the real time

project development each every user has a need to connect to different kinds of the

databases that are at different locations (systems). Whenever the user wants to

connect to a database then the client libraries that are required to connect to that

database server has to be installed at the client. This process repeats in each and every

user system.

Connecting to a database from a Java Program without using installing client

libraries also involves several steps:

1) Getting the appropriate driver for that database

2) Setting the classpath to that driver

3) Specify the Driver Name to register the driver

4) Specify the URL for getting the connection

5) Write the logic for executing select statements and displaying

the results

6) Write the for executing non-select statements and display

Information that how many rows are updated

After executing the SQL statements, some consoles display the data in manner

that is not a better look and feel.

The task of existing system is maintaining information of the permanent data

to be stored in affective way by storing the data description and the actual in different

databases which presently is accomplished in the manual way.

Feature Rich Universal DataBase Engine

Page 7: Integrated Database Environment With a Single Consistent Interface

Limitations of the existing system

The existing system employs a lot of man-hours both for learning how to use

console to connect to different kinds of databases.

This time consuming evaluation coupled by the huge learning power

requirement may also lead to erroneous results. To connect to a database from a user

system needs specific database client libraries has to installed at the user system

Learn and study about a particular database console is time taking process and

that console is used to connect to one database only. Most of the databases doesn’t

have GUI based consoles to connect and work on that databases. Every user feels if

the console is a GUI based and working in GUI environment is easy when compared

to command driven environment.

The drawbacks in the existing system are as follows:

More learning work

Command driven enviroment consoles

Adjusting the console to display the results effectively

Installing the client libraries in user system

User can’t store the statements what he is executing

Manually storing the results in a file

Repeated execution of the same statements

Maintenance of schemas from consoles

Doesn’t switch over to different easily

Executing commit and rollback statements manually

Can’t use undo, redo, cut, paste options effectively from consoles

Feature Rich Universal DataBase Engine

Page 8: Integrated Database Environment With a Single Consistent Interface

Proposed System

The proposed system will be developed on client/server architecture. The user

can run this tool at their system and get connected to different database servers that

are different locations (systems) very easily.

On creation of connection, the users can connect to a database by using that

connection. For creating the connection the user has to fill out the parameters only

once. This allows the user to connect and work with any no of databases from GUI

environment. It provides a single GUI interface for managing different kinds of

databases. This type of enviroment is mainly useful for Project Managers, Project

Leaders and the user who interacts and work with different databases This tool allows

the user to store all the statements what he has executed to be stored as .SQL file.

Later on the user can use that .SQL file to repeatedly execute the same set of

statements.

The system also provides security by asking the password before get

connection if we uncheck the option save password

The objectives of the system are as follows:

1. The user has to use GUI enviroment to connect to a database.

2. Providing one universal database client which is used to maintain

different databases from a single user interface.

3. The user need not install any client libraries at the client system .

4. Provides a facility to manage the schemas.

5. The results to be displayed in the tool in effective manner

6. providing the minimum security

7. Reusing and holding the connection for some time.

Feature Rich Universal DataBase Engine

Page 9: Integrated Database Environment With a Single Consistent Interface

Merits of the Proposed System

GUI enviroment

Storing the SQL statements in .SQL file

Using the predefined connections

Connection to multiple databases in the same way

Providing the operations like cut, copy and paste inside Text Area

Providing Overall Reliability

Easy to use, effective and efficient

Easy to install

System Specifications

Hardware specifications

Processor : Pentium1 GHz

Memory : 256 MB RAM

Hard Disk Capacity : 40GB

CD-ROM : 52X

Display Card : SVGA

Software specifications

Operating System : Windows 2000 Professinal or XP

Technologies : J2SE, JFC –Swing and XML

Parser : SAX Parser

Back End : Any Database

Documentation : Ms Word 2000

Feature Rich Universal DataBase Engine

Page 10: Integrated Database Environment With a Single Consistent Interface

Feasibility Study

Feasibility analysis reduces the development risks. The major areas considered

in feasibility analysis are as follows.

The feasibility study concerns with the considerations made to verify whether

the system is fit to be developed in all terms. Once an idea to develop software is put

forward the question that arises first will pertain to the feasibility aspects. It involves

developing and understanding of the selected program. It calls for decision on the data

sources, study approaches, instruments available. The data is tabulated, analyzed and

there by various interpretations are made finally based upon the analysis. There are

different aspects in the feasibility study.

1) Economic Feasibility

2) Technical feasibility

3) Operational Feasibility

Economic Feasibility

A cost benefit analysis is made up for the project. The main component

considered in economic feasibility is extra money not to be expended if the Integrated

Database Environment with a Single Consistent Interface component is to be

installed to run the server. But there is no problem to this organization as it is already

equipped with the required hardware and software configurations. The cost benefits in

the system are reduced manual cost to a great extent, reduced typical examination

conduction and reduced stationary purchasing cost.

Feature Rich Universal DataBase Engine

Page 11: Integrated Database Environment With a Single Consistent Interface

Technical feasibility

The new system Integrated Database Environment with a Single Consistent

Interface needs any compatible J2SE software and a executable jar file support. The

proposed system will be implemented in Java. All the required hardware and software

are available with the organization. So the project can be developed with the exiting

software. Hence the project is technically feasible. Since XML can also be used in any

enviroment it is very much comfortable.

Operational Feasibility

The project developed is highly user interactive application and network

based. So it is highly operational. It is very simple to operate and even a novice

person can use this system very easily. Most important thing is no training is needed

for the user. No complicated command set is to be remembered or memorized. The

system is fully operationally feasible.

From the feasibility study it has been derived that Integrated Database

Environment with a Single Consistent Interface is fully (economically, technically

and operationally) feasible

Feature Rich Universal DataBase Engine

Page 12: Integrated Database Environment With a Single Consistent Interface

SYSTEM DESIGN

Logical Design:

The system has to be developed from the existing manual system. Study of the

manual system is done thoroughly

All the entries (both internal & external) that affect the system are

identified.

Relationships between the entities are identified.

All attributes and constraints of each attribute are determined.

All the entities are normalized for eliminating redundancy and to

achieve functional dependency.

These are the Modules in this system:

GUI Module: This module provides a graphical interface to make use of the features

available in this tool. It catches the events and executes the functionality by co-

ordinating with other modules.

Connections Module: This module provides a facility to create, edit and delete

different connections and connects to a database if the user selects a connection. It

allows the user to switch over different connections by making use of the same

interface at the front end.

SQL Module: This module allows the users to execute any SQL statement using this

tool and execute those statements on a particular database based on the selected

connection. It allows us to make use of editing option cut, copy and paste in the SQL

area. It also allows us to store the executed SQL statements into a file.

Feature Rich Universal DataBase Engine

Page 13: Integrated Database Environment With a Single Consistent Interface

Transactions Module: It allows us to store support the transactions by making use

commit and rollback options from this tool. It also allows us to store the result of an

SQL statement in .csv format for later use.

Export & Module: It allows us to export the database elements into a file and import

the same also.

Physical Design:

Its schema defines the basic design of a database. The schema is the model, plan

or structure around which fields, records and files are organized. The particular

schema selected depends upon many factors, including the kind and data type to

be processed, the number and type of users, and the hardware available.

The organization of data in the database is aimed to achieve two major

objectives.

Data integrity

Data independence

In relational database such as those created using oracle, we store information

about different subjects in separate tables. To bring the information together in a

meaningful way, we then tell database how the different subjects relates to each

other.

To design a database

We have to decide which facts we want databases to store.

Determine the tables

Feature Rich Universal DataBase Engine

Page 14: Integrated Database Environment With a Single Consistent Interface

Divide the information into separate subjects. Each subject will be in

the database.

Determine the fields.

Decide what information we want to store in each table. Each

Field is displayed as a column in the table.

Determine the relationship between information.

Look at each table and decide how the data in each table is related to

the data on other tables in the database.

Add fields to tables or create new tables if necessary.

Determine the relationships between tables.

Refine our designs.

Analyze the design for errors.

Input design

Input design includes data mediums used for inputting data and validations that

are to be done during data entry. Different messages regarding data are given to

guide users during data entry. Validation checks are done for each input.

Data entry screens are designed so that the system interacts with the user in

providing an effective dialogue. Fields in the screen are logically arranged to help

the user.

The design is the process of converting the user-originated inputs into a

compute-based format. The goal of the input design is to make the data entry easier,

logical and free from error. Errors in the input data are controlled by input design.

The application has been developed in a user-friendly manner. The windows

have been designed in such a way that during the processing the cursor is placed in

the position where the data must be entered. If any of the data going into the system is

wrong then the process and output will magnify these errors.

Feature Rich Universal DataBase Engine

Page 15: Integrated Database Environment With a Single Consistent Interface

The decisions made during design of input is:

1) To achieve the highest possible level of accuracy.

2) To provide a list of possible choices and help while accepting the

input for an important field wherever possible outputs from computer

system are required primarily to communicate the results of processing

to the users. They are also used to provide a permanent copy of these

results for later consultation/verification.

Output Design

Output refers to the results and information that are generated by the system.

Output is the main reason for developing the system and based on this, the usefulness

and applicability of system are evaluated.

Outputs from computer systems are required primarily to communicate the

results of processing to users. Efficiently designed outputs enhance the

understandability of the information.

According to the requirements of the system, various types of outputs are

considered and designed as follows.

1) Internal outputs, whose destination is within the organization and

which require careful design because they, are the user’s main

interface with the computer.

2) Interactive outputs, in which the user communication with the

Computer is essential.

Events

The following is the list of events that will take place in the system, which will

cause flow of input system

Feature Rich Universal DataBase Engine

Page 16: Integrated Database Environment With a Single Consistent Interface

External events

The user has to enter the password for getting the database connection.

The user or the administrator has to fill in the details in the connection

creation form.

The user can select different database connections

After entering his Id and password the user has to enter into the GUI

tool

After entering into GUI environment the user can execute the SQL

commands

The user can execute select statements and see the results in the Tool

Once statements are executed the same statements can be stored

in .SQL file for later use

The user export the results in to a .csv files.

User can choose the different connections to switch over to different

database

User can save his password also

XML support at the back

Temporal events

The user can use options like cut, copy and paste options like notepad and he can

execute commit, rollback options by just clicking the buttons

Error Design

Errors are always likely to occur and it is important to provide means to

handle them. These are two basic kinds of errors

Compile time errors : The error that occurs during compilation of a

program.

Run time errors : The error that occurs during execution. In JAVA

run time errors are called exceptions and the

Feature Rich Universal DataBase Engine

Page 17: Integrated Database Environment With a Single Consistent Interface

process of dealing with them is called exception

handling.

Listed below are the sources of errors

User Input errors : These are typing errors, invalid data etc.

Physical Limitations : These errors occurs with respect to physical

entitles or capacities. For example space is not

available on disk drives or out of primary

memory.

Code Error : Errors that when logic is wrong, popping empty

stacks, locating non-existing files, data

structures etc.

Technical Notes – About Software

Introduction to Swing

This introduction to using Swing in Java will walk you through the basics of Swing. This covers topics of how to create a window, add controls, postion the controls, and handle events from the controls.

The Main Window

Almost all GUI applications have a main or top-level window. In Swing, such window is usually instance of JFrame or JWindow. The difference between those two classes is in simplicity – JWindow is much simpler than JFrame (most noticeable are visual differences - JWindow does not have a title bar, and does not put a button in the

Feature Rich Universal DataBase Engine

Page 18: Integrated Database Environment With a Single Consistent Interface

operating system task bar). So, your applications will almost always start with a JFrame.

Though you can instantiate a JFrame and add components to it, a good practice is to encapsulate and group the code for a single visual frame in a separate class. Usually, I subclass the JFrame and initialize all visual elements of that frame in the constructor.

Always pass a title to the parent class constructor – that String will be displayed in the title bar and on the task bar. Also, remember to always initialize frame size (by calling setSize(width,height)), or your frame will not be noticeable on the screen.

package com.neuri.handsonswing.ch1;

import javax.swing.JFrame;

public class MainFrame extends JFrame{   public MainFrame()   {      super("My title");      setSize(300, 300);   }}

Now you have created your first frame, and it is time to display it. Main frame is usually displayed from the main method – but resist the urge to put the main method in the frame class. Always try to separate the code that deals with visual presentation from the code that deals with application logic – starting and initializing the application is part of application logic, not a part of visual presentation. A good practice is to create an Application class that will contain initialization code.

package com.neuri.handsonswing.ch1;

public class Application {   public static void main(String[] args)    {      // perform any initialization      MainFrame mf = new MainFrame();      mf.show();   }}

Feature Rich Universal DataBase Engine

Page 19: Integrated Database Environment With a Single Consistent Interface

If you run the code now, you will see an empty frame. When you close it, something not quite obvious will happen (or better said, will not happen). The application will not end. Remember that the Frame is just a visual part of application, not application logic – if you do not request application termination when the window closes, your program will still run in the background (look for it in the process list). To avoid this problem, add the following line to the MainFrame constructor:

setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

Before Java2 1.3, you had to register a window listener and then act on the window closing event by stopping the application. Since Java2 1.3, you can specify a simple action that will happen when a window is closed with this shortcut. Other options are HIDE_ON_CLOSE (the default – window is closed but application still runs) and DO_NOTHING_ON_CLOSE (rather strange option that ignores a click on the X button in the upper right corner).

 

Adding ComponentsNow is the time to add some components to the window. In Swing (and the Swing predecessor, AWT) all visual objects are subclasses of Component class. The Composite pattern was applied here to group visual objects into Containers, special components that can contain other components. Containers can specify the order, size and position of embedded components (and this can all be automatically calculated, which is one of the best features of Swing).

JButton is a component class that represents a general purpose button – it can have a text caption or an icon, and can be pressed to invoke an action. Let’s add the button to the frame (note: add imports for javax.swing.* and java.awt.* to the MainFrame source code so that you can use all the components).

When you work with JFrame, you want to put objects into it’s content pane – special container intended to hold the window contents. Obtain the reference to that container with the getContentPane() method.

Feature Rich Universal DataBase Engine

Page 20: Integrated Database Environment With a Single Consistent Interface

Container content = getContentPane();content.add(new JButton("Button 1"));

If you try to add more buttons to the frame, most likely only the last one added will be displayed. That is because the default behavior of JFrame content pane is to display a single component, resized to cover the entire area.

Grouping ComponentsTo put more than one component into a place intended for a single component, group them into a container. JPanel is a general purpose container, that is perfect for grouping a set of components into a “larger” component. So, let’s put the buttons into a JPanel:

JPanel panel=new JPanel();panel.add(new JButton("Button 1"));panel.add(new JButton("Button 2"));panel.add(new JButton("Button 3"));content.add(panel);

Feature Rich Universal DataBase Engine

Page 21: Integrated Database Environment With a Single Consistent Interface

Layout Management Basics

One of the best features of Swing is automatic component positioning and resizing. That is implemented trough a mechanism known as Layout management. Special objects – layout managers – are responsible for sizing, aligning and positioning components. Each container can have a layout manager, and the type of layout manager determines the layout of components in that container. There are several types of layout managers, but the two you will most frequently use are FlowLayout (orders components one after another, without resizing) and BorderLayout (has a central part and four edge areas – component in the central part is resized to take as much space as possible, and components in edge areas are not resized). In the previous examples, you have used both of them. FlowLayout is the default for a JPanel (that is why all three buttons are displayed without resizing), and BorderLayout is default for JFrame content panes (that is why a single component is shown covering the entire area).

Layout for a container is defined using the setLayout method (or usually in the constructor). So, you could change the layout of content pane to FlowLayout and add several components, to see them all on the screen.

The best choice for the window content pane is usually a BorderLayout with a central content part and a bottom status (or button) part. The top part can contain a toolbar, optionally.

Now, let’s combine several components and layouts, and introduce a new component – JTextArea. JTextArea is basically a multiline editor. Initialize the frame content pane explicitly to BorderLayout, put a new JTextArea into the central part and move the button panel below.

Feature Rich Universal DataBase Engine

Page 22: Integrated Database Environment With a Single Consistent Interface

package com.neuri.handsonswing.ch1;

import java.awt.*;import javax.swing.*;

public class MainFrame extends JFrame{   public MainFrame()   {      super("My title");      setSize(300,300);      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      Container content = getContentPane();      content.setLayout(new BorderLayout());      JPanel panel = new JPanel(new FlowLayout());      panel.add(new JButton("Button 1"));      panel.add(new JButton("Button 2"));      panel.add(new JButton("Button 3"));      content.add(panel, BorderLayout.SOUTH);       content.add(new JTextArea(), BorderLayout.CENTER);   }}

Notice that the layouts for content pane and the button panel are explicitly defined. Also notice the last two lines of code – this is the other version of add method, which allows you to specify the way the component is added. In this case, we specify the area of BorderLayout layout manager. Central part is called BorderLayout.CENTER, and other areas are called BorderLayout.NORTH (top), BorderLayout.SOUTH (bottom), BorderLayout.WEST (left) and BorderLayout.EAST (right). If you get confused about this, just remember land-maps from your geography classes.

ScrollingNow, type a few lines of text into the text area – once you type enough lines (or press Enter enough times), the cursor will disappear from the screen. Swing is different from other GUI toolkits, and visual components do not support scrolling unless you tell them to – but, on the other hand, this way you can put scrollbar around almost anything. To enable scrolling, just put the component (or a container with other components) into a JScrollPane – this is a special container that adds scrollbars to it’s content. Change the last line of the previous class to content.add(new JScrollPane(new JTextArea()), BorderLayout.CENTER);to see a scrolling text area inside your window.

Feature Rich Universal DataBase Engine

Page 23: Integrated Database Environment With a Single Consistent Interface

Other Interesting ComponentsExperiment a bit with other components that you will be using often. Try to add the following components in the example frame:

JTextField - a single line text field. For example, the following line will add a text field with 10 spaces for characters to the panel:

JLabel - a simple textual label. Use this component in front of text fields to describe their function.

JComboBox - a drop down menu (optionally editable)

panel=new JPanel(new FlowLayout());panel.add(new JLabel("Enter your name"));panel.add(new JTextField(10));String options[] = new String[]{ "Option 1","Option 2","Option 2" };panel.add(new JComboBox(options));content.add(panel, BorderLayout.NORTH);

Handling Actions and EventsNow that you have learned how to put components on the screen, you will learn how to react to user actions with those components. The central mechanism for this is the Observer pattern, implemented in Swing with event listeners. Components

Feature Rich Universal DataBase Engine

Page 24: Integrated Database Environment With a Single Consistent Interface

publish notifications about events, and event listeners receive these notifications. For example, to execute a code when user presses a button, you should define a listener for the button pressing event and register it with that button.

package com.neuri.handsonswing.ch1;

import java.awt.*;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;

import javax.swing.*;

public class MainFrame extends JFrame{   public MainFrame()   {      super("My title");      setSize(300,300);      setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);      Container content = getContentPane();      content.setLayout(new BorderLayout());      JPanel panel = new JPanel(new FlowLayout());      JButton button1 = new JButton("Button 1");      panel.add(button1);      button1.addActionListener( new MyButtonListener(this));      panel.add(new JButton("Button 2"));      panel.add(new JButton("Button 3"));      content.add(panel, BorderLayout.SOUTH);       content.add(new JScrollPane(new JTextArea()), BorderLayout.CENTER);      panel = new JPanel(new FlowLayout());      panel.add(new JLabel("Enter your name"));      panel.add(new JTextField(10));      String options[] = new String[]{"Option 1","Option 2","Option 2"};      panel.add(new JComboBox(options));      content.add(panel, BorderLayout.NORTH);   }

   private class MyButtonListener implements ActionListener   {      private JFrame parentComponent;      MyButtonListener(JFrame parentComponent)      {         this.parentComponent=parentComponent;      }

      public void actionPerformed(ActionEvent e)       {         JOptionPane.showMessageDialog(parentComponent, "BUTTON PRESSED!");      }

Feature Rich Universal DataBase Engine

Page 25: Integrated Database Environment With a Single Consistent Interface

   }}

In this example, we created an ActionListener and attached it to a button. ActionListener interface has just one method: actionPerformed. That method is called when an action occurs. The event type ActionEvent is the most common in Swing - most components produce an ActionEvent. Components may also produce other events - such as change of the current selection, text or size. For now, you should be most concerned with ActionEvent. In any case, in an IDE that can display methods of a class and look for methods that begin with add and end with Listener (for example, addFocusListener) to see what listener/event types a component supports.

One more interesting thing in this example is usage of class JOptionPane. That class has many utility methods that help you display standardised input dialogs and message dialogs.

This being said, it is time to note that the above example is not written in the style usual for Swing. Since the only usage of a listener is to call a method, it is ofter written as an anonymous inner class.

button1.addActionListener(    new ActionListener()   {      public void actionPerformed(ActionEvent e)       {         JOptionPane.showMessageDialog(MainFrame.this,"BUTTON PRESSED!");      }   });

This way, you do not have to write another class like MyActionListener for every listener - the code is much shorter and (arguably) easier to read. Note the strange notation for the parent component - (MainFrame.this). Since the anonymous action listener instance is a fully-fledged object, using only this would point to that object. MainFrame.this points to the instance of MainFrame that contains the embedded action listener.

For now, just note that there are also other ways of receiving event notification then installing a listener for every object on the screen. For example, the following few lines installs a global listener for the F1 key pressing:

KeyStroke ks=KeyStroke.getKeyStroke(KeyEvent.VK_F1,0);topComponent.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT).put(ks,"HELP");topComponent.getActionMap().put("HELP",   new AbstractAction()   {      public void actionPerformed(ActionEvent evt)      {         // do something here, display a dialog or whatever

Feature Rich Universal DataBase Engine

Page 26: Integrated Database Environment With a Single Consistent Interface

      }   });

Java

Java was conceived by James Gosling,

Patrick Naughton, Chriswarth, Ed Frank and Mike

Sheridan at Sun Micro Systems incorporation in 1991.

It took 18 months to develop e the first working version.

This language was initially called “OAK”, but was

renamed “JAVA” in 1995. Before the initial

implementation of OAK in 1992 and the public

announcement of Java in 1995, many more contributed

to the design and evolution of the language.

Java is a powerful but lean object oriented

programming language .It has generated a lot of

excitement because it makes it possible to program for

Internet by creating applets, programs that can be

embedded in web page. The context of an applet is

limited only by one’s imagination. For example, an

applet can be animation with sound, an interactive

game or a ticker tape with constantly updated stock

prices. Applets can be just little decorations to liven up

web page, or they can be serious applications like word

processors or spreadsheet.

Feature Rich Universal DataBase Engine

Page 27: Integrated Database Environment With a Single Consistent Interface

But Java is more than a programming language

for writing applets. It is being used more and more for

writing standalone applications as well. It is becoming

so popular that many people believe it will become

standard language for both general purpose and

Internet programming.

There are many buzzwords associated with

Java, but because of its spectacular growth in

popularity, a new buzzword has appeared ubiquitous.

Indeed, all indications are that it will soon be

everywhere.

Java builds on the strength of C++. It has taken

the best features of C++ and discarded the more

problematic and error prone parts. To this lean core, it

has added garbage collection (automatic memory

management), multi-threading (the capacity for one

program to do more than one thing at a time), security

capabilities. The result is that Java is simple, elegant,

powerful and easy to use.

Java is actually a platform consisting of three

components.

Java programming language.

Java library of classes and interfaces.

Java virtual Machine.

There are many reasons why java is preferable and they are described as follows.

Feature Rich Universal DataBase Engine

Page 28: Integrated Database Environment With a Single Consistent Interface

Simple

Java was designed to be easy for the professional programmer to learn and use

effectively. Java will be even easy if we already thorough in the concept of object

oriented. Some of confusing concepts are left out of java or implemented in a cleaner,

more approachable manner.

Object Oriented

The Java programming language is object

oriented, which makes program design focus on what

you are dealing with rather than on how you are going

to do something. This makes it more useful for

programming in sophisticated projects because one can

break the things down into understandable components.

A big benefit is that these components can then be

reused.

Object oriented languages use the paradigm of

classes. In simple term, a class includes both the data

and the functions to operate on the data. You can

create an instance of a class, also called an object,

which will have all the data members and functionality

of its class. Because of this, you can think of a class as

being like template, with each object being a specific

instance of a particular type of class.

The class paradigm allows one to encapsulate

data so that those using the data cannot see specific

data values and function implementation.

Encapsulation makes it possible to make the changes in

code without breaking other programs that use that

code. If for example the implementation of a function is

changed, the change is

Feature Rich Universal DataBase Engine

Page 29: Integrated Database Environment With a Single Consistent Interface

invisible to the another programmer who

invokes that function, and it does not affect his/her

program, except hopefully to improve it.

Java includes inheritance, or the ability to

derive new classes from existing classes. The derived

class, also called a subclass, inherits all the data and

functions of the existing class, referred to as the parent

class. A subclass can add new data members to those

inherited from the parent class. As far as methods are

concerned, the subclass can reuse the inherited

methods, as it is, change them, and/or add its own new

methods.

Portable

One of the biggest advantages Java offers is that

it is portable. An application written in Java will run

on all the major platforms. Any computer with a Java

based browser can run the applications or applets

written in the Java programming language. A

programmer no longer has to write one program to run

on a Macintosh, another program to run on a Windows

machine, still another to run on UNIX machine, and so

on. In other words, with Java, developers write their

programs only once. The virtual machine is what gives

Java is cross platform capabilities. Rather than being

compiled into machine language, which is different for

each operating systems and computer architecture,

Java code is compiled into byte codes.

With other languages, the program code is

compiled into a language the computer can understand.

The problem is that other computers with different

machine instruction set cannot understand that

Feature Rich Universal DataBase Engine

Page 30: Integrated Database Environment With a Single Consistent Interface

language. Java code on the other hand is compiled into

byte code rather than a machine language. These byte

code go to the Java virtual machine, which executes

them directly or translates them into the language that

is understood by the machine running it.

In Summary, these means that with the JDBC

API extending Java, a programmer writing Java code

can access all the major relational databases on any

platform that supports the Java virtual machine.

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. Thus, the

ability to create robust programs were given a high priority in the design of java.

However, it also checks our code at run time. In fact, many space hard-to-down bugs

that often turn up in hard-to reproduce run time situations are simply impossible to

create in java.

To better understand how java is robust, two of the reasons are mainly

considered for program failure memory management mistakes and mishandling

exceptional conditions. Memory management can be a difficult, tedious task in

traditional programming environments. Java virtually eliminates these problems by

managing memory allocation and deal location.

Exceptional conditions in traditional environment often arise in situations such

as division by zero or “ file not found” and they must be managed with clumsy and

hard-to-read constructs. Java helps in this area by providing object-oriented exception

handling.

Feature Rich Universal DataBase Engine

Page 31: Integrated Database Environment With a Single Consistent Interface

Security

Every time that we download a “normal” program, we 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. Even so, most users

still worried about the possibilities of infecting their systems with a virus.

In addition to viruses, 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, by searching the contents of our

computer’s local file system. Java answers both of this concern by providing a

“firewall” between a networked application and our computer.

Multithreaded

Java was designed to meet the real-world requirement of creating interactive,

networked programs. To accomplish this, java supports multithreaded programming,

which allows us to write programs that do many things simultaneously. The java run-

time system comes with an elegant yet sophisticated solution for multi process

synchronization that enables us to construct smoothly running interactive systems.

Interpreted and high performance

Java enables the creation of cross-platform programs by compiling into an

intermediate representation called java byte code. This code can be interpreted on any

system tat provides a java Virtual Machine. Most previous attempts at cross-platform

solutions have done so at the expense of performance. Other interpreted system, such

as BASIC, Tcl and PEAL, suffer from almost insurmountable performance deficits.

Java, however, was designed to perform well on very low power CPUs.

Feature Rich Universal DataBase Engine

Page 32: Integrated Database Environment With a Single Consistent Interface

Distributed

Java is built with network communications in mind. It has a comprehensive

library of routines for dealing with network protocols such as TCP/IP, HTTP and

FTP. As a result, Java application can open and access objects across the Internets

with the same ease that programmers normally expects while accessing a local file

system. You don’t have to worry about implementing the details of network yourself;

Java comes with everything needed for truly distributed computing.

Dynamic

Fundamentally, distributed computing environment must be dynamic Java was

designed to adapt in a constantly evolving environment. It is capable of incorporating

new functionality regard less of where that functionality comes from-the local

computer system, the local and wide area networks, and the internet are all potential

contributors.

Garbage Collection

Automatically takes care of allocating and de-

allocating memory, a huge potential source of errors. If

an object is no longer being used (has no references to

it), then it is automatically removed from memory, or

“Garbage Collected”. Programmers don’t have to

keep track of what has been allocated and de-allocated

them, which makes their job a lot easier, but more

importantly it stops memory leaks.

No Pointers

Eliminates big source errors. By using object

references instead of memory pointers, problems with

pointer arithmetic are eliminated, and problems with

Feature Rich Universal DataBase Engine

Page 33: Integrated Database Environment With a Single Consistent Interface

inadvertently accessing the wrong memory address are

greatly reduced.

Simplicity

Makes Java easier to learn and use correctly.

Java keeps it simple by having just one way to do

something instead of having several alternatives, as in

some languages. Java also stays lean by not including

multiple inheritance, which eliminates the errors and

ambiguity that arise when you create a subclass that

inherits from two or more classes.

To replace capabilities, multiple inheritance

provides, Java lets you add functionality to a class

through the use of interfaces.

Feature Rich Universal DataBase Engine

Page 34: Integrated Database Environment With a Single Consistent Interface

JDBC

JDBC is a Java TM API for executing SQL statements. It consists of a set of

classes and interfaces that are written in the Java programming language that makes it

easy to sent SQL statements to virtually any relational database. In other words, with

the JDBC API, it isn’t necessary to write one program to access a Sybase database,

any other program to access an Oracle database, another to access Informix database,

and so on. One can write a single program using JDBC API and the program will be

able to send SQL statements to appropriate database. And with a program written in

Java, one also does not to worry about writing different programs to run on different

platforms. The combination of Java and JDBC lets a programmer writes it once and

run it anywhere.

Java, being robust, secure, easy to understand, easy to use, and automatically

downloadable on a network, is an excellent language basis for database applications.

JDBC is the mechanism for Java applications to talk to variety of different databases.

JDBC extends what you can do in Java. For example, with Java and JDBC API it is

possible to publish a web page containing an applet that uses information obtained

from a remote database. With more and more programmers using Java the need for

easy database access from Java is continuing to grow.

What does JDBC do?

Simply put, JDBC makes it possible to do three things:

Establishes the connection to databases.

Send SQL statements.

Process the results.

JDBC is a low-level API and a base for Higher-level API. JDBC is a low-level

interface, which means that it is used to invoke SQL commands directly .It works

very well in this capacity and is easy to use than any other database connectivity

Feature Rich Universal DataBase Engine

Page 35: Integrated Database Environment With a Single Consistent Interface

API’s. But it was designed also to be a base upon which to build higher-level

interfaces and tools. A higher-level interface is user-friendly using a more

understandable or more convenient API that is translated behind the scenes into a

low-level interface such as JDBC.

JDBC and ODBC:

At this point, Microsoft’s ODBC (open database connectivity) API is probably

the most widely used interface for accessing relational databases. It offers the ability

to connect to almost all databases on all most platforms. So why not just use ODBC

from Java? The answer is that you can use ODBC from Java, but this is best done

with the help of JDBC in the form of JDBC-ODBC Bridge. “Why do you need

JDBC?”

There are several answers to this question:

ODBC is not appropriate for direct use from Java because it uses a c

interface. Calls from Java to native C code have a number of drawbacks in

the security, implementation, robust ness and automatic portability of

applications.

A literal translation of the ODBC C API into a Java API would not be

desirable. For example, Java has no pointers and ODBC makes copious

use of them. You can think of JDBC as ODBC translated into object

oriented interface that is natural for Java programmers.

ODBC is hard to learn. It mixes simple and advanced features together and

it has complex options even for simple queries. JDBC on the other hand is

designed for a wide range of programmers and kept simple things simple.

The big difference is that JDBC builds on and reinforces the style and

virtues of Java and of course, it is easy to use.

Feature Rich Universal DataBase Engine

Page 36: Integrated Database Environment With a Single Consistent Interface

The JDBC API supports both two-tier and three-tier models for database

access. The JDBC API is a natural choice for Java developers because it

offers easy database access for Java applications and applets.

Java Soft provides three JDBC product components as part of the Java

Developer’s Kit (JDK).

JDBC Driver manager.

JDBC driver test suit, and

JDBC-ODBC bridge.

The JDBC driver manager is the backbone of JDBC architecture. It actually

is quite small and simple, its primary function is to connect Java applications to the

correct JDBC driver and then get out of the way.

The JDBC driver test suit provides some confidence that JDBC drivers will

run your program. It tests that a JDBC driver implements all of the JDBC classes and

methods and that it provides the Entry Level SQL functionality required for JDBC

compliance.

The JDBC-ODBC Bridge allows ODBC drivers to be used as JDBC drivers. It

was implemented as way to get off the ground quickly, and long term will provide a

way to access some of the less popular DBMS if JDBC are not implemented.

Feature Rich Universal DataBase Engine

Page 37: Integrated Database Environment With a Single Consistent Interface

Oracle

Oracle is a relational database management system, which organizes data in the

form of tables. Oracle is one of many database servers based on RDBMS model,

which manages a seer of data that attends three specific things-data structures, data

integrity and data manipulation.

With oracle cooperative server technology we can realize the benefits of open,

relational systems for all the applications. Oracle makes efficient use of all systems

resources, on all hardware architecture; to deliver unmatched performance, price

performance and scalability. Any DBMS to be called as RDBMS has to satisfy

Dr.E.F.Codd’s rules.

Features of Oracle

Portable

The Oracle RDBMS is available on wide range of platforms ranging from PCs

to super computers and as a multi user loadable module for Novel NetWare, if you

develop application on system you can run the same application on other systems

without any modifications.

Compatible

Oracle commands can be used for communicating with IBM DB2 mainframe

RDBMS that is different from Oracle, that is Oracle compatible with DB2. Oracle

RDBMS is a high performance fault tolerant DBMS, which is specially designed for

online transaction processing and for handling large database applications.

Feature Rich Universal DataBase Engine

Page 38: Integrated Database Environment With a Single Consistent Interface

Multithreaded Server Architecture

Oracle adaptable multithreaded server architecture delivers scalable high

performance for very large number of users on all hardware architecture including

symmetric multiprocessors (sumps) and loosely coupled multiprocessors.

Performance is achieved by eliminating CPU, I/O, memory and operating system

bottlenecks and by optimizing the Oracle DBMS server code to eliminate all internal

bottlenecks.

Oracle has become the most popular RDBMS in the market because of its ease

of use

Client/server architecture.

Data independence.

Ensuring data integrity and data security.

Managing data concurrency.

Parallel processing support for speed up data entry and online

transaction processing used for applications.

DB procedures, functions and packages.

Dr.E.F.Codd’s Rules

These rules are used for valuating a product to be called as relational database

management systems. Out of 12 rules, a RDBMS product should satisfy at least 8

rules + rule called rule 0 that must be satisfied.

RULE 0 : Foundation Rule

For any system to be advertised as, or claimed to be relational DBMS

should manage database with in it self, with out using an external language.

RULE 1 : Information Rule

All information in relational database is represented at logical level in

only one way as values in tables.

Feature Rich Universal DataBase Engine

Page 39: Integrated Database Environment With a Single Consistent Interface

RULE 2 : Guaranteed Access

Each and every data in a relational database is guaranteed to be

logically accessibility by using to a combination of table name, primary key

value and column name

RULE 3 : Systematic Treatment of Null Values

Null values are supported for representing missing information and

inapplicable information. They must be handled in systematic way,

independent of data types.

RULE 4 : Dynamic Online Catalog based Relation Model

The database description is represented at the logical level in the same

way as ordinary data so that authorized users can apply the same relational

language to its interrogation as they do to the regular data.

RULE 5 : Comprehensive Data Sub Language

A relational system may support several languages and various models

of terminal use. However there must be one language whose statement can

express all of the following:

Data Definitions, View Definitions, Data Manipulations, Integrity,

Constraints, Authorization and transaction boundaries.

RULE 6 : View Updating

Any view that is theoretical can be updatable if changes can be made

to the tables that effect the desired changes in the view.

RULE 7 : High level Update, Insert and Delete

The capability of handling a base relational or derived relational as a

single operand applies not only retrieval of data also to its insertion, updating,

and deletion.

Feature Rich Universal DataBase Engine

Page 40: Integrated Database Environment With a Single Consistent Interface

RULE 8 : Physical Data Independence

Application program and terminal activities remain logically

unimpaired whenever any changes are made in either storage representation or

access method.

RULE 9 : Logical Data Independence

Application programs and terminal activities remain logically

unimpaired whenever any changes are made in either storage representation or

access methods.

RULE 10 : Integrity Independence

Integrity constraints specific to particular database must be definable in

the relational data stored in the catalog, not in application program.

RULE 11 : Distributed Indepandence

Whether or not a system support database distribution, it must have a

data sub-language that can support distributed databases without changing the

application program.

RULE 12 : Non Sub-Version:

If a relational system has low level language, that low language cannot

use to subversion or by pass the integrity rules and constraints expressed in the

higher level relational language.

Feature Rich Universal DataBase Engine

Page 41: Integrated Database Environment With a Single Consistent Interface

Oracle supports the following Codd’s Rules

Rule 1: Information Rule (Representation of information)-YES.

Rule 2: Guaranteed Access-YES.

Rule 3: Systematic treatment of Null values-YES.

Rule 4: Dynamic on-line catalog-based Relational Model-YES.

Rule 5: Comprehensive data sub language-YES.

Rule 6: View Updating-PARTIAL.

Rule 7: High-level Update, Insert and Delete-YES.

Rule 8: Physical data Independence-PARTIAL.

Rule 9: Logical data Independence-PARTIAL.

Rule 10: Integrity Independence-PARTIAL.

Rule 11: Distributed Independence-YES.

Rule 12: Non-subversion-YES.

Feature Rich Universal DataBase Engine

Page 42: Integrated Database Environment With a Single Consistent Interface

GENERAL CONCEPTS OF JFC-SwingGUI programming with Java

Java provides a set of user interface components

The set is the same across Unix, Windows and the Macintosh

The user interface components can be used for applets and for applications

The set allows cross-platform applications and applets to be built

Evolution of Java GUI programming The AWT (Abstract Window Toolkit) has been present in all versions of Java

The AWT objects are built above native code objects, giving a native look-

and-feel

The AWT objects are a least common denominator of all platforms

The Swing objects are a separate library for JDK 1.1

The Swing objects are in pure Java, and have the same look-and-feel on all

platforms

The L&F of Swing objects can be customised to particular styles

In JDK 1.2, the Swing objects are part of the Java Foundation Classes

The JFC objects will provide a superset of each platform's objects

The AWT objects will decrease in importance over time

Applet vs Application

An application starts from main() in a subclass of Frame An applet has as toplevel a subclass of Applet, using methods

o init() o start() o stop()

Placing initialisation code in the constructors makes it relatively easy to write applets and applications sharing code.

Feature Rich Universal DataBase Engine

Page 43: Integrated Database Environment With a Single Consistent Interface

AWT Hierarchy

``Primitive'' objects are directly derived from Component

LayoutManager is used for geometry management

LayoutManager2 fixes some deficiencies in LayoutManager (from JDK 1.1

on)

AWTEvent encodes all the event information

ComponentPeer objects are used to give the native implementation, and

should be ignored most of the time

AWT Primitive Components

The main ``primitive'' objects derived from Component are

These are all in package java.awt.

Feature Rich Universal DataBase Engine

Page 44: Integrated Database Environment With a Single Consistent Interface

Swing Primitive Components These mirror the AWT components:

There are additional components as well

In general, to each AWT component is a Swing component

As much as possible, each Swing component has the same methods and

behaviour as its corresponding AWT component

Container Components Container objects are derived from Component. The main ones derived from that are

Dialog FileDialog Frame Panel Window

MenuComponents Menus are implemented by subclassing Menu Component which is derived from Object

CheckboxMenuItem Menu MenuBar MenuItem

Layout Objects Layout objects derive from Object and are used for geometry management

BorderLayout

Feature Rich Universal DataBase Engine

Page 45: Integrated Database Environment With a Single Consistent Interface

CardLayout FlowLayout GridLayout GridBagLayout

COMPONENTSComponent Objects

Component has a number of methods inherited by all objects derived from it.

Some methods set state

o setEnabled() (replaces enable()/disable())

o setVisible() (replaces hide()/show())

o setBackground(Color)

o setFont(Font)

Other methods are informational

o boolean isEnabled()

o boolean isShowing()

o Color getBackground()

Label

Label is single-line only (stuff after \n ignored)

It is left-to-right only

There are three constructors for Label

Label lab1 = new Label();

Label lab2 = new Label("Hello World");

Label lab3 = new Label("Hello", Label.RIGHT);

Label (2)

Inherited methods allow

label.setVisible(false);

Feature Rich Universal DataBase Engine

Page 46: Integrated Database Environment With a Single Consistent Interface

if (label.isShowing()) ...

Major new methods are

label.setText("Hello");

label.setAlignment(Label.LEFT);

String s = label.getText();

Hello World

Hello World using a Label in a Frame is

import java.awt.*;

public class Hello extends Frame {

public static void main(String argv[])

{

new Hello();

}

Hello() {

Label hello = new Label("Hello World");

add(hello, "Center");

setSize(200, 200);

setVisible(true);

}

}

JLabel

JLabel is the Swing counterpart to Label

It does almost the same as Label (newline shown as VT)

It can show a string and/or image

Just replace Label by JLabel throughout

Frame

Feature Rich Universal DataBase Engine

Page 47: Integrated Database Environment With a Single Consistent Interface

An AWT application will generally subclass from Frame

An application can have multiple Frames - each one has a toplevel window

There are two constructors

Frame();

Frame(String title);

Major methods are

setIconImage(Image)

setMenuBar(MenuBar)

setTitle(String)

(setCursor() has been moved to Component)

JFrame

JFrame is the Swing equivalent of Frame

It adds double buffering to avoid flickering during drawing

It has a slightly different interface to geometry management

Hello World using Swing

import com.sun.java.swing.*;

public class JHello extends JFrame {

public static void main(String argv[]) {

new JHello(); }

JHello() {JLabel hello = new JLabel("Hello World");getContentPane().add(hello, "Center");

Feature Rich Universal DataBase Engine

Page 48: Integrated Database Environment With a Single Consistent Interface

setSize(200, 200); setVisible(true); }}

Button

Button is implemented in Motif using a native PushButton

Actions are invoked on button click only

getClickCount() is available to distinguish between double clicks on mouse events

There are two constructors for Button

Button btn1 = new Button();Button btn2 = new Button("Hello");

There are methods to get and set the label

btn1.setLabel("Hi");String s = btn1.getLabel();

JButton

JButton is the Swing equivalent of Button

A JButton can show a string and/or image

There is much extended control and behaviour

set/getLabel() has been replaced by set/getText()

EVENTS

AWT events

Event model in Java 1.0 is poor s/w engineering, based on class Event In Java 1.1 it changes to a new model called AWTEvent This event model is unchanged for Java 1.2 Events are handled by listeners, not by subclasses of GUI objects

AWT Event classes

Feature Rich Universal DataBase Engine

Page 49: Integrated Database Environment With a Single Consistent Interface

The class AWTEvent has subclasses: ComponentEvent FocusEvent KeyEvent MouseEvent WindowEvent ActionEvent AdjustmentEvent ItemEvent

AWT Event ids

Some of these classes have an id value to distinguish between them

KeyEvent: KEY_PRESSED, KEY_RELEASED, KEY_TYPED

ComponentEvent: COMPONENT_MOVED, COMPONENT_RESIZED,

COMPONENT_SHOWN, COMPONENT_HIDDEN

MouseEvent: MOUSE_CLICKED, MOUSE_DRAGGED,

MOUSE_PRESSED, etc

Triggering events

Events are posted by user actions (or may be done programmatically)

ActionEvent

o click on Button

o double-click on List item

o click on MenuItem

o press <enter> key in TextField

ItemEvent

o select an item in a Choice box

o Checkbox

o select or deselect a List item

Listeners

Listeners are objects that handle events (not the GUI Components any more) ActionEvent handled by ActionListener KeyEvent handled by KeyListener Mouse motion events handled by MouseMotionListener (optimisation)

Feature Rich Universal DataBase Engine

Page 50: Integrated Database Environment With a Single Consistent Interface

Other Mouse events handled by MouseListener

Listeners as interfaces

Listeners are defined as interfaces and must be implemented by the application public interface ActionListener extends EventListener { public void actionPerformed(ActionEvent e);}

public interface MouseListener extends EventListener { public void mouseClicked(MouseEvent e); public void mousePressed(MouseEvent e); public void mouseReleased(MouseEvent e); public void mouseEntered(MouseEvent e); public void mouseExited(MouseEvent e);}

Registering listeners

Each GUI object generates certain events

For each class of AWTEvent there is an add<Event>Listener

e.g. For Button, List, MenuItem and TextField there is a method

addActionListener()

e.g. For Choice Checkbox and List there is a method addItemListener()

Simple Delegation program (1)

import java.awt.Button;import java.awt.Label;import java.awt.Frame;import java.awt.event.ActionListener;

public class DelegateDemo extends Frame { public static void main(String argv[]) {

new DelegateDemo().setVisible(true); }

public DelegateDemo() {

Feature Rich Universal DataBase Engine

Page 51: Integrated Database Environment With a Single Consistent Interface

// create the GUI objectsButton left = new Button("Left");Button right = new Button("Right");Label label = new Label(" ", Label.CENTER);

// set their geometryadd(left, "West");add(right, "East");add(label, "Center");pack();

Simple Delegation program (2)

// continue constructor// create a listener and add it to each ButtonSimpleListener simple =

new SimpleListener(label);left.addActionListener(simple);right.addActionListener(simple);

}}

Simple Delegation program (3)

/** * A listener object that is invoked when a Button is activated * It finds the Button's label and sets it in a Label */class SimpleListener implements ActionListener {

private Label label;

public SimpleListener(Label l) {

// the listener needs to know the Label it will act on label = l;

}

public void actionPerformed(java.awt.event.ActionEvent e) {// get the label showing in whichever Button was pressedString name = e.getActionCommand();

// set this in the Label objectlabel.setText(name);

}}

Feature Rich Universal DataBase Engine

Page 52: Integrated Database Environment With a Single Consistent Interface

Some variations

The Frame is often used as a listener for all components. This is probably bad practice if done too much

Inner classes are contained within a class, and are visible only within that class. Using an inner class for a listener can sometimes be tidier

Anonymous classes can be used as listeners, at the expense of readability

Motion Tracking (1)

This application tracks movement and resizing of the toplevel Frame around the

screen

It uses the ComponentEvent class and the ComponentListener interface

ComponentListener defines methods

public void componentResized(ComponentEvent e);

public void componentMoved(ComponentEvent e);

public void componentShown(ComponentEvent e);

public void componentHidden(ComponentEvent e);

Motion Tracking (2)

import java.awt.*;

public class TrackResize extends Frame { public static void main(String argv[]) {

new TrackResize().setVisible(true); }

public TrackResize() {Label label = new Label();add(label);setSize(300, 100);

addComponentListener(new Tracker(label)); }}

Motion Tracking (3)

class Tracker implements ComponentListener { private Label label;

Feature Rich Universal DataBase Engine

Page 53: Integrated Database Environment With a Single Consistent Interface

Tracker(Label l) {label = l;

} public void componentHidden(ComponentEvent e) {

// empty }

public void componentMoved(ComponentEvent e) {showGeometry(e);

}

public void componentResized(ComponentEvent e) {showGeometry(e);

}

public void componentShown(ComponentEvent e) {// empty

}

Motion Tracking (4)

// Tracker continues private void showGeometry(ComponentEvent e) {

Component c = e.getComponent();Dimension d = c.getSize();Point p = c.getLocation();

label.setText("Position: (" + p.x + "," + p.y + ") Size: )" + d.width + "," + d.height + ")");

}}

Changing key values (1)

import java.awt.*;import java.awt.event.*;

public class MapKey extends Frame { public static void main(String argv[]) {

new MapKey().setVisible(true); }

public MapKey() {

Feature Rich Universal DataBase Engine

Page 54: Integrated Database Environment With a Single Consistent Interface

TextField text = new TextField(20);add(text);pack();

text.addKeyListener(new ToUpper()); }}

Changing key values (2)

class ToUpper implements KeyListener { public void keyTyped(KeyEvent e) {

// empty }

public void keyPressed(KeyEvent e) {e.setModifiers(Event.SHIFT_MASK);

} public void keyReleased(KeyEvent e) {

// empty }}

Consuming events

Events may need to be ``blocked'' from reaching objects sometimes

o In password entry, keystrokes need to be caught by the application but

not reach the Text object for display

o A GUI builder might use mouse clicks to select objects such as Button,

but not activate the Button

The delegation model allows this for key and mouse events

Events are discarded by calling the method AWTEvent.consume()

Consuming events

This key listener discards non-alphabetic events: public class Alpha implements KeyListener {

public void keyPressed(KeyEvent e) { if (! Character.isLetter(e.getKeyChar())) { Toolkit.getDefaultToolkit().beep(); e.consume(); } }

Feature Rich Universal DataBase Engine

Page 55: Integrated Database Environment With a Single Consistent Interface

public void keyReleased(KeyEvent e) { // empty }

public void keyTyped(KeyEvent e) { // empty }}

Generating Events

Events may be created and placed on the event queue for applications The event queue is found from

Toolkit.getDefaultToolkit().getSystemEventQueue() The event queue is not accessible yet from applets (need applet queue) Adding semantic events to queue does nothing to native GUI objects, and only

makes the application state inconsistent

Adding input events has no effect as yet, but may in the future Adding new event types to the queue may be done

Generating Events of a new Class

New event classes can be subclassed from AWTEvent

Possible values for id field must be greater than

AWTEvent.RESERVED_MAX_ID or event handling breaks

A subclass of Component must be defined to handle the new event type

The subclass will ignore events by default: make it receive the new event by

enableEvents(0)

FileDialog

Implemented by Motif FileSelectionDialog

FileDialog has two constructors

FileDialog(Frame parent, String title);FileDialog(Frame parent, String title,int mode);

The mode can be LOAD or SAVE - which affects the labelling of the dialog

Major methods are

Feature Rich Universal DataBase Engine

Page 56: Integrated Database Environment With a Single Consistent Interface

setDirectory(String) // sets dirMasksetFile(String)setFilenameFilter(FilenameFilter) - still does nothing

FileDialog (2)

method setVisible(true) is modal. When it terminates the file selected can be found

FileDialog fd = new FileDialog();fd.setVisible(true);System.out.println("Selected: " +

fd.getFile());

No event processing is required by the application.

FileDialog Parent

Creation of a FileDialog requires a Frame parent. If this is done from a Button then the Frame has to be found by walking up the parent tree from the Button: class FileOpen implements ActionListener { public void actionPerformed(ActionEvent e) { Object fr = e.getComponent();

while (fr != null && !(fr instanceof Frame)) fr = ((Component)

fr).getParent(); new FileDialog((Frame) fr, "Open"); // etc }}

JFileChooser

JFileChooser is the Swing alternative

GEOMETRY

Panel

Panel is a general purpose container used to give geometric structure to an application

Panels can be nested

Geometry

Feature Rich Universal DataBase Engine

Page 57: Integrated Database Environment With a Single Consistent Interface

Geometry controls the initial placement of objects on the screen, and their

behaviour under internal or external resizing

Under X, to see clearer what is happening in examples, set the resource

*borderWidth: 3 in your resource files

Geometry is identical for AWT and Swing components

Size Calculations

minimumSize() is set by the object's native implementation peer for AWT

objects e.g. MButtonPeer sets minimumSize() as label width + 14, label height

+ 8.

For Swing objects, it is set by its UI component (which is the Java equivalent

to the peer)

preferredSize() usually defaults to minimumSize()

Geometry Calculations

Changing the preferred size of an object does not change its size, or trigger any

geometry negotiation e.g. resetting the label of a Button does not change the size

Changing the preferred size of an object automatically invalidates it.

To force a size recalculation for invalid children of a Container call layout() on the

Container.

This will force a resize each time the label is reset:

class AutoResizeButton extends Button {

public void setLabel(String name) {

super.setLabel(name);

getParent().layout();

}

}

Insets and Layout Objects

An inset gives a top, bottom, left and right border within which a Container

lays out its contents.

Insets should probably be treated as readonly

Feature Rich Universal DataBase Engine

Page 58: Integrated Database Environment With a Single Consistent Interface

Geometry layout is done by an associated Layout object

Layout objects include

BorderLayout - NSEW layout

FlowLayout - left-to-right with overflow

GridLayout - regular rectangular grid

GridBagLayout - general gridded layout

CardLayout allows ``flipping'' through a set of ``cards''

BorderLayout

Objects are added to the "North", "South", "West", "East" or "Center"

Safer programs may use BorderLayout.NORTH, etc (compiler catches errors)

This is the default layout for Frame

An example program is

BorderLayout (2)

import java.awt.*;

class TestBorderLayout extends Frame { TestBorderLayout() { add(new PushButton("Push Me W", "West")); add(new PushButton("Push Me E"), "East"); add(new PushButton("Push Me S"), "South"); add(new PushButton("Push Me N"), "North"); setSize(400, 200); setVisible(true); }}

Feature Rich Universal DataBase Engine

Page 59: Integrated Database Environment With a Single Consistent Interface

BorderLayout (3)

If there is a North component it stretches the full width (less the inset's left and

right).

The height of the North component is its preferredSize().height.

If there is a South component it stretches the full width (less the inset's left and

right), with height its preferredSize.height().

If there is a West component it fills the vertical space after the inset's top and

bottom and the heights of the North and South components.

The width of the West component is its preferredSize.width().

Similar for the East component.

The Center component is forced to fill the remaining space

FlowLayout

Install this by setLayout(new FlowLayout())

Elements are laid out from left to right (centered), with overflow onto the next

row

An example is

FlowLayout (2)

TestFlowLayout() {

setLayout(new FlowLayout());

add(new Button("Push Me 1"));add(new Button("Push Me 2"));add(new Button("Push Me 3"));add(new Button("Push Me 4"));setSize(400, 100);setVisible(true);

}

FlowLayout (3)

Feature Rich Universal DataBase Engine

Page 60: Integrated Database Environment With a Single Consistent Interface

The same layout after resizing

GridLayout

Gridlayout is a rectangular grid each of the same size

There are two constructors

GridLayout(int rows, int cols)

GridLayout(int rows, int cols,

int hgap, int vgap)

Elements are added by rows

GridLayout (2)

GridLayout (3)

TestGridLayout() {

setLayout(new GridLayout(2, 2));

add new Button("Push Me 1"));

Feature Rich Universal DataBase Engine

Page 61: Integrated Database Environment With a Single Consistent Interface

add(new Button("Push Me 2"));add(new Button("Push Me 3"));add(new Button("Push Me 4"));setSize(400, 200);setVisible(true);

}

GridBagLayout

A GridBagLayout allows arbitrary gridded arrangements Each component managed by a GridBagLayout has an associated GridBagLayoutConstraint to control it

GridBagLayout gridbag = new GridBagLayout();

Button btn = new Button("Hello");GridBagConstraints c =

new GridBagConstraints();// set values in c ...gridbag.setConstraints(btn, c);A GridBagConstraints can be reused or changed for many objects (it is copied on each setConstraints())

GridBagLayout: Direction of Addition

The GridBagConstraints gridx and gridy control placement of objects

gridx and gridy can set absolute positions from (0,0) in the topright corner

If gridx == RELATIVE add in row order i.e. to the right of the last component or in

the next row if it was the last of the row

If gridy == RELATIVE add in column order

The default (both RELATIVE) is row order

The direction can be changed for each object

GridBagLayout: Direction of Addition (2)

Feature Rich Universal DataBase Engine

Page 62: Integrated Database Environment With a Single Consistent Interface

GridBagLayout: Direction of Addition (3)

import java.awt.*;

public class GridBagDirection extends Frame {

Button btn1, btn2, btn3,

btn4, btn5, btn6;

GridBagLayout gridbag;

GridBagConstraints c;

public static void main(String argv[])

{

new GridBagDirection();

}

GridBagLayout: Direction of Addition (4)

void init() {

gridbag = new GridBagLayout();

setLayout(gridbag);

c = new GridBagConstraints();

c.weightx = 1.0;

c.fill = GridBagConstraints.BOTH;

Feature Rich Universal DataBase Engine

Page 63: Integrated Database Environment With a Single Consistent Interface

makeButtons();

}

GridBagLayout: Direction of Addition (5)

void makeButtons() {

btn1 = new Button("Push Me 1"); add(btn1);

btn2 = new Button("Push Me 2"); add(btn2);

btn3 = new Button("Push Me 3"); add(btn3);

btn4 = new Button("Push Me 4"); add(btn4);

btn5 = new Button("Push Me 5"); add(btn5);

btn6 = new Button("Push Me 6"); add(btn6);

}

GridBagLayout: Direction of Addition (6)

GridBagDirection()

{

init();

gridbag.setConstraints(btn1, c);

// btn2 below btn1

c.gridx = 0;

c.gridy = GridBagConstraints.RELATIVE;

gridbag.setConstraints(btn2, c);

GridBagLayout: Direction of Addition (7)

// btn3 right of btn2

c.gridx = GridBagConstraints.RELATIVE;

c.gridy = 1;

Feature Rich Universal DataBase Engine

Page 64: Integrated Database Environment With a Single Consistent Interface

gridbag.setConstraints(btn3, c);

// btn4 below btn3

c.gridx = 1;

c.gridy = GridBagConstraints.RELATIVE;

gridbag.setConstraints(btn4, c);

GridBagLayout: Direction of Addition (8)

// btn5 right of btn4

c.gridx = GridBagConstraints.RELATIVE;

c.gridy = 2;

gridbag.setConstraints(btn5, c);

// btn6 below btn5

c.gridx = 2;

c.gridy = 3; // absolute, for variety

gridbag.setConstraints(btn6, c);

setSize(400, 200);

setVisible(true);

}

GridBagLayout: Cell Size Requests

Each component occupies one horizontal cell and one vertical cell by default

gridwidth and gridheight of GridBagConstraints can be set to alter this

A gridwidth value of REMAINDER makes this the last in the row

A gridheight value of REMAINDER makes this the last in the column

GridBagLayout: Multiple Rows

Feature Rich Universal DataBase Engine

Page 65: Integrated Database Environment With a Single Consistent Interface

GridBagLayout: Multiple Rows (2)

GridBagMultiRow()

{

GridBagLayout gridbag =

new GridBagLayout();

setLayout(gridbag);

GridBagConstraints c =

new GridBagConstraints();

c.weightx = 1.0;

c.fill = GridBagConstraints.BOTH;

// three in one row

gridbag.setConstraints(btn1, c);

gridbag.setConstraints(btn2, c);

c.gridwidth = GridBagConstraints.REMAINDER;

gridbag.setConstraints(btn3, c);

GridBagLayout: Multiple Rows (3)

// two in one row

c.gridwidth = 1;

gridbag.setConstraints(btn4, c);

c.gridwidth = GridBagConstraints.REMAINDER;

gridbag.setConstraints(btn5, c);

Feature Rich Universal DataBase Engine

Page 66: Integrated Database Environment With a Single Consistent Interface

// row by itself

c.gridwidth = GridBagConstraints.REMAINDER;

gridbag.setConstraints(btn6, c);

setSize(600, 300);

setVisible(true);

}

GridBagLayout: Cell Size Granting

A request for a cell height of n will be the minimum of n and the number of remaining

rows requested by gridwidth == REMAINDER

A request for a cell width of n will be the minimum of n and the number of remaining

columns requested by gridheight == REMAINDER

Denied Request

Only one row, so height can't be greater than one

GridBagHeightDenied()

{

// all height requests ignored

gridbag.setConstraints(btn1, c);

c.gridheight = 2;

gridbag.setConstraints(btn2, c);

c.gridheight = 3;

gridbag.setConstraints(btn3, c);

c.gridheight = 4;

gridbag.setConstraints(btn4, c);

c.gridheight = 5;

gridbag.setConstraints(btn5, c);

gridbag.setConstraints(btn6, c);

}

}

Feature Rich Universal DataBase Engine

Page 67: Integrated Database Environment With a Single Consistent Interface

Accepted Request

Accepted Request (2)

GridBagHeightAccepted(){ gridbag.setConstraints(btn1, c); c.gridheight = 2; gridbag.setConstraints(btn2, c); c.gridheight = 3; gridbag.setConstraints(btn3, c); // these all end rows c.gridheight = 1; c.gridwidth = GridBagConstraints.REMAINDER; gridbag.setConstraints(btn4, c); gridbag.setConstraints(btn5, c); gridbag.setConstraints(btn6, c);}

GridBaglayout: Resizing

weightx and weighty control resize behaviour

A weight of zero is no resize

Weights greater than zero resize proportionately

GridBaglayout: Fill

fill controls how a Component fills a space larger than its preferred size

values are NONE (default), HORIZONTAL, VERTICAL, BOTH

Feature Rich Universal DataBase Engine

Page 68: Integrated Database Environment With a Single Consistent Interface

GridBaglayout: Anchors

anchor controls where a Component is placed in a cell it doesn't fill

completely

Values are CENTER (default), NORTH, NORTHEAST, etc

A Complex Layout

A Complex Layout (2)

GridBagConstraints c = new GridBagConstraints(); c.weightx = 0.0; c.anchor = GridBagConstraints.EAST;

GridBagConstraints c2 = new GridBagConstraints(); c2.gridwidth = GridBagConstraints.REMAINDER; c2.weightx = 1.0; c2.fill = GridBagConstraints.HORIZONTAL;

gridbag.setConstraints(nameL, c);

Feature Rich Universal DataBase Engine

Page 69: Integrated Database Environment With a Single Consistent Interface

gridbag.setConstraints(nameT, c2); gridbag.setConstraints(phoneL, c); gridbag.setConstraints(phoneT, c2); gridbag.setConstraints(addressL, c); gridbag.setConstraints(addressT, c2);

CardLayout

CardLayout contains a set of ``cards'' only one of which is visible at any time Principal methods are first(Container)last(Container)next(Container)previous(Container)

CardLayout (2)

Flip through Btn1 - Btn4 circularly import java.awt.*;import java.awt.event.*;

public class TestCardLayout extends Frame implements ActionListener { public static void main(String argv[]) {

new TestCardLayout(); }

TestCardLayout() {

setLayout(new CardLayout());

addButton("1");

addButton("2");addButton("3");addButton("4");

setSize(200, 100);show();

}

protected void addButton(String key) {Button btn = new Button("Btn " + key);add(btn, key);btn.addActionListener(this);

}

Feature Rich Universal DataBase Engine

Page 70: Integrated Database Environment With a Single Consistent Interface

public void actionPerformed(ActionEvent e) {CardLayout card = (CardLayout) getLayout();

if (e.getActionCommand().equals("Btn 4")) { card.first(this);} else { card.next(this);}

}}

Building your own manager

LayoutManager is declared as an interface public interface LayoutManager { void addLayoutComponent(String name, Component comp); void removeLayoutComponent(Component comp); Dimension preferredLayoutSize(Container parent); Dimension minimumLayoutSize(Container parent); void layoutContainer(Container parent);}

Building your own manager

The following manager sets the size of its (single) child (ignoring insets): class SizeLayout implements LayoutManager { Dimension size;

public SizeLayout() { size = new Dimension(0, 0); }

public SizeLayout(Dimension s) { size = s; }

public void setSize(Dimension s) { size = new Dimension(s); }

public Dimension getSize() { return new Dimension(size); }

public void addLayoutComponent(String n, Component c) { }

Feature Rich Universal DataBase Engine

Page 71: Integrated Database Environment With a Single Consistent Interface

public void removeLayoutComponent(Component c) { }

public Dimension preferredLayoutSize(Container parent) { if (parent.countComponents() == 0) return new Dimension(width, height);

// use the first component added Component c = parent.getComponent(0); return c.preferredSize(); }

public Dimension minimumLayoutSize(Container parent) { if (parent.countComponents() == 0) return new Dimension(width, height);

// use the first component added Component c = parent.getComponent(0); return c.minimumSize(); }

public void layoutContainer(Container parent) { if (parent.countComponents() == 0) return;

// use the first component added Component c = parent.getComponent(0); c.setBounds(0, 0, size.width, size.height); c.validate(); }}

MENUS

Menus

All menu components are subclassed from MenuComponent (MenuBar, Menu, MenuItem, CheckboxMenuItem).

Menus are pulldown (1.0) or popup as well (1.1) Menus can be changed by the setMenu() of Frame. This unmaps the old menu

and maps the new one For applets, you need to walk up the window tree to find a Frame, just as with

Dialogs

Feature Rich Universal DataBase Engine

Page 72: Integrated Database Environment With a Single Consistent Interface

MenuBar

MenuBar provides a horizontal bar containing menu selections Pulldown menus hang from there It is added to Frame by Frame's method setMenu(MenuBar)

Menu

The default constructor Menu(String label)creates a non-tearable menu. The constructor Menu(String label, boolean tearOff)allows control of this

MenuItem and CheckboxMenuItem

MenuItem is an ordinary selection element A MenuItem with name ``-'' is a separator In Java 1.1 a constructor allows a ``hot-key'' to be associated with a MenuItem CheckboxMenuItem can be set to on or off

Menu Example

private void CreateMenu(){ MenuBar mb = new MenuBar(); Menu fileB = new Menu("File"); mb.add(fileB);

NewButton newB = new NewButton("New"); QuitButton quitB = new QuitButton("Quit"); fileB.add(newB); fileB.add(quitB); Menu editB = new Menu("Edit"); mb.add(editB); setMenuBar(mb);}

Menu selection handling

Feature Rich Universal DataBase Engine

Page 73: Integrated Database Environment With a Single Consistent Interface

Menu selection has changed to the delegation model too A click on MenuItem is handled by an ActionEvent listener

DIALOGS

Dialogs

Dialog has constructors Dialog(Frame parent,boolean modal);Dialog(Frame parent,String title,boolean modal)

About Dialog

public class About extends Frame { About() { Button btn = new Button("Popup about..."); add("Center", btn); addActionListener(new PopupDialog()); setSize(200, 200); setVisible(true); }}

About Dialog (2)

Feature Rich Universal DataBase Engine

Page 74: Integrated Database Environment With a Single Consistent Interface

class PopupDialog implements ActionListener { Dialog dialog = null;

public void actionPerformed(ActionEvent e) { if (dialog == null) { dialog = new Dialog((Frame)getParent(), "About ...", true); Button btn = new Button("Ok"); btn.addActionListener(new DownDialog()); Label label = new Label("About: Version 1.0, 1997"); dialog.add(btn, "South"); dialog.add(label, "Center"); dialog.setSize(200, 100); } dialog.setVisible(true); }}

About Dialog (3)

class DownDialog implements ActionListener {

public void actionPerformed(ActionEvent e) { e.getComponent().getParent().setVisible(false); }}

MISCELLANEOUS

Fonts

There are only a small number of fonts: "Dialog", "DialogInput", "SanSerif" (was "Helvetica"), "Serif" (was "TimesRoman"), "MonoSpaced (was "Courier"), "Symbol" Font styles are BOLD, ITALIC or PLAIN Font has one constructor Font(String name, int style, int pointsize)A font can be set in a Component by setFont() Label label = new Label("Hello World");Font font = new Font("Courier",

Font.ITALIC, 12);label.setFont(font);

Graphics

Drawing is done using a Graphics object within a Component such as Panel Drawing should be done within the paint() method of components

Feature Rich Universal DataBase Engine

Page 75: Integrated Database Environment With a Single Consistent Interface

public void paint(Graphics g) { g.drawLine(1,1, 100,100); g.setColor(new Color(Color.red)); g.drawLine(1, 200, 100, 100); }

Lightweight Objects

Lightweight objects are built purely in Java They have no native-code GUI object They have the same geometry model They have the same event handling model They are being used to develop the Java Foundation Classes THE JFC objects mirror the AWT objects Eventually, much of the native code stuff will disappear

Feature Rich Universal DataBase Engine

Page 76: Integrated Database Environment With a Single Consistent Interface

UML Diagrams:

Screens:

Feature Rich Universal DataBase Engine

Page 77: Integrated Database Environment With a Single Consistent Interface

TESTING

Testing is a process of executing a program with the indent of finding an error.

Testing is a crucial element of software quality assurance and presents ultimate

review of specification, design and coding.

System Testing is an important phase. Testing represents an interesting anomaly

for the software. Thus a series of testing are performed for the proposed system

before the system is ready for user acceptance testing.

A good test case is one that has a high probability of finding an as undiscovered

error. A successful test is one that uncovers an as undiscovered error.

Feature Rich Universal DataBase Engine

Page 78: Integrated Database Environment With a Single Consistent Interface

Testing Objectives

1. Testing is a process of executing a program with the intent of finding an

error

2. A good test case is one that has a probability of finding an as yet

undiscovered error

3. A successful test is one that uncovers an undiscovered error

Testing Principles

All tests should be traceable to end user requirements

Tests should be planned long before testing begins

Testing should begin on a small scale and progress towards testing in

large

Exhaustive testing is not possible

To be most effective testing should be conducted by a independent

third party

The primary objective for test case design is to derive a set of tests that has the highest

livelihood for uncovering defects in software. To accomplish this objective two

different categories of test case design techniques are used. They are

White-box testing.

Black-box testing.

White-box testing

White box testing focus on the program control structure. Test cases are

derived to ensure that all statements in the program have been executed at least once

during testing and that all logical conditions have been executed.

Feature Rich Universal DataBase Engine

Page 79: Integrated Database Environment With a Single Consistent Interface

Block-box testing

Black box testing is designed to validate functional requirements

without regard to the internal workings of a program. Black box testing mainly

focuses on the information domain of the software, deriving test cases by

partitioning input and output in a manner that provides through test coverage.

Incorrect and missing functions, interface errors, errors in data structures, error

in functional logic are the errors falling in this category.

Testing strategies

A strategy for software testing must accommodate low-level tests that are

necessary to verify that all small source code segment has been correctly implemented

as well as high-level tests that validate major system functions against customer

requirements.

Testing fundamentals

Testing is a process of executing program with the intent of finding error. A

good test case is one that has high probability of finding an undiscovered error. If

testing is conducted successfully it uncovers the errors in the software. Testing cannot

show the absence of defects, it can only show that software defects present.

Testing Information flow

Information flow for testing flows the pattern. Two class of input provided to

test the process. The software configuration includes a software requirements

specification, a design specification and source code.

Feature Rich Universal DataBase Engine

Page 80: Integrated Database Environment With a Single Consistent Interface

Test configuration includes test plan and test cases and test tools. Tests are

conducted and all the results are evaluated. That is test results are compared with

expected results. When erroneous data are uncovered, an error is implied and

debugging commences.

Unit testing

Unit testing is essential for the verification of the code produced during the

coding phase and hence the goal is to test the internal logic of the modules. Using the

detailed design description as a guide, important paths are tested to uncover errors

with in the boundary of the modules. These tests were carried out during the

programming stage itself. All units of Integrated Database Environment with a

Single Consistent Interface were successfully tested.

Integration testing

Integration testing focuses on unit tested modules and build the program

structure that is dictated by the design phase.

System testing:

System testing tests the integration of each module in the system. It also tests

to find discrepancies between the system and it’s original objective, current

specification and system documentation. The primary concern is the compatibility of

individual modules. Entire system is working properly or not will be tested here, and

specified path ODBC connection will correct or not, and giving output or not are

tested here these verifications and validations are done by giving input values to the

system and by comparing with expected output. Top-down testing implementing

here.

Feature Rich Universal DataBase Engine

Page 81: Integrated Database Environment With a Single Consistent Interface

Acceptance Testing:

This testing is done to verify the readiness of the system for the

implementation. Acceptance testing begins when the system is complete. It’s

purpose is to provide the end user with the confidence that the system is ready

for use.

It involves planning and execution of functional tests, performance tests and

stress tests in order to demonstrate that the implemented system satisfies its

requirements.

Tools to special importance during acceptance testing include:

Test coverage Analyzer – records the control paths followed for each test case.

Timing Analyzer – also called a profiler, reports the time spent in various

regions of the code are areas to concentrate on to improve system performance.

Coding standards – static analyzers and standard checkers are used to inspect

code for deviations from standards and guidelines.

Feature Rich Universal DataBase Engine

Page 82: Integrated Database Environment With a Single Consistent Interface

Test Cases

Test cases are derived to ensure that all statements in the program have been executed

at least once during testing and that all logical conditions have been executed.

Using White-Box testing methods, the software engineer can drive test cases that

Guarantee that logical decisions on their true and false sides.

Exercise all logical decisions on their true and false sides.

Execute all loops at their boundaries and with in their operational bounds.

Exercise internal data structure to assure their validity.

The test case specification for system testing has to be submitted for review before

system testing commences.

S No Test Case Action taken

1 Create a connection with wrong details and test it

Displays error message

2 Create a connection with correct details and test it

Displays Success message

3 Select a connection from the existing list Connected to that database

4 Execute SQL query in the test area Results should be displayed in JTable

5 Save all the SQL statements All the statements will be saved in .SQL file

6 Open existing SQL file All the statements will be displayed in the text area

7 Execute insert or update statements Statements will be executed successfully

8 Create a connection for MySQL database and use that database

It will be connected to that database

9 Test submitted within time Test index page displayed

10 Try to use commit option after the SQL statement

All the statements which are executed till now will be commited

11 Try to use rollback option SQL statements will be rolled

back

12 Try to use schema option All the schema information will

be displayed

13 Export the results Results will be saved in .csv file.

Feature Rich Universal DataBase Engine

Page 83: Integrated Database Environment With a Single Consistent Interface

Drives and Stubs: Since all procedures and functions that verify, validate inputs are

included in testing, no stub need to be written. The test cases are kept in file and

driver is written to read the test cases and invoke the test unit with the different test

cases.

Software testing is one element of a broader topic that is often referred to as a

verification and validation. Verification refers to the set of activities that refers to a

different set of activities that ensure the software has been built is traceable to

customer requirements.

Verification : “ Are we building the product right”

Validation : “Are we building the right product”

The definition of V&V encompasses many of the activities that we have

referred to as software quality assurance(SQA). The activities required to achieve it

may be viewed as a set of components.

Validation testing succeeds when the system functions according to the user

expectations.

Alpha test is conducted at the developer’s site. It is conducted in a

controlled environment.

Beta test is conducted at one or more customer sites by the end user

of the software.

Validation testing is the step where requirement established as apart of the

software requirements analysis are validated against the software meet all-

functional and behavioral performance requirements and the errors, which are

uncovered during the testing, are corrected. Form level and as well as field level

validations are performed in all the data entry screens.

Implementation

Feature Rich Universal DataBase Engine

Page 84: Integrated Database Environment With a Single Consistent Interface

The most crucial phase of any project is the implementation. This includes all

those activities that take place to convert from the old system to the new system. It

involves setting up of the system for use by the concerned end user. A successful

implementation involves a high level of interaction between the analyst, programmers

and the end user. The most common method of implementation is the phased

approach, which involves installation of the system concurrently with the existing

system. This has its advantage in that the normal activity carried out, as part of the

existing system is anyway hampered. The end users are provided with sufficient

documentation and adequate training in the form of demonstration/presentation in

order to familiarize with the system.

The working of the system was under observation for a period of two days

after implementation and it was found to the hassle free. The feedbacks from the users

are awaited.

CONCLUSION

“Integrated Database Environment with a Single Consistent Interface ” has

been developed after a detailed study of the existing manual system. After the

Feature Rich Universal DataBase Engine

Page 85: Integrated Database Environment With a Single Consistent Interface

completion of the coding of the projects, the developed application was tested on

different kinds of databases with different SQL statements to check the accuracy of

the data manipulation from single window and their associated outputs.

This software Tool is advantageous and highly useful, overcoming the

conventional techniques, which were not easy. More over, it takes lot of time to learn

how to use a console to each and every database and start working on it by executing

SQL statements. The software developed eradicates all those hurdles and easy to use

and satisfies all the necessary formalities. It has been developed with systematic

design principles confirming to the step of the system development life cycle. The

system has been modularly developed and implemented interrelation between the

modules and thereby overcoming the drawbacks of the manual system.

“Integrated Database Environment with a Single Consistent Interface”

provides the better GUI Universal database client to easily connect and work with any

kind of database. The software is user friendly for both the users and the

administrator.

User Manual

Running this application in any environment is quite easy. Since java is

platform independent it is very to port this application in different environments.

Copy the executable jar file and double click on it then automatically this tool will

start and open a new window. In this window the user can start working

Before start working in the application, the user has to create the connection

by selecting Configure option from File Menu and move to connections tabbed pane.

Click on the new connection icon for creating the new connection and enter the

Feature Rich Universal DataBase Engine

Page 86: Integrated Database Environment With a Single Consistent Interface

database specific parameters. This connection will be stored permanently and later on

the user can use this connection to connect to the database. In the same way the user

can click on edit, delete connection icons to edit the connection parameters and delete

the connection permanently.

Once the user chooses the connection and connection is established then the

user can start execute statements by writing the statements in Text Area provided in

the tool and clicking execute button. User can click on commit and rollback options

also to commit and rollback the statements.

The user can store the SQL statements what he has typed in Text Area by

selecting File---->Save option to store it in .SQL file. The user can export the results

by selecting export option from Query Menu. The application has been developed in a

user-friendly manner and it is very easy to use the application. The user can gain

acquaintance with the system easily.

BIBLIOGRAPHY

HTML Complete reference - Thomas A. Powell

JFC-Swing - Sun Press

Java Complete reference - Patric Naugthon, Herbert

Schildt

Software Engineering - Roger S.Pressman

Feature Rich Universal DataBase Engine

Page 87: Integrated Database Environment With a Single Consistent Interface

Feature Rich Universal DataBase Engine